branch_name
stringclasses 22
values | content
stringlengths 18
81.8M
| directory_id
stringlengths 40
40
| languages
listlengths 1
36
| num_files
int64 1
7.38k
| repo_language
stringclasses 151
values | repo_name
stringlengths 7
101
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep># SimplePortfolio
It is simple portfolio without using any external libraries.I have use only html5,css3 here.
|
be1136aa8c7d7b836dc3d2f9fc081a65747c5d9c
|
[
"Markdown"
] | 1 |
Markdown
|
dipamar/SimplePortfolio
|
5ab5ed4bfd0ffacd4eb881ef701b50726cf88aea
|
e488f4b31519853936d9340cc1a1d2ba9e817f11
|
refs/heads/master
|
<repo_name>H4mxa/movie-app<file_sep>/action/movie-data.js
const MovieData = [
{
id: '1',
name: '<NAME>',
releaseYear: 2008,
description:
'When the menace known as <NAME> emerges from his mysterious past, he wreaks havoc and chaos on the people of Gotham. The Dark Knight must accept one of the greatest psychological and physical tests of his ability to fight injustice.',
longDesc:
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
rating: 4.7,
genre: 'action, crime, drama',
image:
'https://images.unsplash.com/photo-1497124401559-3e75ec2ed794?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1470&q=80',
},
{
id: '2',
name: '<NAME>',
releaseYear: 2004,
description:
'A meek Hobbit from the Shire and eight companions set out on a journey to destroy the powerful One Ring and save Middle-earth from the Dark Lord Sauron.',
longDesc:
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
rating: 4.9,
genre: 'adventure, drama, fantasy',
image:
'https://images.unsplash.com/photo-1597515377435-abed237b6bd6?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80',
},
{
id: '3',
name: '<NAME>',
releaseYear: 1994,
description:
'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.',
longDesc:
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
rating: 4.8,
genre: 'drama',
image:
'https://images.unsplash.com/photo-1555400113-4961f30f68bb?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80',
},
];
const CATEGORY_DATA = [
{
id: '1',
name: 'Darama',
},
{
id: '2',
name: 'Music',
},
{
id: '3',
name: 'Adventure',
},
{
id: '4',
name: 'Historical',
},
{
id: '5',
name: 'Action',
},
];
export const getCategories = () => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(CATEGORY_DATA), 10);
});
};
export const getMovies = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(MovieData);
reject('Cannot fetch data!');
}, 0);
});
};
// this function will create our movie from movieCreateForm
export const createMovie = (createMovieForm) => {
return new Promise((resolve, reject) => {
MovieData.push(createMovieForm);
setTimeout(() => {
resolve(MovieData);
reject('Cannot create movie!');
}, 0);
});
};
export const getMovieById = (id) => {
return new Promise((resolve, reject) => {
const movieIndex = MovieData.findIndex((movie) => movie.id === id);
const movie = MovieData[movieIndex];
setTimeout(() => resolve(movie), 0);
});
};
<file_sep>/components/MovieList.jsx
import React, { Component } from 'react';
import Link from 'next/link';
class MovieList extends Component {
// shorten the description of movies list
shorten = (text, maxLength) => {
if (text && text.length > maxLength) {
return text.substr(0, 200) + '...';
}
return text;
};
renderMovies(movies) {
return movies.map((movie, idx) => (
<div key={idx} className="col-lg-4 col-md-6 mb-4 ">
<div className="card h-100 bg-dark text-white">
<Link href="/movies/[id]" as={`/movies/${movie.id}`}>
<a>
<img
className="card-img-top"
src={movie.image}
alt={movie.name}
/>
</a>
</Link>
<div className="card-body">
<h4 className="card-title ">
<Link href="/movies/[id]" as={`/movies/${movie.id}`}>
<a className="title">{movie.name}</a>
</Link>
</h4>
<p className="card-text desc">
{this.shorten(movie.description, 100)}
</p>
</div>
<div className="card-footer">
<small className="text-muted">{movie.rating}</small>
</div>
<style jsx>
{`
.title {
color: #00ff00;
}
.desc {
color: #00ffff;
}
`}
</style>
</div>
</div>
));
}
render() {
const { movies } = this.props;
return <React.Fragment>{this.renderMovies(movies)}</React.Fragment>;
}
}
export default MovieList;
<file_sep>/pages/movies/[id].js
import { useRouter } from 'next/router';
import { getMovieById } from '../../action/movie-data';
const Movies = (props) => {
const router = useRouter();
const { id } = router.query;
const { movie } = props;
return (
<div className="container">
<div className="jumbotron">
<h1 className="display-4">{movie.name}</h1>
<p className="lead">{movie.description}</p>
<hr className="my-4" />
<p>{movie.longDesc}</p>
<a className="btn btn-primary btn-lg" href="#" role="button">
Learn more
</a>
</div>
</div>
);
};
Movies.getInitialProps = async ({ query }) => {
const movie = await getMovieById(query.id);
return { movie };
};
export default Movies;
<file_sep>/pages/index.js
import React, { Component } from 'react';
// --------- Components -------------
import Navbar from '../components/Navbar';
import SideMenu from '../components/SideMenu';
import Carousel from '../components/Carouse';
import MovieList from '../components/MovieList';
// ---------- data ------------------
import { getMovies, getCategories } from '../action/movie-data';
const Home = (props) => {
return (
<div>
<div className="home-page">
<div className="container">
<div className="row">
<div className="col-lg-3">
<SideMenu categories={props.getAllCategories} />
</div>
<div className="col-lg-9">
<Carousel images={props.carouselImages} />
<div className="row">
<MovieList movies={props.movies} />
</div>
</div>
</div>
</div>
</div>
</div>
);
};
export default Home;
Home.getInitialProps = async () => {
const movies = await getMovies();
const getAllCategories = await getCategories();
const carouselImages = movies.map((movie) => ({
id: `image-${movie.id}`,
imageUrl: movie.image,
name: movie.name,
}));
return {
movies,
carouselImages,
getAllCategories,
};
};
// class Home extends Component {
// static async getInitialProps() {
// const movies = await getMovies();
// return {
// movies,
// };
// }
// // constructor() {
// // super();
// // this.state = {
// // movies: [],
// // errorMessage: '',
// // };
// // }
// // Is called only on Client (Browser)
// // componentDidMount() {
// // getMovies()
// // .then((movies) => {
// // this.setState({ movies });
// // })
// // .catch((error) => {
// // this.setState({ errorMessage: error });
// // });
// // }
// render() {
// const { movies } = this.props;
// return (
// <div>
// <div className="home-page">
// <div className="container">
// <div className="row">
// <div className="col-lg-3">
// <SideMenu />
// </div>
// <div className="col-lg-9">
// <Carousel />
// <div className="row">
// <MovieList movies={movies || []} />
// </div>
// </div>
// </div>
// </div>
// </div>
// <Footer />
// <style jsx>
// {`
// .home-page {
// padding-top: 80px;
// }
// `}
// </style>
// </div>
// );
// }
// }
// export default Home;
<file_sep>/components/SideMenu.jsx
import Model from './Model';
import MovieCreateForm from './MovieCreateForm';
import { createMovie } from '../action/movie-data';
const SideMenu = (props) => {
const { categories } = props;
const handleCreateMovie = (createMovieForm) => {
createMovie(createMovieForm).then((createMovieForm) => {
console.log(JSON.stringify(createMovieForm));
});
};
return (
<div>
<Model hasSubmit={false}>
<MovieCreateForm handleFormSubmit={handleCreateMovie} />
</Model>
<h1 className="my-4 text-white">Categories</h1>
{categories.map((category) => (
<div key={category.id} className="list-group ">
<a href="#" className="list-group-item bg-dark text-light">
{category.name}
</a>
</div>
))}
<style jsx>
{`
.list-group-item:hover {
text-decoration: none;
}
`}
</style>
</div>
);
};
export default SideMenu;
|
ea5e3ec07c57c0e0a7c4ffd08376a732136a73f7
|
[
"JavaScript"
] | 5 |
JavaScript
|
H4mxa/movie-app
|
7be54d16b0ab10bd46776b1d13538a082a3ecb2f
|
f8bc39d880524fdc9ad02cb08b4ce57e162730af
|
refs/heads/master
|
<file_sep>add wave *
run 5000 ns
<file_sep>library IEEE;
use IEEE.STD_LOGIC_1164.all;
USE ieee.numeric_std.all;
Entity changeSign is
GENERIC ( N : integer:=33);
Port(X: in std_logic_vector(N-1 downto 0);
Y: out std_logic_vector(N-1 downto 0));
end changeSign;
Architecture behavioural of changeSign is
signal notInput:std_logic_vector(N-1 downto 0);
signal temp: unsigned(N-1 downto 0);
begin
notInput<= NOT X;
temp<= unsigned(notInput) +1;
Y<= std_logic_vector(temp);
End behavioural;<file_sep>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
entity half_adder is
port ( a,b : in std_logic;
sum,cry: out std_logic
);
end half_adder;
architecture adder_arch of half_adder is
begin
sum <= a xor b;
cry <= a and b;
end adder_arch;<file_sep>analyze -f vhdl -lib WORK ../src/fpnormalize_fpnormalize.vhd
analyze -f vhdl -lib WORK ../src/fpround_fpround.vhd
analyze -f vhdl -lib WORK ../src/unpackfp_unpackfp.vhd
analyze -f vhdl -lib WORK ../src/packfp_packfp.vhd
analyze -f vhdl -lib WORK ../src/regIn_out.vhd
analyze -f vhdl -lib WORK ../src/regOut_Exp.vhd
analyze -f vhdl -lib WORK ../src/regOut_Sig.vhd
analyze -f vhdl -lib WORK ../src/regOut_Sign.vhd
analyze -f vhdl -lib WORK ../src/fpmul_stage1_struct.vhd
analyze -f vhdl -lib WORK ../src/fpmul_stage2_struct.vhd
analyze -f vhdl -lib WORK ../src/fpmul_stage3_struct.vhd
analyze -f vhdl -lib WORK ../src/fpmul_stage4_struct.vhd
analyze -f vhdl -lib WORK ../src/fpmul_pipeline.vhd
analyze -f vhdl -lib WORK ../src/changeSign.vhd
analyze -f vhdl -lib WORK ../src/daddaTree.vhd
analyze -f vhdl -lib WORK ../src/final_adder.vhd
analyze -f vhdl -lib WORK ../src/fullAdder.vhd
analyze -f vhdl -lib WORK ../src/half_adder.vhd
analyze -f vhdl -lib WORK ../src/MBE_radix4_fullyDaddaTree.vhd
analyze -f vhdl -lib WORK ../src/mux2to1_32bit.vhd
analyze -f vhdl -lib WORK ../src/mux4to1_36bit.vhd
analyze -f vhdl -lib WORK ../src/mux8to1_34bit.vhd
analyze -f vhdl -lib WORK ../src/mux8to1_35bit.vhd
analyze -f vhdl -lib WORK ../src/operand_generation.vhd
set power_preserve_rtl_hier_names true
elaborate FPmul -arch pipeline -lib WORK > ./output_report/elaborate.txt
uniquify
link
create_clock -name MY_CLK -period 1.78 clk
set_dont_touch_network MY_CLK
set_clock_uncertainty 0.07 [get_clocks MY_CLK]
set_input_delay 0.5 -max -clock MY_CLK [remove_from_collection [all_inputs] clk]
set_output_delay 0.5 -max -clock MY_CLK [all_outputs]
set OLOAD [load_of NangateOpenCellLibrary/BUF_X4/A]
set_load $OLOAD [all_outputs]
ungroup -all -flatten
compile
report_resources > ./output_report/repResources.txt
report_timing > ./output_report/reportTiming.txt
report_area > ./output_report/reportArea.txt
quit
<file_sep>//`timescale 1ns
module testbench ();
wire CLK_i;
wire [31:0] DATA_i;
wire [31:0] FP_Z_i;
clk_gen CG( .CLK(CLK_i));
data_maker SM(.CLK(CLK_i),
.DATA(DATA_i));
FPmul UUT( .clk(CLK_i),
.FP_A(DATA_i),
.FP_B(DATA_i),
.FP_Z(FP_Z_i));
data_sink DS(.CLK(CLK_i),
.FP_Z(FP_Z_i));
endmodule
<file_sep>#!/bin/bash
source /software/scripts/init_msim6.2g
rm -rf work
rm -f transcript
rm -f vsim.wlf
vlib work
vcom -93 -work ./work ../src/packfp_packfp.vhd
vcom -93 -work ./work ../src/fpround_fpround.vhd
vcom -93 -work ./work ../src/fpnormalize_fpnormalize.vhd
vcom -93 -work ./work ../src/unpackfp_unpackfp.vhd
vcom -93 -work ./work ../src/fpmul_stage1_struct.vhd
vcom -93 -work ./work ../src/fpmul_stage2_struct.vhd
vcom -93 -work ./work ../src/fpmul_stage3_struct.vhd
vcom -93 -work ./work ../src/fpmul_stage4_struct.vhd
vcom -93 -work ./work ../src/regIn_out.vhd
vcom -93 -work ./work ../src/regOut_Exp.vhd
vcom -93 -work ./work ../src/regOut_Sig.vhd
vcom -93 -work ./work ../src/regOut_Sign.vhd
vcom -93 -work ./work ../src/fpmul_pipeline.vhd
vcom -93 -work ./work ../src/changeSign.vhd
vcom -93 -work ./work ../src/daddaTree.vhd
vcom -93 -work ./work ../src/final_adder.vhd
vcom -93 -work ./work ../src/fullAdder.vhd
vcom -93 -work ./work ../src/half_adder.vhd
vcom -93 -work ./work ../src/MBE_radix4_fullyDaddaTree.vhd
vcom -93 -work ./work ../src/mux2to1_32bit.vhd
vcom -93 -work ./work ../src/mux4to1_36bit.vhd
vcom -93 -work ./work ../src/mux8to1_34bit.vhd
vcom -93 -work ./work ../src/mux8to1_35bit.vhd
vcom -93 -work ./work ../src/operand_generation.vhd
vcom -93 -work ./work ../tb/*.vhd
vlog -work ./work ../tb/*.v
vsim work.testbench
<file_sep>library IEEE;
use IEEE.STD_LOGIC_1164.all;
USE ieee.numeric_std.all;
entity mux4to1_36bit is
GENERIC ( N : integer:=36);
port(
selP_P: in std_logic_vector(1 downto 0);
Input_Z,Input_A,Input_mA,Input_m2A: in std_logic_vector(N-4 downto 0);
P_Pout: out std_logic_vector(N-1 downto 0));
end mux4to1_36bit;
Architecture behavioural of mux4to1_36bit is
signal pp: std_logic_vector(N-4 downto 0);
signal s_z: std_logic_vector(N-5 downto 0);
signal s: std_logic_vector(N-4 downto 0);
signal temp: std_logic_vector(N-4 downto 0);
begin
MUX:process (selP_P,Input_Z,Input_A,Input_mA,Input_m2A)
begin
case selP_P is
when "00" => pp <= Input_Z;
when "01" => pp <= Input_A;
when "10" => pp<= Input_m2A;
when "11" => pp <= Input_mA;
when others => pp <= Input_Z; --0
end case;
end process MUX;
--s_z<= (others => '0');
--s<= s_z & selP_P(1);
--temp<= std_logic_vector(unsigned(s)+unsigned(pp));
temp <= pp;
P_Pout<= not(selP_P(1))&selP_P(1)&selP_P(1)&temp;
end behavioural;
<file_sep>fileDiRiferimento='daddaTree_Layers_Graph.txt'
F=open(fileDiRiferimento, 'w')
s7='Layer:7\n'
F.write(s7)
first_string='|'
x=64
while x:
if x<11:
first_string+=' '+str(x-1)+'|'
else:
first_string+=str(x-1)+'|'
x=x-1
first_string=first_string+'\n'
F.write(first_string)
c1=0
c2=35
c=63
for r in range(17):
row='|'+' |'*(c-c2)+' *|'*(c2-c1+1)+' |'*(c1-0)+'R['+str(r)+']\n'
if r==0 or r==14:
c2=c2+1
elif r>0 and r<14:
c2=c2+2
c1=c1+2
F.write(row)
space='\n\n\n'
F.write(space)
s6='Layer:6\n'
F.write(s6)
first_string='|'
x=64
while x:
if x<11:
first_string+=' '+str(x-1)+'|'
else:
first_string+=str(x-1)+'|'
x=x-1
first_string=first_string+'\n'
F.write(first_string)
c1=0
c2=63
c=63
for r in range(13):
row='|'+' |'*(c-c2)+' *|'*(c2-c1+1)+' |'*(c1-0)+'R['+str(r)+']\n'
if r==1 or r==11:
c2=c2-1
elif r>1 and r<11:
c2=c2-2
c1=c1+2
F.write(row)
space='\n\n\n'
F.write(space)
s5='Layer:5\n'
F.write(s5)
first_string='|'
x=64
while x:
if x<11:
first_string+=' '+str(x-1)+'|'
else:
first_string+=str(x-1)+'|'
x=x-1
first_string=first_string+'\n'
F.write(first_string)
c1=0
c2=63
c=63
for r in range(9):
row='|'+' |'*(c-c2)+' *|'*(c2-c1+1)+' |'*(c1-0)+'R['+str(r)+']\n'
if r==1 or r==7:
c2=c2-1
elif r>1 and r<7:
c2=c2-2
c1=c1+2
F.write(row)
space='\n\n\n'
F.write(space)
s4='Layer:4\n'
F.write(s4)
first_string='|'
x=64
while x:
if x<11:
first_string+=' '+str(x-1)+'|'
else:
first_string+=str(x-1)+'|'
x=x-1
first_string=first_string+'\n'
F.write(first_string)
c1=0
c2=63
c=63
for r in range(6):
row='|'+' |'*(c-c2)+' *|'*(c2-c1+1)+' |'*(c1-0)+'R['+str(r)+']\n'
if r==1 or r==4:
c2=c2-1
elif r>1 and r<4:
c2=c2-2
c1=c1+2
F.write(row)
space='\n\n\n'
F.write(space)
s3='Layer:3\n'
F.write(s3)
first_string='|'
x=64
while x:
if x<11:
first_string+=' '+str(x-1)+'|'
else:
first_string+=str(x-1)+'|'
x=x-1
first_string=first_string+'\n'
F.write(first_string)
c1=0
c2=63
c=63
for r in range(4):
row='|'+' |'*(c-c2)+' *|'*(c2-c1+1)+' |'*(c1-0)+'R['+str(r)+']\n'
if r==1 or r==2:
c2=c2-1
c1=c1+2
F.write(row)
space='\n\n\n'
F.write(space)
s2='Layer:2\n'
F.write(s2)
first_string='|'
x=64
while x:
if x<11:
first_string+=' '+str(x-1)+'|'
else:
first_string+=str(x-1)+'|'
x=x-1
first_string=first_string+'\n'
F.write(first_string)
c1=0
c2=63
c=63
for r in range(3):
row='|'+' |'*(c-c2)+' *|'*(c2-c1+1)+' |'*(c1-0)+'R['+str(r)+']\n'
c1=c1+2
F.write(row)
space='\n\n\n'
F.write(space)
s1='Layer:1\n'
F.write(s1)
first_string='|'
x=64
while x:
if x<11:
first_string+=' '+str(x-1)+'|'
else:
first_string+=str(x-1)+'|'
x=x-1
first_string=first_string+'\n'
F.write(first_string)
c1=0
c2=63
c=63
for r in range(2):
row='|'+' |'*(c-c2)+' *|'*(c2-c1+1)+' |'*(c1-0)+'R['+str(r)+']\n'
c1=c1+2
F.write(row)
<file_sep>LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE ieee.numeric_std.all;
ENTITY regOut_Sig IS
GENERIC ( N : integer:=28);
PORT ( Clock,Load: IN STD_LOGIC;
datoInput: in std_logic_vector(N-1 downto 0);
datoOutput : OUT std_logic_vector(N-1 DOWNTO 0));
END regOut_Sig ;
ARCHITECTURE Behavior OF regOut_Sig IS
BEGIN
PROCESS (Clock)
BEGIN
IF (Clock'EVENT AND Clock = '1') THEN
IF (Load='1') THEN
datoOutput <= datoInput;
END IF;
END IF;
END PROCESS;
END Behavior;<file_sep>library IEEE;
Use IEEE. STD_LOGIC_1164.all;
entity fulladder IS
port (a,b,cin :in STD_LOGIC;
sum,carry : out STD_LOGIC);
end fulladder;
architecture FA_arch of fulladder is
signal s1,c1,c2 : STD_LOGIC;
component half_adder is
port (a,b :in STD_LOGIC;
sum,cry: out STD_LOGIC);
end component;
Begin
HA1: half_adder port map (a,b,s1,c1);
HA2: half_adder port map (s1,cin,sum,c2);
carry<= c1 or c2;
end FA_arch;<file_sep>library IEEE;
use IEEE.STD_LOGIC_1164.all;
USE ieee.numeric_std.all;
use std.textio.all;
Entity operand_generation is
GENERIC ( N : integer:=32);
Port( multiplicand, multiplier: in std_logic_vector(N-1 downto 0);
pp0:out std_logic_vector(N+3 downto 0);
pp1,pp2,pp3,pp4,pp5,pp6,pp7,pp8,pp9,pp10,pp11,pp12,pp13,pp14:out std_logic_vector(N+2 downto 0);
pp15:out std_logic_vector(N+1 downto 0);
pp16: out std_logic_vector(N-1 downto 0)
);
End operand_generation;
Architecture structural of operand_generation is
--declaration of the signal connection
signal Z,A,TwiceA,MinusA,MinusTwiceA: std_logic_vector(N downto 0);
signal Z_32bit: std_logic_vector(N-1 downto 0);
signal sel_pp0: std_logic_vector(1 downto 0);
signal sel_pp1,sel_pp2,sel_pp3,sel_pp4,sel_pp5,sel_pp6,sel_pp7,sel_pp8,sel_pp9,sel_pp10: std_logic_vector(2 downto 0);
signal sel_pp11,sel_pp12,sel_pp13,sel_pp14,sel_pp15: std_logic_vector(2 downto 0);
signal sel_pp16: std_logic;
--component declaration
Component changeSign is
GENERIC ( N : integer:=33);
Port(X: in std_logic_vector(N-1 downto 0);
Y: out std_logic_vector(N-1 downto 0));
end component;
Component mux4to1_36bit is
GENERIC ( N : integer:=36);
port(
selP_P: in std_logic_vector(1 downto 0);
Input_Z,Input_A,Input_mA,Input_m2A: in std_logic_vector(N-4 downto 0);
P_Pout: out std_logic_vector(N-1 downto 0));
end component;
Component mux2to1_32bit is
GENERIC ( N : integer:=32);
port(
selP_P: in std_logic;
Input_Z,Input_A: in std_logic_vector(N-1 downto 0);
P_Pout: out std_logic_vector(N-1 downto 0));
end component;
Component mux8to1_35bit is
GENERIC ( N : integer:=35);
port(
selP_P: in std_logic_vector(2 downto 0);
Input_Z,Input_A,Input_2A,Input_mA,Input_m2A: in std_logic_vector(N-3 downto 0);
P_Pout: out std_logic_vector(N-1 downto 0));
end component;
Component mux8to1_34bit is
GENERIC ( N : integer:=34);
port(
selP_P: in std_logic_vector(2 downto 0);
Input_Z,Input_A,Input_2A,Input_mA,Input_m2A: in std_logic_vector(N-2 downto 0);
P_Pout: out std_logic_vector(N-1 downto 0));
end component;
Begin
Z<= (others => '0');
Z_32bit<= (others => '0');
A<='0'& multiplicand;
TwiceA<=multiplicand&'0';
Minus_A: changeSign Port Map(A,MinusA);
Minus_2A: changeSign Port Map(TwiceA,MinusTwiceA);
sel_pp0<= multiplier(1 downto 0);
sel_pp1<= multiplier(3 downto 1);
sel_pp2<= multiplier(5 downto 3);
sel_pp3<= multiplier(7 downto 5);
sel_pp4<= multiplier(9 downto 7);
sel_pp5<= multiplier(11 downto 9);
sel_pp6<= multiplier(13 downto 11);
sel_pp7<= multiplier(15 downto 13);
sel_pp8<= multiplier(17 downto 15);
sel_pp9<= multiplier(19 downto 17);
sel_pp10<= multiplier(21 downto 19);
sel_pp11<= multiplier(23 downto 21);
sel_pp12<= multiplier(25 downto 23);
sel_pp13<= multiplier(27 downto 25);
sel_pp14<= multiplier(29 downto 27);
sel_pp15<= multiplier(31 downto 29);
sel_pp16<= multiplier(31);
First_Mux: mux4to1_36bit Port Map(sel_pp0,Z,A,MinusA,MinusTwiceA,pp0);
Muxs_2: mux8to1_35bit port map(sel_pp1,Z,A,TwiceA,MinusA,MinusTwiceA,pp1);
Muxs_3: mux8to1_35bit port map(sel_pp2,Z,A,TwiceA,MinusA,MinusTwiceA,pp2);
Muxs_4: mux8to1_35bit port map(sel_pp3,Z,A,TwiceA,MinusA,MinusTwiceA,pp3);
Muxs_5: mux8to1_35bit port map(sel_pp4,Z,A,TwiceA,MinusA,MinusTwiceA,pp4);
Muxs_6: mux8to1_35bit port map(sel_pp5,Z,A,TwiceA,MinusA,MinusTwiceA,pp5);
Muxs_7: mux8to1_35bit port map(sel_pp6,Z,A,TwiceA,MinusA,MinusTwiceA,pp6);
Muxs_8: mux8to1_35bit port map(sel_pp7,Z,A,TwiceA,MinusA,MinusTwiceA,pp7);
Muxs_9: mux8to1_35bit port map(sel_pp8,Z,A,TwiceA,MinusA,MinusTwiceA,pp8);
Muxs_10: mux8to1_35bit port map(sel_pp9,Z,A,TwiceA,MinusA,MinusTwiceA,pp9);
Muxs_11: mux8to1_35bit port map(sel_pp10,Z,A,TwiceA,MinusA,MinusTwiceA,pp10);
Muxs_12: mux8to1_35bit port map(sel_pp11,Z,A,TwiceA,MinusA,MinusTwiceA,pp11);
Muxs_13: mux8to1_35bit port map(sel_pp12,Z,A,TwiceA,MinusA,MinusTwiceA,pp12);
Muxs_14: mux8to1_35bit port map(sel_pp13,Z,A,TwiceA,MinusA,MinusTwiceA,pp13);
Muxs_15: mux8to1_35bit port map(sel_pp14,Z,A,TwiceA,MinusA,MinusTwiceA,pp14);
Muxs_16: mux8to1_34bit port map(sel_pp15,Z,A,TwiceA,MinusA,MinusTwiceA,pp15);
Last_Mux_17: mux2to1_32bit Port Map(sel_pp16,Z_32bit,multiplicand,pp16);
End Structural;
<file_sep>add wave *
run 145 ns
<file_sep>library IEEE;
use IEEE.STD_LOGIC_1164.all;
USE ieee.numeric_std.all;
entity mux8to1_34bit is
GENERIC ( N : integer:=34);
port(
selP_P: in std_logic_vector(2 downto 0);
Input_Z,Input_A,Input_2A,Input_mA,Input_m2A: in std_logic_vector(N-2 downto 0);
P_Pout: out std_logic_vector(N-1 downto 0));
end mux8to1_34bit;
Architecture behavioural of mux8to1_34bit is
signal pp: std_logic_vector(N-2 downto 0);
signal sign: std_logic;
begin
MUX:process (selP_P,Input_Z,Input_A,Input_mA,Input_m2A,Input_2A)
begin
sign<= selP_P(2);
case selP_P is
when "000" =>
pp <= Input_Z; --0
when "001" =>
pp <= Input_A; --A
when "010" =>
pp<= Input_A; --A
when "011" =>
pp <= Input_2A; --2A
when "100" =>
pp <= Input_m2A; -- -2A
when "101" =>
pp <= Input_mA; -- -A
when "110" =>
pp <= Input_mA; -- -A
when "111" =>
pp <= Input_Z; -- 0
sign <= '0';
when others =>
pp <= Input_Z; --0
end case;
end process MUX;
P_Pout<= not(sign)&pp;
end behavioural;
<file_sep>LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE ieee.numeric_std.all;
ENTITY final_adder IS
GENERIC ( N : integer:=64);
PORT (Add_first,Add_second: IN std_logic_vector(N-1 DOWNTO 0);
outSum: out std_logic_vector(N-1 downto 0));
END final_adder;
ARCHITECTURE Behavior OF final_adder is
signal temp: unsigned(N-1 downto 0);
begin
temp<= unsigned(Add_first) + unsigned(Add_second);
outSum<=std_logic_vector(temp);
end Behavior;<file_sep>LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE ieee.numeric_std.all;
Entity daddaTree is
GENERIC ( N : integer:=32);
Port( pp0: in std_logic_vector(N+3 downto 0);
pp1,pp2,pp3,pp4,pp5,pp6,pp7,pp8,pp9,pp10,pp11,pp12,pp13,pp14: in std_logic_vector(N+2 downto 0);
pp15: in std_logic_vector(N+1 downto 0);
pp16: in std_logic_vector(N-1 downto 0);
f_add1,f_add2: out std_logic_vector((2*N-1) downto 0)
);
End daddaTree;
Architecture structural of daddaTree is
type vector_6 is array (43 downto 0) of std_logic;
type vector_5 is array (51 downto 0) of std_logic;
type vector_4 is array (57 downto 0) of std_logic;
type vector_3 is array (61 downto 0) of std_logic;
type vector_2 is array (63 downto 0) of std_logic;
type vector_1 is array (64 downto 0) of std_logic;
type matrix_6 is array (0 to 12) of vector_6;
type matrix_5 is array (0 to 8) of vector_5;
type matrix_4 is array (0 to 5) of vector_4;
type matrix_3 is array (0 to 4) of vector_3;
type matrix_2 is array (0 to 2) of vector_2;
type matrix_1 is array (0 to 1) of vector_1;
signal layer_6: matrix_6;
signal layer_5: matrix_5;
signal layer_4: matrix_4;
signal layer_3: matrix_3;
signal layer_2: matrix_2;
signal layer_1: matrix_1:=(others => (others=>'0'));
Component half_adder is
port ( a,b : in std_logic;
sum,cry: out std_logic
);
end Component;
Component fulladder IS
port (a,b,cin :in STD_LOGIC;
sum,carry : out STD_LOGIC);
end Component;
Begin
--layer7: FA&HA to generate layer6
--column26
HA1: half_adder port map(pp0(26),pp1(24),layer_6(0)(26),layer_6(0)(27));
--column27
FA1: fulladder port map(pp0(27),pp1(25),pp2(23),layer_6(1)(27),layer_6(0)(28));
--column28
FA2: fulladder port map(pp0(28),pp1(26),pp2(24),layer_6(1)(28),layer_6(0)(29));
HA2: half_adder port map(pp3(22),pp4(20),layer_6(2)(28),layer_6(1)(29));
--column29
FA3: fulladder port map(pp0(29),pp1(27),pp2(25),layer_6(2)(29),layer_6(0)(30));
FA4: fulladder port map(pp3(23),pp4(21),pp5(19),layer_6(3)(29),layer_6(1)(30));
--column30
FA5: fulladder port map(pp0(30),pp1(28),pp2(26),layer_6(2)(30),layer_6(0)(31));
FA6: fulladder port map(pp3(24),pp4(22),pp5(20),layer_6(3)(30),layer_6(1)(31));
HA3: half_adder port map(pp6(18),pp7(16),layer_6(4)(30),layer_6(2)(31));
--column31
FA7: fulladder port map(pp0(31),pp1(29),pp2(27),layer_6(3)(31),layer_6(0)(32));
FA8: fulladder port map(pp3(25),pp4(23),pp5(21),layer_6(4)(31),layer_6(1)(32));
FA9: fulladder port map(pp6(19),pp7(17),pp8(15),layer_6(5)(31),layer_6(2)(32));
--column32
FA10: fulladder port map(pp0(32),pp1(30),pp2(28),layer_6(3)(32),layer_6(0)(33));
FA11: fulladder port map(pp3(26),pp4(24),pp5(22),layer_6(4)(32),layer_6(1)(33));
FA12: fulladder port map(pp6(20),pp7(18),pp8(16),layer_6(5)(32),layer_6(2)(33));
HA4: half_adder port map(pp9(14),pp10(12),layer_6(6)(32),layer_6(3)(33));
--column33
FA13: fulladder port map(pp0(33),pp1(31),pp2(29),layer_6(4)(33),layer_6(0)(34));
FA14: fulladder port map(pp3(27),pp4(25),pp5(23),layer_6(5)(33),layer_6(1)(34));
FA15: fulladder port map(pp6(21),pp7(19),pp8(17),layer_6(6)(33),layer_6(2)(34));
FA16: fulladder port map(pp9(15),pp10(13),pp11(11),layer_6(7)(33),layer_6(3)(34));
--column34
FA17: fulladder port map(pp0(34),pp1(32),pp2(30),layer_6(4)(34),layer_6(0)(35));
FA18: fulladder port map(pp3(28),pp4(26),pp5(24),layer_6(5)(34),layer_6(1)(35));
FA19: fulladder port map(pp6(22),pp7(20),pp8(18),layer_6(6)(34),layer_6(2)(35));
FA20: fulladder port map(pp9(16),pp10(14),pp11(12),layer_6(7)(34),layer_6(3)(35));
--column35
FA21: fulladder port map(pp0(35),pp1(33),pp2(31),layer_6(4)(35),layer_6(0)(36));
FA22: fulladder port map(pp3(29),pp4(27),pp5(25),layer_6(5)(35),layer_6(1)(36));
FA23: fulladder port map(pp6(23),pp7(21),pp8(19),layer_6(6)(35),layer_6(2)(36));
FA24: fulladder port map(pp9(17),pp10(15),pp11(13),layer_6(7)(35),layer_6(3)(36));
--column36
FA25: fulladder port map(pp1(34),pp2(32),pp3(30),layer_6(4)(36),layer_6(0)(37));
FA26: fulladder port map(pp4(28),pp5(26),pp6(24),layer_6(5)(36),layer_6(1)(37));
FA27: fulladder port map(pp7(22),pp8(20),pp9(18),layer_6(6)(36),layer_6(2)(37));
HA5: half_adder port map(pp10(16),pp11(14),layer_6(7)(36),layer_6(3)(37));
--column37
FA28: fulladder port map(pp2(33),pp3(31),pp4(29),layer_6(4)(37),layer_6(0)(38));
FA29: fulladder port map(pp5(27),pp6(25),pp7(23),layer_6(5)(37),layer_6(1)(38));
FA30: fulladder port map(pp8(21),pp9(19),pp10(17),layer_6(6)(37),layer_6(2)(38));
--column38
FA31: fulladder port map(pp2(34),pp3(32),pp4(30),layer_6(3)(38),layer_6(0)(39));
FA32: fulladder port map(pp5(28),pp6(26),pp7(24),layer_6(4)(38),layer_6(1)(39));
HA6: half_adder port map(pp8(22),pp9(20),layer_6(5)(38),layer_6(2)(39));
--column39
FA33: fulladder port map(pp3(33),pp4(31),pp5(29),layer_6(3)(39),layer_6(0)(40));
FA34: fulladder port map(pp6(27),pp7(25),pp8(23),layer_6(4)(39),layer_6(1)(40));
--column40
FA35: fulladder port map(pp3(34),pp4(32),pp5(30),layer_6(2)(40),layer_6(0)(41));
HA7: half_adder port map(pp6(28),pp7(26),layer_6(3)(40),layer_6(1)(41));
--column41
FA36: fulladder port map(pp4(33),pp5(31),pp6(29),layer_6(2)(41),layer_6(0)(42));
--column42
HA8: half_adder port map(pp4(34),pp5(32),layer_6(1)(42),layer_6(0)(43));
--layer6: FA&HA to generate layer5
--column18
HA9: half_adder port map(pp0(18),pp1(16),layer_5(0)(18),layer_5(0)(19));
--column19
FA37: fulladder port map(pp0(19),pp1(17),pp2(15),layer_5(1)(19),layer_5(0)(20));
--column20
FA38: fulladder port map(pp0(20),pp1(18),pp2(16),layer_5(1)(20),layer_5(0)(21));
HA10: half_adder port map(pp3(14),pp4(12),layer_5(2)(20),layer_5(1)(21));
--column21
FA39: fulladder port map(pp0(21),pp1(19),pp2(17),layer_5(2)(21),layer_5(0)(22));
FA40: fulladder port map(pp3(15),pp4(13),pp5(11),layer_5(3)(21),layer_5(1)(22));
--column22
FA41: fulladder port map(pp0(22),pp1(20),pp2(18),layer_5(2)(22),layer_5(0)(23));
FA42: fulladder port map(pp3(16),pp4(14),pp5(12),layer_5(3)(22),layer_5(1)(23));
HA11: half_adder port map(pp6(10),pp7(8),layer_5(4)(22),layer_5(2)(23));
--column23
FA43: fulladder port map(pp0(23),pp1(21),pp2(19),layer_5(3)(23),layer_5(0)(24));
FA44: fulladder port map(pp3(17),pp4(15),pp5(13),layer_5(4)(23),layer_5(1)(24));
FA45: fulladder port map(pp6(11),pp7(9),pp8(7),layer_5(5)(23),layer_5(2)(24));
--column24
FA46: fulladder port map(pp0(24),pp1(22),pp2(20),layer_5(3)(24),layer_5(0)(25));
FA47: fulladder port map(pp3(18),pp4(16),pp5(14),layer_5(4)(24),layer_5(1)(25));
FA48: fulladder port map(pp6(12),pp7(10),pp8(8),layer_5(5)(24),layer_5(2)(25));
HA12: half_adder port map(pp9(6),pp10(4),layer_5(6)(24),layer_5(3)(25));
--column25
FA49: fulladder port map(pp0(25),pp1(23),pp2(21),layer_5(4)(25),layer_5(0)(26));
FA50: fulladder port map(pp3(19),pp4(17),pp5(15),layer_5(5)(25),layer_5(1)(26));
FA51: fulladder port map(pp6(13),pp7(11),pp8(9),layer_5(6)(25),layer_5(2)(26));
FA52: fulladder port map(pp9(7),pp10(5),pp11(3),layer_5(7)(25),layer_5(3)(26));
--column26
FA53: fulladder port map(layer_6(0)(26),pp2(22),pp3(20),layer_5(4)(26),layer_5(0)(27));
FA54: fulladder port map(pp4(18),pp5(16),pp6(14),layer_5(5)(26),layer_5(1)(27));
FA55: fulladder port map(pp7(12),pp8(10),pp9(8),layer_5(6)(26),layer_5(2)(27));
FA56: fulladder port map(pp10(6),pp11(4),pp12(2),layer_5(7)(26),layer_5(3)(27));
--column27
FA57: fulladder port map(layer_6(0)(27),layer_6(1)(27),pp3(21),layer_5(4)(27),layer_5(0)(28));
FA58: fulladder port map(pp4(19),pp5(17),pp6(15),layer_5(5)(27),layer_5(1)(28));
FA59: fulladder port map(pp7(13),pp8(11),pp9(9),layer_5(6)(27),layer_5(2)(28));
FA60: fulladder port map(pp10(7),pp11(5),pp12(3),layer_5(7)(27),layer_5(3)(28));
--column28
FA61: fulladder port map(layer_6(0)(28),layer_6(1)(28),layer_6(2)(28),layer_5(4)(28),layer_5(0)(29));
FA62: fulladder port map(pp5(18),pp6(16),pp7(14),layer_5(5)(28),layer_5(1)(29));
FA63: fulladder port map(pp8(12),pp9(10),pp10(8),layer_5(6)(28),layer_5(2)(29));
FA64: fulladder port map(pp11(6),pp12(4),pp13(2),layer_5(7)(28),layer_5(3)(29));
--column29
FA65: fulladder port map(layer_6(0)(29),layer_6(1)(29),layer_6(2)(29),layer_5(4)(29),layer_5(0)(30));
FA66: fulladder port map(layer_6(3)(29),pp6(17),pp7(15),layer_5(5)(29),layer_5(1)(30));
FA67: fulladder port map(pp8(13),pp9(11),pp10(9),layer_5(6)(29),layer_5(2)(30));
FA68: fulladder port map(pp11(7),pp12(5),pp13(3),layer_5(7)(29),layer_5(3)(30));
--column30
FA69: fulladder port map(layer_6(0)(30),layer_6(1)(30),layer_6(2)(30),layer_5(4)(30),layer_5(0)(31));
FA70: fulladder port map(layer_6(3)(30),layer_6(4)(30),pp8(14),layer_5(5)(30),layer_5(1)(31));
FA71: fulladder port map(pp9(12),pp10(10),pp11(8),layer_5(6)(30),layer_5(2)(31));
FA72: fulladder port map(pp12(6),pp13(4),pp14(2),layer_5(7)(30),layer_5(3)(31));
--column31
FA73: fulladder port map(layer_6(0)(31),layer_6(1)(31),layer_6(2)(31),layer_5(4)(31),layer_5(0)(32));
FA74: fulladder port map(layer_6(3)(31),layer_6(4)(31),layer_6(5)(31),layer_5(5)(31),layer_5(1)(32));
FA75: fulladder port map(pp9(13),pp10(11),pp11(9),layer_5(6)(31),layer_5(2)(32));
FA76: fulladder port map(pp12(7),pp13(5),pp14(3),layer_5(7)(31),layer_5(3)(32));
--column32
FA77: fulladder port map(layer_6(0)(32),layer_6(1)(32),layer_6(2)(32),layer_5(4)(32),layer_5(0)(33));
FA78: fulladder port map(layer_6(3)(32),layer_6(4)(32),layer_6(5)(32),layer_5(5)(32),layer_5(1)(33));
FA79: fulladder port map(layer_6(6)(32),pp11(10),pp12(8),layer_5(6)(32),layer_5(2)(33));
FA80: fulladder port map(pp13(6),pp14(4),pp15(2),layer_5(7)(32),layer_5(3)(33));
--column33
FA81: fulladder port map(layer_6(0)(33),layer_6(1)(33),layer_6(2)(33),layer_5(4)(33),layer_5(0)(34));
FA82: fulladder port map(layer_6(3)(33),layer_6(4)(33),layer_6(5)(33),layer_5(5)(33),layer_5(1)(34));
FA83: fulladder port map(layer_6(6)(33),layer_6(7)(33),pp12(9),layer_5(6)(33),layer_5(2)(34));
FA84: fulladder port map(pp13(7),pp14(5),pp15(3),layer_5(7)(33),layer_5(3)(34));
--column34
FA85: fulladder port map(layer_6(0)(34),layer_6(1)(34),layer_6(2)(34),layer_5(4)(34),layer_5(0)(35));
FA86: fulladder port map(layer_6(3)(34),layer_6(4)(34),layer_6(5)(34),layer_5(5)(34),layer_5(1)(35));
FA87: fulladder port map(layer_6(6)(34),layer_6(7)(34),pp12(10),layer_5(6)(34),layer_5(2)(35));
FA88: fulladder port map(pp13(8),pp14(6),pp15(4),layer_5(7)(34),layer_5(3)(35));
--column35
FA89: fulladder port map(layer_6(0)(35),layer_6(1)(35),layer_6(2)(35),layer_5(4)(35),layer_5(0)(36));
FA90: fulladder port map(layer_6(3)(35),layer_6(4)(35),layer_6(5)(35),layer_5(5)(35),layer_5(1)(36));
FA91: fulladder port map(layer_6(6)(35),layer_6(7)(35),pp12(11),layer_5(6)(35),layer_5(2)(36));
FA92: fulladder port map(pp13(9),pp14(7),pp15(5),layer_5(7)(35),layer_5(3)(36));
--column36
FA93: fulladder port map(layer_6(0)(36),layer_6(1)(36),layer_6(2)(36),layer_5(4)(36),layer_5(0)(37));
FA94: fulladder port map(layer_6(3)(36),layer_6(4)(36),layer_6(5)(36),layer_5(5)(36),layer_5(1)(37));
FA95: fulladder port map(layer_6(6)(36),layer_6(7)(36),pp12(12),layer_5(6)(36),layer_5(2)(37));
FA96: fulladder port map(pp13(10),pp14(8),pp15(6),layer_5(7)(36),layer_5(3)(37));
--column37
FA97: fulladder port map(layer_6(0)(37),layer_6(1)(37),layer_6(2)(37),layer_5(4)(37),layer_5(0)(38));
FA98: fulladder port map(layer_6(3)(37),layer_6(4)(37),layer_6(5)(37),layer_5(5)(37),layer_5(1)(38));
FA99: fulladder port map(layer_6(6)(37),pp11(15),pp12(13),layer_5(6)(37),layer_5(2)(38));
FA100: fulladder port map(pp13(11),pp14(9),pp15(7),layer_5(7)(37),layer_5(3)(38));
--column38
FA101: fulladder port map(layer_6(0)(38),layer_6(1)(38),layer_6(2)(38),layer_5(4)(38),layer_5(0)(39));
FA102: fulladder port map(layer_6(3)(38),layer_6(4)(38),layer_6(5)(38),layer_5(5)(38),layer_5(1)(39));
FA103: fulladder port map(pp10(18),pp11(16),pp12(14),layer_5(6)(38),layer_5(2)(39));
FA104: fulladder port map(pp13(12),pp14(10),pp15(8),layer_5(7)(38),layer_5(3)(39));
--column39
FA105: fulladder port map(layer_6(0)(39),layer_6(1)(39),layer_6(2)(39),layer_5(4)(39),layer_5(0)(40));
FA106: fulladder port map(layer_6(3)(39),layer_6(4)(39),pp9(21),layer_5(5)(39),layer_5(1)(40));
FA107: fulladder port map(pp10(19),pp11(17),pp12(15),layer_5(6)(39),layer_5(2)(40));
FA108: fulladder port map(pp13(13),pp14(11),pp15(9),layer_5(7)(39),layer_5(3)(40));
--column40
FA109: fulladder port map(layer_6(0)(40),layer_6(1)(40),layer_6(2)(40),layer_5(4)(40),layer_5(0)(41));
FA110: fulladder port map(layer_6(3)(40),pp8(24),pp9(22),layer_5(5)(40),layer_5(1)(41));
FA111: fulladder port map(pp10(20),pp11(18),pp12(16),layer_5(6)(40),layer_5(2)(41));
FA112: fulladder port map(pp13(14),pp14(12),pp15(10),layer_5(7)(40),layer_5(3)(41));
--column41
FA113: fulladder port map(layer_6(0)(41),layer_6(1)(41),layer_6(2)(41),layer_5(4)(41),layer_5(0)(42));
FA114: fulladder port map(pp7(27),pp8(25),pp9(23),layer_5(5)(41),layer_5(1)(42));
FA115: fulladder port map(pp10(21),pp11(19),pp12(17),layer_5(6)(41),layer_5(2)(42));
FA116: fulladder port map(pp13(15),pp14(13),pp15(11),layer_5(7)(41),layer_5(3)(42));
--column42
FA117: fulladder port map(layer_6(0)(42),layer_6(1)(42),pp6(30),layer_5(4)(42),layer_5(0)(43));
FA118: fulladder port map(pp7(28),pp8(26),pp9(24),layer_5(5)(42),layer_5(1)(43));
FA119: fulladder port map(pp10(22),pp11(20),pp12(18),layer_5(6)(42),layer_5(2)(43));
FA120: fulladder port map(pp13(16),pp14(14),pp15(12),layer_5(7)(42),layer_5(3)(43));
--column43
FA121: fulladder port map(layer_6(0)(43),pp5(33),pp6(31),layer_5(4)(43),layer_5(0)(44));
FA122: fulladder port map(pp7(29),pp8(27),pp9(25),layer_5(5)(43),layer_5(1)(44));
FA123: fulladder port map(pp10(23),pp11(21),pp12(19),layer_5(6)(43),layer_5(2)(44));
FA124: fulladder port map(pp13(17),pp14(15),pp15(13),layer_5(7)(43),layer_5(3)(44));
--column44
FA125: fulladder port map(pp5(34),pp6(32),pp7(30),layer_5(4)(44),layer_5(0)(45));
FA126: fulladder port map(pp8(28),pp9(26),pp10(24),layer_5(5)(44),layer_5(1)(45));
FA127: fulladder port map(pp11(22),pp12(20),pp13(18),layer_5(6)(44),layer_5(2)(45));
HA13: half_adder port map(pp14(16),pp15(14),layer_5(7)(44),layer_5(3)(45));
--column45
FA128: fulladder port map(pp6(33),pp7(31),pp8(29),layer_5(4)(45),layer_5(0)(46));
FA129: fulladder port map(pp9(27),pp10(25),pp11(23),layer_5(5)(45),layer_5(1)(46));
FA130: fulladder port map(pp12(21),pp13(19),pp14(17),layer_5(6)(45),layer_5(2)(46));
--column46
FA131: fulladder port map(pp6(34),pp7(32),pp8(30),layer_5(3)(46),layer_5(0)(47));
FA132: fulladder port map(pp9(28),pp10(26),pp11(24),layer_5(4)(46),layer_5(1)(47));
HA14: half_adder port map(pp12(22),pp13(20),layer_5(5)(46),layer_5(2)(47));
--column47
FA133: fulladder port map(pp7(33),pp8(31),pp9(29),layer_5(3)(47),layer_5(0)(48));
FA134: fulladder port map(pp10(27),pp11(25),pp12(23),layer_5(4)(47),layer_5(1)(48));
--column48
FA135: fulladder port map(pp7(34),pp8(32),pp9(30),layer_5(2)(48),layer_5(0)(49));
HA15: half_adder port map(pp10(28),pp11(26),layer_5(3)(48),layer_5(1)(49));
--column49
FA136: fulladder port map(pp8(33),pp9(31),pp10(29),layer_5(2)(49),layer_5(0)(50));
--column50
HA16: half_adder port map(pp8(34),pp9(32),layer_5(1)(50),layer_5(0)(51));
--layer5: FA&HA to generate layer4
--column12
HA17: half_adder port map(pp0(12),pp1(10),layer_4(0)(12),layer_4(0)(13));
--column13
FA137: fulladder port map(pp0(13),pp1(11),pp2(9),layer_4(1)(13),layer_4(0)(14));
--column14
FA138: fulladder port map(pp0(14),pp1(12),pp2(10),layer_4(1)(14),layer_4(0)(15));
HA18: half_adder port map(pp3(8),pp4(6),layer_4(2)(14),layer_4(1)(15));
--column15
FA139: fulladder port map(pp0(15),pp1(13),pp2(11),layer_4(2)(15),layer_4(0)(16));
FA140: fulladder port map(pp3(9),pp4(7),pp5(5),layer_4(3)(15),layer_4(1)(16));
--column16
FA141: fulladder port map(pp0(16),pp1(14),pp2(12),layer_4(2)(16),layer_4(0)(17));
FA142: fulladder port map(pp3(10),pp4(8),pp5(6),layer_4(3)(16),layer_4(1)(17));
HA19: half_adder port map(pp6(4),pp7(2),layer_4(4)(16),layer_4(2)(17));
--column17
FA143: fulladder port map(pp0(17),pp1(15),pp2(13),layer_4(3)(17),layer_4(0)(18));
FA144: fulladder port map(pp3(11),pp4(9),pp5(7),layer_4(4)(17),layer_4(1)(18));
FA145: fulladder port map(pp6(5),pp7(3),pp8(1),layer_4(5)(17),layer_4(2)(18));
--column18
FA146: fulladder port map(layer_5(0)(18),pp2(14),pp3(12),layer_4(3)(18),layer_4(0)(19));
FA147: fulladder port map(pp4(10),pp5(8),pp6(6),layer_4(4)(18),layer_4(1)(19));
FA148: fulladder port map(pp7(4),pp8(2),pp9(0),layer_4(5)(18),layer_4(2)(19));
--column19
FA149: fulladder port map(layer_5(0)(19),layer_5(1)(19),pp3(13),layer_4(3)(19),layer_4(0)(20));
FA150: fulladder port map(pp4(11),pp5(9),pp6(7),layer_4(4)(19),layer_4(1)(20));
FA151: fulladder port map(pp7(5),pp8(3),pp9(1),layer_4(5)(19),layer_4(2)(20));
--column20
FA152: fulladder port map(layer_5(0)(20),layer_5(1)(20),layer_5(2)(20),layer_4(3)(20),layer_4(0)(21));
FA153: fulladder port map(pp5(10),pp6(8),pp7(6),layer_4(4)(20),layer_4(1)(21));
FA154: fulladder port map(pp8(4),pp9(2),pp10(0),layer_4(5)(20),layer_4(2)(21));
--column21
FA155: fulladder port map(layer_5(0)(21),layer_5(1)(21),layer_5(2)(21),layer_4(3)(21),layer_4(0)(22));
FA156: fulladder port map(layer_5(3)(21),pp6(9),pp7(7),layer_4(4)(21),layer_4(1)(22));
FA157: fulladder port map(pp8(5),pp9(3),pp10(1),layer_4(5)(21),layer_4(2)(22));
--column22
FA158: fulladder port map(layer_5(0)(22),layer_5(1)(22),layer_5(2)(22),layer_4(3)(22),layer_4(0)(23));
FA159: fulladder port map(layer_5(3)(22),layer_5(4)(22),pp8(6),layer_4(4)(22),layer_4(1)(23));
FA160: fulladder port map(pp9(4),pp10(2),pp11(0),layer_4(5)(22),layer_4(2)(23));
--column23
FA161: fulladder port map(layer_5(0)(23),layer_5(1)(23),layer_5(2)(23),layer_4(3)(23),layer_4(0)(24));
FA162: fulladder port map(layer_5(3)(23),layer_5(4)(23),layer_5(5)(23),layer_4(4)(23),layer_4(1)(24));
FA163: fulladder port map(pp9(5),pp10(3),pp11(1),layer_4(5)(23),layer_4(2)(24));
--column24
FA164: fulladder port map(layer_5(0)(24),layer_5(1)(24),layer_5(2)(24),layer_4(3)(24),layer_4(0)(25));
FA165: fulladder port map(layer_5(3)(24),layer_5(4)(24),layer_5(5)(24),layer_4(4)(24),layer_4(1)(25));
FA166: fulladder port map(layer_5(6)(24),pp11(2),pp12(0),layer_4(5)(24),layer_4(2)(25));
--column25
FA167: fulladder port map(layer_5(0)(25),layer_5(1)(25),layer_5(2)(25),layer_4(3)(25),layer_4(0)(26));
FA168: fulladder port map(layer_5(3)(25),layer_5(4)(25),layer_5(5)(25),layer_4(4)(25),layer_4(1)(26));
FA169: fulladder port map(layer_5(6)(25),layer_5(7)(25),pp12(1),layer_4(5)(25),layer_4(2)(26));
--column26
FA170: fulladder port map(layer_5(0)(26),layer_5(1)(26),layer_5(2)(26),layer_4(3)(26),layer_4(0)(27));
FA171: fulladder port map(layer_5(3)(26),layer_5(4)(26),layer_5(5)(26),layer_4(4)(26),layer_4(1)(27));
FA172: fulladder port map(layer_5(6)(26),layer_5(7)(26),pp13(0),layer_4(5)(26),layer_4(2)(27));
--column27
FA173: fulladder port map(layer_5(0)(27),layer_5(1)(27),layer_5(2)(27),layer_4(3)(27),layer_4(0)(28));
FA174: fulladder port map(layer_5(3)(27),layer_5(4)(27),layer_5(5)(27),layer_4(4)(27),layer_4(1)(28));
FA175: fulladder port map(layer_5(6)(27),layer_5(7)(27),pp13(1),layer_4(5)(27),layer_4(2)(28));
--column28
FA176: fulladder port map(layer_5(0)(28),layer_5(1)(28),layer_5(2)(28),layer_4(3)(28),layer_4(0)(29));
FA177: fulladder port map(layer_5(3)(28),layer_5(4)(28),layer_5(5)(28),layer_4(4)(28),layer_4(1)(29));
FA178: fulladder port map(layer_5(6)(28),layer_5(7)(28),pp14(0),layer_4(5)(28),layer_4(2)(29));
--column29
FA179: fulladder port map(layer_5(0)(29),layer_5(1)(29),layer_5(2)(29),layer_4(3)(29),layer_4(0)(30));
FA180: fulladder port map(layer_5(3)(29),layer_5(4)(29),layer_5(5)(29),layer_4(4)(29),layer_4(1)(30));
FA181: fulladder port map(layer_5(6)(29),layer_5(7)(29),pp14(1),layer_4(5)(29),layer_4(2)(30));
--column30
FA182: fulladder port map(layer_5(0)(30),layer_5(1)(30),layer_5(2)(30),layer_4(3)(30),layer_4(0)(31));
FA183: fulladder port map(layer_5(3)(30),layer_5(4)(30),layer_5(5)(30),layer_4(4)(30),layer_4(1)(31));
FA184: fulladder port map(layer_5(6)(30),layer_5(7)(30),pp15(0),layer_4(5)(30),layer_4(2)(31));
--column31
FA185: fulladder port map(layer_5(0)(31),layer_5(1)(31),layer_5(2)(31),layer_4(3)(31),layer_4(0)(32));
FA186: fulladder port map(layer_5(3)(31),layer_5(4)(31),layer_5(5)(31),layer_4(4)(31),layer_4(1)(32));
FA187: fulladder port map(layer_5(6)(31),layer_5(7)(31),pp15(1),layer_4(5)(31),layer_4(2)(32));
--column32
FA188: fulladder port map(layer_5(0)(32),layer_5(1)(32),layer_5(2)(32),layer_4(3)(32),layer_4(0)(33));
FA189: fulladder port map(layer_5(3)(32),layer_5(4)(32),layer_5(5)(32),layer_4(4)(32),layer_4(1)(33));
FA190: fulladder port map(layer_5(6)(32),layer_5(7)(32),pp16(0),layer_4(5)(32),layer_4(2)(33));
--column33
FA191: fulladder port map(layer_5(0)(33),layer_5(1)(33),layer_5(2)(33),layer_4(3)(33),layer_4(0)(34));
FA192: fulladder port map(layer_5(3)(33),layer_5(4)(33),layer_5(5)(33),layer_4(4)(33),layer_4(1)(34));
FA193: fulladder port map(layer_5(6)(33),layer_5(7)(33),pp16(1),layer_4(5)(33),layer_4(2)(34));
--column34
FA194: fulladder port map(layer_5(0)(34),layer_5(1)(34),layer_5(2)(34),layer_4(3)(34),layer_4(0)(35));
FA195: fulladder port map(layer_5(3)(34),layer_5(4)(34),layer_5(5)(34),layer_4(4)(34),layer_4(1)(35));
FA196: fulladder port map(layer_5(6)(34),layer_5(7)(34),pp16(2),layer_4(5)(34),layer_4(2)(35));
--column35
FA197: fulladder port map(layer_5(0)(35),layer_5(1)(35),layer_5(2)(35),layer_4(3)(35),layer_4(0)(36));
FA198: fulladder port map(layer_5(3)(35),layer_5(4)(35),layer_5(5)(35),layer_4(4)(35),layer_4(1)(36));
FA199: fulladder port map(layer_5(6)(35),layer_5(7)(35),pp16(3),layer_4(5)(35),layer_4(2)(36));
--column36
FA200: fulladder port map(layer_5(0)(36),layer_5(1)(36),layer_5(2)(36),layer_4(3)(36),layer_4(0)(37));
FA201: fulladder port map(layer_5(3)(36),layer_5(4)(36),layer_5(5)(36),layer_4(4)(36),layer_4(1)(37));
FA202: fulladder port map(layer_5(6)(36),layer_5(7)(36),pp16(4),layer_4(5)(36),layer_4(2)(37));
--column37
FA203: fulladder port map(layer_5(0)(37),layer_5(1)(37),layer_5(2)(37),layer_4(3)(37),layer_4(0)(38));
FA204: fulladder port map(layer_5(3)(37),layer_5(4)(37),layer_5(5)(37),layer_4(4)(37),layer_4(1)(38));
FA205: fulladder port map(layer_5(6)(37),layer_5(7)(37),pp16(5),layer_4(5)(37),layer_4(2)(38));
--column38
FA206: fulladder port map(layer_5(0)(38),layer_5(1)(38),layer_5(2)(38),layer_4(3)(38),layer_4(0)(39));
FA207: fulladder port map(layer_5(3)(38),layer_5(4)(38),layer_5(5)(38),layer_4(4)(38),layer_4(1)(39));
FA208: fulladder port map(layer_5(6)(38),layer_5(7)(38),pp16(6),layer_4(5)(38),layer_4(2)(39));
--column39
FA209: fulladder port map(layer_5(0)(39),layer_5(1)(39),layer_5(2)(39),layer_4(3)(39),layer_4(0)(40));
FA210: fulladder port map(layer_5(3)(39),layer_5(4)(39),layer_5(5)(39),layer_4(4)(39),layer_4(1)(40));
FA211: fulladder port map(layer_5(6)(39),layer_5(7)(39),pp16(7),layer_4(5)(39),layer_4(2)(40));
--column40
FA212: fulladder port map(layer_5(0)(40),layer_5(1)(40),layer_5(2)(40),layer_4(3)(40),layer_4(0)(41));
FA213: fulladder port map(layer_5(3)(40),layer_5(4)(40),layer_5(5)(40),layer_4(4)(40),layer_4(1)(41));
FA214: fulladder port map(layer_5(6)(40),layer_5(7)(40),pp16(8),layer_4(5)(40),layer_4(2)(41));
--column41
FA215: fulladder port map(layer_5(0)(41),layer_5(1)(41),layer_5(2)(41),layer_4(3)(41),layer_4(0)(42));
FA216: fulladder port map(layer_5(3)(41),layer_5(4)(41),layer_5(5)(41),layer_4(4)(41),layer_4(1)(42));
FA217: fulladder port map(layer_5(6)(41),layer_5(7)(41),pp16(9),layer_4(5)(41),layer_4(2)(42));
--column42
FA218: fulladder port map(layer_5(0)(42),layer_5(1)(42),layer_5(2)(42),layer_4(3)(42),layer_4(0)(43));
FA219: fulladder port map(layer_5(3)(42),layer_5(4)(42),layer_5(5)(42),layer_4(4)(42),layer_4(1)(43));
FA220: fulladder port map(layer_5(6)(42),layer_5(7)(42),pp16(10),layer_4(5)(42),layer_4(2)(43));
--column43
FA221: fulladder port map(layer_5(0)(43),layer_5(1)(43),layer_5(2)(43),layer_4(3)(43),layer_4(0)(44));
FA222: fulladder port map(layer_5(3)(43),layer_5(4)(43),layer_5(5)(43),layer_4(4)(43),layer_4(1)(44));
FA223: fulladder port map(layer_5(6)(43),layer_5(7)(43),pp16(11),layer_4(5)(43),layer_4(2)(44));
--column44
FA224: fulladder port map(layer_5(0)(44),layer_5(1)(44),layer_5(2)(44),layer_4(3)(44),layer_4(0)(45));
FA225: fulladder port map(layer_5(3)(44),layer_5(4)(44),layer_5(5)(44),layer_4(4)(44),layer_4(1)(45));
FA226: fulladder port map(layer_5(6)(44),layer_5(7)(44),pp16(12),layer_4(5)(44),layer_4(2)(45));
--column45
FA227: fulladder port map(layer_5(0)(45),layer_5(1)(45),layer_5(2)(45),layer_4(3)(45),layer_4(0)(46));
FA228: fulladder port map(layer_5(3)(45),layer_5(4)(45),layer_5(5)(45),layer_4(4)(45),layer_4(1)(46));
FA229: fulladder port map(layer_5(6)(45),pp15(15),pp16(13),layer_4(5)(45),layer_4(2)(46));
--column46
FA230: fulladder port map(layer_5(0)(46),layer_5(1)(46),layer_5(2)(46),layer_4(3)(46),layer_4(0)(47));
FA231: fulladder port map(layer_5(3)(46),layer_5(4)(46),layer_5(5)(46),layer_4(4)(46),layer_4(1)(47));
FA232: fulladder port map(pp14(18),pp15(16),pp16(14),layer_4(5)(46),layer_4(2)(47));
--column47
FA233: fulladder port map(layer_5(0)(47),layer_5(1)(47),layer_5(2)(47),layer_4(3)(47),layer_4(0)(48));
FA234: fulladder port map(layer_5(3)(47),layer_5(4)(47),pp13(21),layer_4(4)(47),layer_4(1)(48));
FA235: fulladder port map(pp14(19),pp15(17),pp16(15),layer_4(5)(47),layer_4(2)(48));
--column48
FA236: fulladder port map(layer_5(0)(48),layer_5(1)(48),layer_5(2)(48),layer_4(3)(48),layer_4(0)(49));
FA237: fulladder port map(layer_5(3)(48),pp12(24),pp13(22),layer_4(4)(48),layer_4(1)(49));
FA238: fulladder port map(pp14(20),pp15(18),pp16(16),layer_4(5)(48),layer_4(2)(49));
--column49
FA239: fulladder port map(layer_5(0)(49),layer_5(1)(49),layer_5(2)(49),layer_4(3)(49),layer_4(0)(50));
FA240: fulladder port map(pp11(27),pp12(25),pp13(23),layer_4(4)(49),layer_4(1)(50));
FA241: fulladder port map(pp14(21),pp15(19),pp16(17),layer_4(5)(49),layer_4(2)(50));
--column50
FA242: fulladder port map(layer_5(0)(50),layer_5(1)(50),pp10(30),layer_4(3)(50),layer_4(0)(51));
FA243: fulladder port map(pp11(28),pp12(26),pp13(24),layer_4(4)(50),layer_4(1)(51));
FA244: fulladder port map(pp14(22),pp15(20),pp16(18),layer_4(5)(50),layer_4(2)(51));
--column51
FA245: fulladder port map(layer_5(0)(51),pp9(33),pp10(31),layer_4(3)(51),layer_4(0)(52));
FA246: fulladder port map(pp11(29),pp12(27),pp13(25),layer_4(4)(51),layer_4(1)(52));
FA247: fulladder port map(pp14(23),pp15(21),pp16(19),layer_4(5)(51),layer_4(2)(52));
--column52
FA248: fulladder port map(pp9(34),pp10(32),pp11(30),layer_4(3)(52),layer_4(0)(53));
FA249: fulladder port map(pp12(28),pp13(26),pp14(24),layer_4(4)(52),layer_4(1)(53));
HA20: half_adder port map(pp15(22),pp16(20),layer_4(5)(52),layer_4(2)(53));
--column53
FA250: fulladder port map(pp10(33),pp11(31),pp12(29),layer_4(3)(53),layer_4(0)(54));
FA251: fulladder port map(pp13(27),pp14(25),pp15(23),layer_4(4)(53),layer_4(1)(54));
--column54
FA252: fulladder port map(pp10(34),pp11(32),pp12(30),layer_4(2)(54),layer_4(0)(55));
HA21: half_adder port map(pp13(28),pp14(26),layer_4(3)(54),layer_4(1)(55));
--column55
FA253: fulladder port map(pp11(33),pp12(31),pp13(29),layer_4(2)(55),layer_4(0)(56));
--column56
HA22: half_adder port map(pp11(34),pp12(32),layer_4(1)(56),layer_4(0)(57));
--layer4: FA&HA to generate layer3
--column8
HA23: half_adder port map(pp0(8),pp1(6),layer_3(0)(8),layer_3(0)(9));
--column9
FA254: fulladder port map(pp0(9),pp1(7),pp2(5),layer_3(1)(9),layer_3(0)(10));
--column10
FA255: fulladder port map(pp0(10),pp1(8),pp2(6),layer_3(1)(10),layer_3(0)(11));
HA24: half_adder port map(pp3(4),pp4(2),layer_3(2)(10),layer_3(1)(11));
--column11
FA256: fulladder port map(pp0(11),pp1(9),pp2(7),layer_3(2)(11),layer_3(0)(12));
FA257: fulladder port map(pp3(5),pp4(3),pp5(1),layer_3(3)(11),layer_3(1)(12));
--column12
FA258: fulladder port map(layer_4(0)(12),pp2(8),pp3(6),layer_3(2)(12),layer_3(0)(13));
FA259: fulladder port map(pp4(4),pp5(2),pp6(0),layer_3(3)(12),layer_3(1)(13));
--column13
FA260: fulladder port map(layer_4(0)(13),layer_4(1)(13),pp3(7),layer_3(2)(13),layer_3(0)(14));
FA261: fulladder port map(pp4(5),pp5(3),pp6(1),layer_3(3)(13),layer_3(1)(14));
--column14
FA262: fulladder port map(layer_4(0)(14),layer_4(1)(14),layer_4(2)(14),layer_3(2)(14),layer_3(0)(15));
FA263: fulladder port map(pp5(4),pp6(2),pp7(0),layer_3(3)(14),layer_3(1)(15));
--column15
FA264: fulladder port map(layer_4(0)(15),layer_4(1)(15),layer_4(2)(15),layer_3(2)(15),layer_3(0)(16));
FA265: fulladder port map(layer_4(3)(15),pp6(3),pp7(1),layer_3(3)(15),layer_3(1)(16));
--column16
FA266: fulladder port map(layer_4(0)(16),layer_4(1)(16),layer_4(2)(16),layer_3(2)(16),layer_3(0)(17));
FA267: fulladder port map(layer_4(3)(16),layer_4(4)(16),pp8(0),layer_3(3)(16),layer_3(1)(17));
--column17
FA268: fulladder port map(layer_4(0)(17),layer_4(1)(17),layer_4(2)(17),layer_3(2)(17),layer_3(0)(18));
FA269: fulladder port map(layer_4(3)(17),layer_4(4)(17),layer_4(5)(17),layer_3(3)(17),layer_3(1)(18));
--column18
FA270: fulladder port map(layer_4(0)(18),layer_4(1)(18),layer_4(2)(18),layer_3(2)(18),layer_3(0)(19));
FA271: fulladder port map(layer_4(3)(18),layer_4(4)(18),layer_4(5)(18),layer_3(3)(18),layer_3(1)(19));
--column19
FA272: fulladder port map(layer_4(0)(19),layer_4(1)(19),layer_4(2)(19),layer_3(2)(19),layer_3(0)(20));
FA273: fulladder port map(layer_4(3)(19),layer_4(4)(19),layer_4(5)(19),layer_3(3)(19),layer_3(1)(20));
--column20
FA274: fulladder port map(layer_4(0)(20),layer_4(1)(20),layer_4(2)(20),layer_3(2)(20),layer_3(0)(21));
FA275: fulladder port map(layer_4(3)(20),layer_4(4)(20),layer_4(5)(20),layer_3(3)(20),layer_3(1)(21));
--column21
FA276: fulladder port map(layer_4(0)(21),layer_4(1)(21),layer_4(2)(21),layer_3(2)(21),layer_3(0)(22));
FA277: fulladder port map(layer_4(3)(21),layer_4(4)(21),layer_4(5)(21),layer_3(3)(21),layer_3(1)(22));
--column22
FA278: fulladder port map(layer_4(0)(22),layer_4(1)(22),layer_4(2)(22),layer_3(2)(22),layer_3(0)(23));
FA279: fulladder port map(layer_4(3)(22),layer_4(4)(22),layer_4(5)(22),layer_3(3)(22),layer_3(1)(23));
--column23
FA280: fulladder port map(layer_4(0)(23),layer_4(1)(23),layer_4(2)(23),layer_3(2)(23),layer_3(0)(24));
FA281: fulladder port map(layer_4(3)(23),layer_4(4)(23),layer_4(5)(23),layer_3(3)(23),layer_3(1)(24));
--column24
FA282: fulladder port map(layer_4(0)(24),layer_4(1)(24),layer_4(2)(24),layer_3(2)(24),layer_3(0)(25));
FA283: fulladder port map(layer_4(3)(24),layer_4(4)(24),layer_4(5)(24),layer_3(3)(24),layer_3(1)(25));
--column25
FA284: fulladder port map(layer_4(0)(25),layer_4(1)(25),layer_4(2)(25),layer_3(2)(25),layer_3(0)(26));
FA285: fulladder port map(layer_4(3)(25),layer_4(4)(25),layer_4(5)(25),layer_3(3)(25),layer_3(1)(26));
--column26
FA286: fulladder port map(layer_4(0)(26),layer_4(1)(26),layer_4(2)(26),layer_3(2)(26),layer_3(0)(27));
FA287: fulladder port map(layer_4(3)(26),layer_4(4)(26),layer_4(5)(26),layer_3(3)(26),layer_3(1)(27));
--column27
FA288: fulladder port map(layer_4(0)(27),layer_4(1)(27),layer_4(2)(27),layer_3(2)(27),layer_3(0)(28));
FA289: fulladder port map(layer_4(3)(27),layer_4(4)(27),layer_4(5)(27),layer_3(3)(27),layer_3(1)(28));
--column28
FA290: fulladder port map(layer_4(0)(28),layer_4(1)(28),layer_4(2)(28),layer_3(2)(28),layer_3(0)(29));
FA291: fulladder port map(layer_4(3)(28),layer_4(4)(28),layer_4(5)(28),layer_3(3)(28),layer_3(1)(29));
--column29
FA292: fulladder port map(layer_4(0)(29),layer_4(1)(29),layer_4(2)(29),layer_3(2)(29),layer_3(0)(30));
FA293: fulladder port map(layer_4(3)(29),layer_4(4)(29),layer_4(5)(29),layer_3(3)(29),layer_3(1)(30));
--column30
FA294: fulladder port map(layer_4(0)(30),layer_4(1)(30),layer_4(2)(30),layer_3(2)(30),layer_3(0)(31));
FA295: fulladder port map(layer_4(3)(30),layer_4(4)(30),layer_4(5)(30),layer_3(3)(30),layer_3(1)(31));
--column31
FA296: fulladder port map(layer_4(0)(31),layer_4(1)(31),layer_4(2)(31),layer_3(2)(31),layer_3(0)(32));
FA297: fulladder port map(layer_4(3)(31),layer_4(4)(31),layer_4(5)(31),layer_3(3)(31),layer_3(1)(32));
--column32
FA298: fulladder port map(layer_4(0)(32),layer_4(1)(32),layer_4(2)(32),layer_3(2)(32),layer_3(0)(33));
FA299: fulladder port map(layer_4(3)(32),layer_4(4)(32),layer_4(5)(32),layer_3(3)(32),layer_3(1)(33));
--column33
FA300: fulladder port map(layer_4(0)(33),layer_4(1)(33),layer_4(2)(33),layer_3(2)(33),layer_3(0)(34));
FA301: fulladder port map(layer_4(3)(33),layer_4(4)(33),layer_4(5)(33),layer_3(3)(33),layer_3(1)(34));
--column34
FA302: fulladder port map(layer_4(0)(34),layer_4(1)(34),layer_4(2)(34),layer_3(2)(34),layer_3(0)(35));
FA303: fulladder port map(layer_4(3)(34),layer_4(4)(34),layer_4(5)(34),layer_3(3)(34),layer_3(1)(35));
--column35
FA304: fulladder port map(layer_4(0)(35),layer_4(1)(35),layer_4(2)(35),layer_3(2)(35),layer_3(0)(36));
FA305: fulladder port map(layer_4(3)(35),layer_4(4)(35),layer_4(5)(35),layer_3(3)(35),layer_3(1)(36));
--column36
FA306: fulladder port map(layer_4(0)(36),layer_4(1)(36),layer_4(2)(36),layer_3(2)(36),layer_3(0)(37));
FA307: fulladder port map(layer_4(3)(36),layer_4(4)(36),layer_4(5)(36),layer_3(3)(36),layer_3(1)(37));
--column37
FA308: fulladder port map(layer_4(0)(37),layer_4(1)(37),layer_4(2)(37),layer_3(2)(37),layer_3(0)(38));
FA309: fulladder port map(layer_4(3)(37),layer_4(4)(37),layer_4(5)(37),layer_3(3)(37),layer_3(1)(38));
--column38
FA310: fulladder port map(layer_4(0)(38),layer_4(1)(38),layer_4(2)(38),layer_3(2)(38),layer_3(0)(39));
FA311: fulladder port map(layer_4(3)(38),layer_4(4)(38),layer_4(5)(38),layer_3(3)(38),layer_3(1)(39));
--column39
FA312: fulladder port map(layer_4(0)(39),layer_4(1)(39),layer_4(2)(39),layer_3(2)(39),layer_3(0)(40));
FA313: fulladder port map(layer_4(3)(39),layer_4(4)(39),layer_4(5)(39),layer_3(3)(39),layer_3(1)(40));
--column40
FA314: fulladder port map(layer_4(0)(40),layer_4(1)(40),layer_4(2)(40),layer_3(2)(40),layer_3(0)(41));
FA315: fulladder port map(layer_4(3)(40),layer_4(4)(40),layer_4(5)(40),layer_3(3)(40),layer_3(1)(41));
--column41
FA316: fulladder port map(layer_4(0)(41),layer_4(1)(41),layer_4(2)(41),layer_3(2)(41),layer_3(0)(42));
FA317: fulladder port map(layer_4(3)(41),layer_4(4)(41),layer_4(5)(41),layer_3(3)(41),layer_3(1)(42));
--column42
FA318: fulladder port map(layer_4(0)(42),layer_4(1)(42),layer_4(2)(42),layer_3(2)(42),layer_3(0)(43));
FA319: fulladder port map(layer_4(3)(42),layer_4(4)(42),layer_4(5)(42),layer_3(3)(42),layer_3(1)(43));
--column43
FA320: fulladder port map(layer_4(0)(43),layer_4(1)(43),layer_4(2)(43),layer_3(2)(43),layer_3(0)(44));
FA321: fulladder port map(layer_4(3)(43),layer_4(4)(43),layer_4(5)(43),layer_3(3)(43),layer_3(1)(44));
--column44
FA322: fulladder port map(layer_4(0)(44),layer_4(1)(44),layer_4(2)(44),layer_3(2)(44),layer_3(0)(45));
FA323: fulladder port map(layer_4(3)(44),layer_4(4)(44),layer_4(5)(44),layer_3(3)(44),layer_3(1)(45));
--column45
FA324: fulladder port map(layer_4(0)(45),layer_4(1)(45),layer_4(2)(45),layer_3(2)(45),layer_3(0)(46));
FA325: fulladder port map(layer_4(3)(45),layer_4(4)(45),layer_4(5)(45),layer_3(3)(45),layer_3(1)(46));
--column46
FA326: fulladder port map(layer_4(0)(46),layer_4(1)(46),layer_4(2)(46),layer_3(2)(46),layer_3(0)(47));
FA327: fulladder port map(layer_4(3)(46),layer_4(4)(46),layer_4(5)(46),layer_3(3)(46),layer_3(1)(47));
--column47
FA328: fulladder port map(layer_4(0)(47),layer_4(1)(47),layer_4(2)(47),layer_3(2)(47),layer_3(0)(48));
FA329: fulladder port map(layer_4(3)(47),layer_4(4)(47),layer_4(5)(47),layer_3(3)(47),layer_3(1)(48));
--column48
FA330: fulladder port map(layer_4(0)(48),layer_4(1)(48),layer_4(2)(48),layer_3(2)(48),layer_3(0)(49));
FA331: fulladder port map(layer_4(3)(48),layer_4(4)(48),layer_4(5)(48),layer_3(3)(48),layer_3(1)(49));
--column49
FA332: fulladder port map(layer_4(0)(49),layer_4(1)(49),layer_4(2)(49),layer_3(2)(49),layer_3(0)(50));
FA333: fulladder port map(layer_4(3)(49),layer_4(4)(49),layer_4(5)(49),layer_3(3)(49),layer_3(1)(50));
--column50
FA334: fulladder port map(layer_4(0)(50),layer_4(1)(50),layer_4(2)(50),layer_3(2)(50),layer_3(0)(51));
FA335: fulladder port map(layer_4(3)(50),layer_4(4)(50),layer_4(5)(50),layer_3(3)(50),layer_3(1)(51));
--column51
FA336: fulladder port map(layer_4(0)(51),layer_4(1)(51),layer_4(2)(51),layer_3(2)(51),layer_3(0)(52));
FA337: fulladder port map(layer_4(3)(51),layer_4(4)(51),layer_4(5)(51),layer_3(3)(51),layer_3(1)(52));
--column52
FA338: fulladder port map(layer_4(0)(52),layer_4(1)(52),layer_4(2)(52),layer_3(2)(52),layer_3(0)(53));
FA339: fulladder port map(layer_4(3)(52),layer_4(4)(52),layer_4(5)(52),layer_3(3)(52),layer_3(1)(53));
--column53
FA340: fulladder port map(layer_4(0)(53),layer_4(1)(53),layer_4(2)(53),layer_3(2)(53),layer_3(0)(54));
FA341: fulladder port map(layer_4(3)(53),layer_4(4)(53),pp16(21),layer_3(3)(53),layer_3(1)(54));
--column54
FA342: fulladder port map(layer_4(0)(54),layer_4(1)(54),layer_4(2)(54),layer_3(2)(54),layer_3(0)(55));
FA343: fulladder port map(layer_4(3)(54),pp15(24),pp16(22),layer_3(3)(54),layer_3(1)(55));
--column55
FA344: fulladder port map(layer_4(0)(55),layer_4(1)(55),layer_4(2)(55),layer_3(2)(55),layer_3(0)(56));
FA345: fulladder port map(pp14(27),pp15(25),pp16(23),layer_3(3)(55),layer_3(1)(56));
--column56
FA346: fulladder port map(layer_4(0)(56),layer_4(1)(56),pp13(30),layer_3(2)(56),layer_3(0)(57));
FA347: fulladder port map(pp14(28),pp15(26),pp16(24),layer_3(3)(56),layer_3(1)(57));
--column57
FA348: fulladder port map(layer_4(0)(57),pp12(33),pp13(31),layer_3(2)(57),layer_3(0)(58));
FA349: fulladder port map(pp14(29),pp15(27),pp16(25),layer_3(3)(57),layer_3(1)(58));
--column58
FA350: fulladder port map(pp12(34),pp13(32),pp14(30),layer_3(2)(58),layer_3(0)(59));
HA25: half_adder port map(pp15(28),pp16(26),layer_3(3)(58),layer_3(1)(59));
--column59
FA351: fulladder port map(pp13(33),pp14(31),pp15(29),layer_3(2)(59),layer_3(0)(60));
--column60
HA26: half_adder port map(pp13(34),pp14(32),layer_3(1)(60),layer_3(0)(61));
--layer3: FA&HA to generate layer2
--column6
HA27: half_adder port map(pp0(6),pp1(4),layer_2(0)(6),layer_2(0)(7));
--column7
FA352: fulladder port map(pp0(7),pp1(5),pp2(3),layer_2(1)(7),layer_2(0)(8));
--column8
FA353: fulladder port map(layer_3(0)(8),pp2(4),pp3(2),layer_2(1)(8),layer_2(0)(9));
--column9
FA354: fulladder port map(layer_3(0)(9),layer_3(1)(9),pp3(3),layer_2(1)(9),layer_2(0)(10));
--column10
FA355: fulladder port map(layer_3(0)(10),layer_3(1)(10),layer_3(2)(10),layer_2(1)(10),layer_2(0)(11));
--column11
FA356: fulladder port map(layer_3(0)(11),layer_3(1)(11),layer_3(2)(11),layer_2(1)(11),layer_2(0)(12));
--column12
FA357: fulladder port map(layer_3(0)(12),layer_3(1)(12),layer_3(2)(12),layer_2(1)(12),layer_2(0)(13));
--column13
FA358: fulladder port map(layer_3(0)(13),layer_3(1)(13),layer_3(2)(13),layer_2(1)(13),layer_2(0)(14));
--column14
FA359: fulladder port map(layer_3(0)(14),layer_3(1)(14),layer_3(2)(14),layer_2(1)(14),layer_2(0)(15));
--column15
FA360: fulladder port map(layer_3(0)(15),layer_3(1)(15),layer_3(2)(15),layer_2(1)(15),layer_2(0)(16));
--column16
FA361: fulladder port map(layer_3(0)(16),layer_3(1)(16),layer_3(2)(16),layer_2(1)(16),layer_2(0)(17));
--column17
FA362: fulladder port map(layer_3(0)(17),layer_3(1)(17),layer_3(2)(17),layer_2(1)(17),layer_2(0)(18));
--column18
FA363: fulladder port map(layer_3(0)(18),layer_3(1)(18),layer_3(2)(18),layer_2(1)(18),layer_2(0)(19));
--column19
FA364: fulladder port map(layer_3(0)(19),layer_3(1)(19),layer_3(2)(19),layer_2(1)(19),layer_2(0)(20));
--column20
FA365: fulladder port map(layer_3(0)(20),layer_3(1)(20),layer_3(2)(20),layer_2(1)(20),layer_2(0)(21));
--column21
FA366: fulladder port map(layer_3(0)(21),layer_3(1)(21),layer_3(2)(21),layer_2(1)(21),layer_2(0)(22));
--column22
FA367: fulladder port map(layer_3(0)(22),layer_3(1)(22),layer_3(2)(22),layer_2(1)(22),layer_2(0)(23));
--column23
FA368: fulladder port map(layer_3(0)(23),layer_3(1)(23),layer_3(2)(23),layer_2(1)(23),layer_2(0)(24));
--column24
FA369: fulladder port map(layer_3(0)(24),layer_3(1)(24),layer_3(2)(24),layer_2(1)(24),layer_2(0)(25));
--column25
FA370: fulladder port map(layer_3(0)(25),layer_3(1)(25),layer_3(2)(25),layer_2(1)(25),layer_2(0)(26));
--column26
FA371: fulladder port map(layer_3(0)(26),layer_3(1)(26),layer_3(2)(26),layer_2(1)(26),layer_2(0)(27));
--column27
FA372: fulladder port map(layer_3(0)(27),layer_3(1)(27),layer_3(2)(27),layer_2(1)(27),layer_2(0)(28));
--column28
FA373: fulladder port map(layer_3(0)(28),layer_3(1)(28),layer_3(2)(28),layer_2(1)(28),layer_2(0)(29));
--column29
FA374: fulladder port map(layer_3(0)(29),layer_3(1)(29),layer_3(2)(29),layer_2(1)(29),layer_2(0)(30));
--column30
FA375: fulladder port map(layer_3(0)(30),layer_3(1)(30),layer_3(2)(30),layer_2(1)(30),layer_2(0)(31));
--column31
FA376: fulladder port map(layer_3(0)(31),layer_3(1)(31),layer_3(2)(31),layer_2(1)(31),layer_2(0)(32));
--column32
FA377: fulladder port map(layer_3(0)(32),layer_3(1)(32),layer_3(2)(32),layer_2(1)(32),layer_2(0)(33));
--column33
FA378: fulladder port map(layer_3(0)(33),layer_3(1)(33),layer_3(2)(33),layer_2(1)(33),layer_2(0)(34));
--column34
FA379: fulladder port map(layer_3(0)(34),layer_3(1)(34),layer_3(2)(34),layer_2(1)(34),layer_2(0)(35));
--column35
FA380: fulladder port map(layer_3(0)(35),layer_3(1)(35),layer_3(2)(35),layer_2(1)(35),layer_2(0)(36));
--column36
FA381: fulladder port map(layer_3(0)(36),layer_3(1)(36),layer_3(2)(36),layer_2(1)(36),layer_2(0)(37));
--column37
FA382: fulladder port map(layer_3(0)(37),layer_3(1)(37),layer_3(2)(37),layer_2(1)(37),layer_2(0)(38));
--column38
FA383: fulladder port map(layer_3(0)(38),layer_3(1)(38),layer_3(2)(38),layer_2(1)(38),layer_2(0)(39));
--column39
FA384: fulladder port map(layer_3(0)(39),layer_3(1)(39),layer_3(2)(39),layer_2(1)(39),layer_2(0)(40));
--column40
FA385: fulladder port map(layer_3(0)(40),layer_3(1)(40),layer_3(2)(40),layer_2(1)(40),layer_2(0)(41));
--column41
FA386: fulladder port map(layer_3(0)(41),layer_3(1)(41),layer_3(2)(41),layer_2(1)(41),layer_2(0)(42));
--column42
FA387: fulladder port map(layer_3(0)(42),layer_3(1)(42),layer_3(2)(42),layer_2(1)(42),layer_2(0)(43));
--column43
FA388: fulladder port map(layer_3(0)(43),layer_3(1)(43),layer_3(2)(43),layer_2(1)(43),layer_2(0)(44));
--column44
FA389: fulladder port map(layer_3(0)(44),layer_3(1)(44),layer_3(2)(44),layer_2(1)(44),layer_2(0)(45));
--column45
FA390: fulladder port map(layer_3(0)(45),layer_3(1)(45),layer_3(2)(45),layer_2(1)(45),layer_2(0)(46));
--column46
FA391: fulladder port map(layer_3(0)(46),layer_3(1)(46),layer_3(2)(46),layer_2(1)(46),layer_2(0)(47));
--column47
FA392: fulladder port map(layer_3(0)(47),layer_3(1)(47),layer_3(2)(47),layer_2(1)(47),layer_2(0)(48));
--column48
FA393: fulladder port map(layer_3(0)(48),layer_3(1)(48),layer_3(2)(48),layer_2(1)(48),layer_2(0)(49));
--column49
FA394: fulladder port map(layer_3(0)(49),layer_3(1)(49),layer_3(2)(49),layer_2(1)(49),layer_2(0)(50));
--column50
FA395: fulladder port map(layer_3(0)(50),layer_3(1)(50),layer_3(2)(50),layer_2(1)(50),layer_2(0)(51));
--column51
FA396: fulladder port map(layer_3(0)(51),layer_3(1)(51),layer_3(2)(51),layer_2(1)(51),layer_2(0)(52));
--column52
FA397: fulladder port map(layer_3(0)(52),layer_3(1)(52),layer_3(2)(52),layer_2(1)(52),layer_2(0)(53));
--column53
FA398: fulladder port map(layer_3(0)(53),layer_3(1)(53),layer_3(2)(53),layer_2(1)(53),layer_2(0)(54));
--column54
FA399: fulladder port map(layer_3(0)(54),layer_3(1)(54),layer_3(2)(54),layer_2(1)(54),layer_2(0)(55));
--column55
FA400: fulladder port map(layer_3(0)(55),layer_3(1)(55),layer_3(2)(55),layer_2(1)(55),layer_2(0)(56));
--column56
FA401: fulladder port map(layer_3(0)(56),layer_3(1)(56),layer_3(2)(56),layer_2(1)(56),layer_2(0)(57));
--column57
FA402: fulladder port map(layer_3(0)(57),layer_3(1)(57),layer_3(2)(57),layer_2(1)(57),layer_2(0)(58));
--column58
FA403: fulladder port map(layer_3(0)(58),layer_3(1)(58),layer_3(2)(58),layer_2(1)(58),layer_2(0)(59));
--column59
FA404: fulladder port map(layer_3(0)(59),layer_3(1)(59),layer_3(2)(59),layer_2(1)(59),layer_2(0)(60));
--column60
FA405: fulladder port map(layer_3(0)(60),layer_3(1)(60),pp15(30),layer_2(1)(60),layer_2(0)(61));
--column61
FA406: fulladder port map(layer_3(0)(61),pp14(33),pp15(31),layer_2(1)(61),layer_2(0)(62));
--column62
HA28: half_adder port map(pp14(34),pp15(32),layer_2(1)(62),layer_2(0)(63));
--layer2: FA&HA to generate layer1
--column4
HA29: half_adder port map(pp0(4),pp1(2),layer_1(0)(4),layer_1(0)(5));
--column5
FA407: fulladder port map(pp0(5),pp1(3),pp2(1),layer_1(1)(5),layer_1(0)(6));
--column6
FA408: fulladder port map(layer_2(0)(6),pp2(2),pp3(0),layer_1(1)(6),layer_1(0)(7));
--column7
FA409: fulladder port map(layer_2(0)(7),layer_2(1)(7),pp3(1),layer_1(1)(7),layer_1(0)(8));
--column8
FA410: fulladder port map(layer_2(0)(8),layer_2(1)(8),pp4(0),layer_1(1)(8),layer_1(0)(9));
--column9
FA411: fulladder port map(layer_2(0)(9),layer_2(1)(9),pp4(1),layer_1(1)(9),layer_1(0)(10));
--column10
FA412: fulladder port map(layer_2(0)(10),layer_2(1)(10),pp5(0),layer_1(1)(10),layer_1(0)(11));
--column11
FA413: fulladder port map(layer_2(0)(11),layer_2(1)(11),layer_3(3)(11),layer_1(1)(11),layer_1(0)(12));
--column12
FA414: fulladder port map(layer_2(0)(12),layer_2(1)(12),layer_3(3)(12),layer_1(1)(12),layer_1(0)(13));
--column13
FA415: fulladder port map(layer_2(0)(13),layer_2(1)(13),layer_3(3)(13),layer_1(1)(13),layer_1(0)(14));
--column14
FA416: fulladder port map(layer_2(0)(14),layer_2(1)(14),layer_3(3)(14),layer_1(1)(14),layer_1(0)(15));
--column15
FA417: fulladder port map(layer_2(0)(15),layer_2(1)(15),layer_3(3)(15),layer_1(1)(15),layer_1(0)(16));
--column16
FA418: fulladder port map(layer_2(0)(16),layer_2(1)(16),layer_3(3)(16),layer_1(1)(16),layer_1(0)(17));
--column17
FA419: fulladder port map(layer_2(0)(17),layer_2(1)(17),layer_3(3)(17),layer_1(1)(17),layer_1(0)(18));
--column18
FA420: fulladder port map(layer_2(0)(18),layer_2(1)(18),layer_3(3)(18),layer_1(1)(18),layer_1(0)(19));
--column19
FA421: fulladder port map(layer_2(0)(19),layer_2(1)(19),layer_3(3)(19),layer_1(1)(19),layer_1(0)(20));
--column20
FA422: fulladder port map(layer_2(0)(20),layer_2(1)(20),layer_3(3)(20),layer_1(1)(20),layer_1(0)(21));
--column21
FA423: fulladder port map(layer_2(0)(21),layer_2(1)(21),layer_3(3)(21),layer_1(1)(21),layer_1(0)(22));
--column22
FA424: fulladder port map(layer_2(0)(22),layer_2(1)(22),layer_3(3)(22),layer_1(1)(22),layer_1(0)(23));
--column23
FA425: fulladder port map(layer_2(0)(23),layer_2(1)(23),layer_3(3)(23),layer_1(1)(23),layer_1(0)(24));
--column24
FA426: fulladder port map(layer_2(0)(24),layer_2(1)(24),layer_3(3)(24),layer_1(1)(24),layer_1(0)(25));
--column25
FA427: fulladder port map(layer_2(0)(25),layer_2(1)(25),layer_3(3)(25),layer_1(1)(25),layer_1(0)(26));
--column26
FA428: fulladder port map(layer_2(0)(26),layer_2(1)(26),layer_3(3)(26),layer_1(1)(26),layer_1(0)(27));
--column27
FA429: fulladder port map(layer_2(0)(27),layer_2(1)(27),layer_3(3)(27),layer_1(1)(27),layer_1(0)(28));
--column28
FA430: fulladder port map(layer_2(0)(28),layer_2(1)(28),layer_3(3)(28),layer_1(1)(28),layer_1(0)(29));
--column29
FA431: fulladder port map(layer_2(0)(29),layer_2(1)(29),layer_3(3)(29),layer_1(1)(29),layer_1(0)(30));
--column30
FA432: fulladder port map(layer_2(0)(30),layer_2(1)(30),layer_3(3)(30),layer_1(1)(30),layer_1(0)(31));
--column31
FA433: fulladder port map(layer_2(0)(31),layer_2(1)(31),layer_3(3)(31),layer_1(1)(31),layer_1(0)(32));
--column32
FA434: fulladder port map(layer_2(0)(32),layer_2(1)(32),layer_3(3)(32),layer_1(1)(32),layer_1(0)(33));
--column33
FA435: fulladder port map(layer_2(0)(33),layer_2(1)(33),layer_3(3)(33),layer_1(1)(33),layer_1(0)(34));
--column34
FA436: fulladder port map(layer_2(0)(34),layer_2(1)(34),layer_3(3)(34),layer_1(1)(34),layer_1(0)(35));
--column35
FA437: fulladder port map(layer_2(0)(35),layer_2(1)(35),layer_3(3)(35),layer_1(1)(35),layer_1(0)(36));
--column36
FA438: fulladder port map(layer_2(0)(36),layer_2(1)(36),layer_3(3)(36),layer_1(1)(36),layer_1(0)(37));
--column37
FA439: fulladder port map(layer_2(0)(37),layer_2(1)(37),layer_3(3)(37),layer_1(1)(37),layer_1(0)(38));
--column38
FA440: fulladder port map(layer_2(0)(38),layer_2(1)(38),layer_3(3)(38),layer_1(1)(38),layer_1(0)(39));
--column39
FA441: fulladder port map(layer_2(0)(39),layer_2(1)(39),layer_3(3)(39),layer_1(1)(39),layer_1(0)(40));
--column40
FA442: fulladder port map(layer_2(0)(40),layer_2(1)(40),layer_3(3)(40),layer_1(1)(40),layer_1(0)(41));
--column41
FA443: fulladder port map(layer_2(0)(41),layer_2(1)(41),layer_3(3)(41),layer_1(1)(41),layer_1(0)(42));
--column42
FA444: fulladder port map(layer_2(0)(42),layer_2(1)(42),layer_3(3)(42),layer_1(1)(42),layer_1(0)(43));
--column43
FA445: fulladder port map(layer_2(0)(43),layer_2(1)(43),layer_3(3)(43),layer_1(1)(43),layer_1(0)(44));
--column44
FA446: fulladder port map(layer_2(0)(44),layer_2(1)(44),layer_3(3)(44),layer_1(1)(44),layer_1(0)(45));
--column45
FA447: fulladder port map(layer_2(0)(45),layer_2(1)(45),layer_3(3)(45),layer_1(1)(45),layer_1(0)(46));
--column46
FA448: fulladder port map(layer_2(0)(46),layer_2(1)(46),layer_3(3)(46),layer_1(1)(46),layer_1(0)(47));
--column47
FA449: fulladder port map(layer_2(0)(47),layer_2(1)(47),layer_3(3)(47),layer_1(1)(47),layer_1(0)(48));
--column48
FA450: fulladder port map(layer_2(0)(48),layer_2(1)(48),layer_3(3)(48),layer_1(1)(48),layer_1(0)(49));
--column49
FA451: fulladder port map(layer_2(0)(49),layer_2(1)(49),layer_3(3)(49),layer_1(1)(49),layer_1(0)(50));
--column50
FA452: fulladder port map(layer_2(0)(50),layer_2(1)(50),layer_3(3)(50),layer_1(1)(50),layer_1(0)(51));
--column51
FA453: fulladder port map(layer_2(0)(51),layer_2(1)(51),layer_3(3)(51),layer_1(1)(51),layer_1(0)(52));
--column52
FA454: fulladder port map(layer_2(0)(52),layer_2(1)(52),layer_3(3)(52),layer_1(1)(52),layer_1(0)(53));
--column53
FA455: fulladder port map(layer_2(0)(53),layer_2(1)(53),layer_3(3)(53),layer_1(1)(53),layer_1(0)(54));
--column54
FA456: fulladder port map(layer_2(0)(54),layer_2(1)(54),layer_3(3)(54),layer_1(1)(54),layer_1(0)(55));
--column55
FA457: fulladder port map(layer_2(0)(55),layer_2(1)(55),layer_3(3)(55),layer_1(1)(55),layer_1(0)(56));
--column56
FA458: fulladder port map(layer_2(0)(56),layer_2(1)(56),layer_3(3)(56),layer_1(1)(56),layer_1(0)(57));
--column57
FA459: fulladder port map(layer_2(0)(57),layer_2(1)(57),layer_3(3)(57),layer_1(1)(57),layer_1(0)(58));
--column58
FA460: fulladder port map(layer_2(0)(58),layer_2(1)(58),layer_3(3)(58),layer_1(1)(58),layer_1(0)(59));
--column59
FA461: fulladder port map(layer_2(0)(59),layer_2(1)(59),pp16(27),layer_1(1)(59),layer_1(0)(60));
--column60
FA462: fulladder port map(layer_2(0)(60),layer_2(1)(60),pp16(28),layer_1(1)(60),layer_1(0)(61));
--column61
FA463: fulladder port map(layer_2(0)(61),layer_2(1)(61),pp16(29),layer_1(1)(61),layer_1(0)(62));
--column62
FA464: fulladder port map(layer_2(0)(62),layer_2(1)(62),pp16(30),layer_1(1)(62),layer_1(0)(63));
--column63
FA465: fulladder port map(layer_2(0)(63),pp15(33),pp16(31),layer_1(1)(63),layer_1(0)(64));
layer_1(0)(0)<=pp0(0);
layer_1(0)(1)<=pp0(1);
layer_1(0)(2)<=pp0(2);
layer_1(0)(3)<=pp0(3);
layer_1(1)(2)<=pp1(0);
layer_1(1)(3)<=pp1(1);
layer_1(1)(4)<=pp2(2);
f_add1<=layer_1(0)(63)&layer_1(0)(62)&layer_1(0)(61)&layer_1(0)(60)&layer_1(0)(59)&layer_1(0)(58)&layer_1(0)(57)&layer_1(0)(56)&layer_1(0)(55)&layer_1(0)(54)&layer_1(0)(53)&layer_1(0)(52)&layer_1(0)(51)&layer_1(0)(50)&layer_1(0)(49)&layer_1(0)(48)&layer_1(0)(47)&layer_1(0)(46)&layer_1(0)(45)&layer_1(0)(44)&layer_1(0)(43)&layer_1(0)(42)&layer_1(0)(41)&layer_1(0)(40)&layer_1(0)(39)&layer_1(0)(38)&layer_1(0)(37)&layer_1(0)(36)&layer_1(0)(35)&layer_1(0)(34)&layer_1(0)(33)&layer_1(0)(32)&layer_1(0)(31)&layer_1(0)(30)&layer_1(0)(29)&layer_1(0)(28)&layer_1(0)(27)&layer_1(0)(26)&layer_1(0)(25)&layer_1(0)(24)&layer_1(0)(23)&layer_1(0)(22)&layer_1(0)(21)&layer_1(0)(20)&layer_1(0)(19)&layer_1(0)(18)&layer_1(0)(17)&layer_1(0)(16)&layer_1(0)(15)&layer_1(0)(14)&layer_1(0)(13)&layer_1(0)(12)&layer_1(0)(11)&layer_1(0)(10)&layer_1(0)(9)&layer_1(0)(8)&layer_1(0)(7)&layer_1(0)(6)&layer_1(0)(5)&layer_1(0)(4)&layer_1(0)(3)&layer_1(0)(2)&layer_1(0)(1)&layer_1(0)(0);
f_add2<=layer_1(1)(63)&layer_1(1)(62)&layer_1(1)(61)&layer_1(1)(60)&layer_1(1)(59)&layer_1(1)(58)&layer_1(1)(57)&layer_1(1)(56)&layer_1(1)(55)&layer_1(1)(54)&layer_1(1)(53)&layer_1(1)(52)&layer_1(1)(51)&layer_1(1)(50)&layer_1(1)(49)&layer_1(1)(48)&layer_1(1)(47)&layer_1(1)(46)&layer_1(1)(45)&layer_1(1)(44)&layer_1(1)(43)&layer_1(1)(42)&layer_1(1)(41)&layer_1(1)(40)&layer_1(1)(39)&layer_1(1)(38)&layer_1(1)(37)&layer_1(1)(36)&layer_1(1)(35)&layer_1(1)(34)&layer_1(1)(33)&layer_1(1)(32)&layer_1(1)(31)&layer_1(1)(30)&layer_1(1)(29)&layer_1(1)(28)&layer_1(1)(27)&layer_1(1)(26)&layer_1(1)(25)&layer_1(1)(24)&layer_1(1)(23)&layer_1(1)(22)&layer_1(1)(21)&layer_1(1)(20)&layer_1(1)(19)&layer_1(1)(18)&layer_1(1)(17)&layer_1(1)(16)&layer_1(1)(15)&layer_1(1)(14)&layer_1(1)(13)&layer_1(1)(12)&layer_1(1)(11)&layer_1(1)(10)&layer_1(1)(9)&layer_1(1)(8)&layer_1(1)(7)&layer_1(1)(6)&layer_1(1)(5)&layer_1(1)(4)&layer_1(1)(3)&layer_1(1)(2)&layer_1(1)(1)&layer_1(1)(0);
End Structural;
<file_sep>#!/bin/bash
source /software/scripts/init_msim6.2g
rm -rf work
rm -f transcript
rm -f vsim.wlf
vlib work
vcom -93 -work ./work ../src/regIn_out.vhd
vcom -93 -work ./work ../src/packfp_packfp.vhd
vcom -93 -work ./work ../src/fpround_fpround.vhd
vcom -93 -work ./work ../src/fpnormalize_fpnormalize.vhd
vcom -93 -work ./work ../src/unpackfp_unpackfp.vhd
vcom -93 -work ./work ../src/fpmul_stage1_struct.vhd
vcom -93 -work ./work ../src/fpmul_stage2_struct.vhd
vcom -93 -work ./work ../src/fpmul_stage3_struct.vhd
vcom -93 -work ./work ../src/fpmul_stage4_struct.vhd
vcom -93 -work ./work ../src/fpmul_pipeline.vhd
vcom -93 -work ./work ../tb/*.vhd
vlog -work ./work ../tb/*.v
vsim work.testbench
<file_sep>LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE ieee.numeric_std.all;
ENTITY regOut_Exp IS
GENERIC ( N : integer:=8);
PORT ( Clock,Load: IN STD_LOGIC;
datoInput: in std_logic_vector(N-1 downto 0);
datoOutput : OUT std_logic_vector(N-1 DOWNTO 0));
END regOut_Exp ;
ARCHITECTURE Behavior OF regOut_Exp IS
BEGIN
PROCESS (Clock)
BEGIN
IF (Clock'EVENT AND Clock = '1') THEN
IF (Load='1') THEN
datoOutput <= datoInput;
END IF;
END IF;
END PROCESS;
END Behavior;<file_sep>library IEEE;
use IEEE.STD_LOGIC_1164.all;
USE ieee.numeric_std.all;
entity mux2to1_32bit is
GENERIC ( N : integer:=32);
port(
selP_P: in std_logic;
Input_Z,Input_A: in std_logic_vector(N-1 downto 0);
P_Pout: out std_logic_vector(N-1 downto 0));
end mux2to1_32bit;
Architecture behavioural of mux2to1_32bit is
begin
MUX:process (selP_P,Input_Z,Input_A)
begin
case selP_P is
when '0' => P_Pout <= Input_Z; --0
when '1' => P_Pout <= Input_A; --A
when others => P_Pout <= Input_Z; --0
end case;
end process MUX;
end behavioural;
<file_sep>add wave *
run 200 ns
<file_sep>LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE ieee.numeric_std.all;
Entity MBE_radix4_fullyDaddaTree is
GENERIC ( N : integer:=32);
Port( multiplicand,multiplier: in std_logic_vector(N-1 downto 0);
result: out std_logic_vector((2*N-1) downto 0)
);
End MBE_radix4_fullyDaddaTree;
Architecture structural of MBE_radix4_fullyDaddaTree is
signal p_p0 :std_logic_vector(N+3 downto 0);
signal p_p1,p_p2,p_p3,p_p4,p_p5,p_p6,p_p7,p_p8,p_p9,p_p10,p_p11,p_p12,p_p13,p_p14:std_logic_vector(N+2 downto 0);
signal p_p15: std_logic_vector(N+1 downto 0);
signal p_p16: std_logic_vector(N-1 downto 0);
signal f_add1,f_add2: std_logic_vector((2*N-1) downto 0);
Component daddaTree is
GENERIC ( N : integer:=32);
Port( pp0: in std_logic_vector(N+3 downto 0);
pp1,pp2,pp3,pp4,pp5,pp6,pp7,pp8,pp9,pp10,pp11,pp12,pp13,pp14: in std_logic_vector(N+2 downto 0);
pp15: in std_logic_vector(N+1 downto 0);
pp16: in std_logic_vector(N-1 downto 0);
f_add1,f_add2: out std_logic_vector((2*N-1) downto 0)
);
End Component;
Component operand_generation is
GENERIC ( N : integer:=32);
Port( multiplicand, multiplier: in std_logic_vector(N-1 downto 0);
pp0:out std_logic_vector(N+3 downto 0);
pp1,pp2,pp3,pp4,pp5,pp6,pp7,pp8,pp9,pp10,pp11,pp12,pp13,pp14:out std_logic_vector(N+2 downto 0);
pp15:out std_logic_vector(N+1 downto 0);
pp16: out std_logic_vector(N-1 downto 0)
);
End Component;
Component final_adder IS
GENERIC ( N : integer:=64);
PORT (Add_first,Add_second: IN std_logic_vector(N-1 DOWNTO 0);
outSum: out std_logic_vector(N-1 downto 0));
END Component;
Begin
Generation_pp_Radix4: operand_generation PORT MAP(multiplicand,multiplier,p_p0,p_p1,p_p2,p_p3,p_p4,p_p5,p_p6,p_p7,p_p8,p_p9,p_p10,p_p11,p_p12,p_p13,p_p14,p_p15,p_p16);
Fully_PP_DaddaTree: daddaTree PORT MAP(p_p0,p_p1,p_p2,p_p3,p_p4,p_p5,p_p6,p_p7,p_p8,p_p9,p_p10,p_p11,p_p12,p_p13,p_p14,p_p15,p_p16,f_add1,f_add2);
Result_MBE: final_adder PORT MAP(f_add1,f_add2,result);
end structural;
<file_sep>fileDiRiferimento='daddaTree.txt'
F=open(fileDiRiferimento, 'a')
s='FA'
s7=': fulladder port map(layer_7('
FA_n=': fulladder port map('
HA='HA'
HA_s=': half_adder port map('
n_HA=1
n_FA=1
j=0
x=3
k=0
L=['pp0(','pp1(','pp2(','pp3(','pp4(','pp5(','pp6(','pp7(','pp8(','pp9(','pp10(','pp11(','pp12(','pp13(','pp14(','pp15(','pp16(']
col='--column'
#layer7: FA&HA to generate layer6
com='--layer7: FA&HA to generate layer6\n'
F.write(com)
for C in range(26,43):
column=col+str(C)+'\n'
F.write(column)
if C==26 or C==42:
index_L=0
n=C
if C==42:
index_L=4
n=C-8
stringa=HA+str(n_HA)+HA_s+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),layer_6('+str(0)+')('+str(C)+'),layer_6('+str(0)+')('+str(C+1)+'));'+'\n'
n_HA=n_HA+1
F.write(stringa)
elif C==27 or C==41:
index_L=0
n=C
if C==41:
index_L=4
n=C-8
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_6('+str(1)+')('+str(C)+'),layer_6('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==28 or C==40:
index_L=0
n=C
if C==40:
index_L=3
n=C-6
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_6('+str(1)+')('+str(C)+'),layer_6('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=HA+str(n_HA)+HA_s+L[index_L+3]+str(n-6)+'),'+L[index_L+4]+str(n-8)+'),layer_6('+str(2)+')('+str(C)+'),layer_6('+str(1)+')('+str(C+1)+'));'+'\n'
n_HA=n_HA+1
F.write(stringa)
elif C==29 or C==39:
index_L=0
n=C
if C==39:
index_L=3
n=C-6
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_6('+str(2)+')('+str(C)+'),layer_6('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=s+str(n_FA)+FA_n+L[index_L+3]+str(n-6)+'),'+L[index_L+4]+str(n-8)+'),'+L[index_L+5]+str(n-10)+'),layer_6('+str(3)+')('+str(C)+'),layer_6('+str(1)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==30 or C==38:
index_L=0
n=C
if C==38:
index_L=2
n=C-4
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_6('+str(2)+')('+str(C)+'),layer_6('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=s+str(n_FA)+FA_n+L[index_L+3]+str(n-6)+'),'+L[index_L+4]+str(n-8)+'),'+L[index_L+5]+str(n-10)+'),layer_6('+str(3)+')('+str(C)+'),layer_6('+str(1)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=HA+str(n_HA)+HA_s+L[index_L+6]+str(n-12)+'),'+L[index_L+7]+str(n-14)+'),layer_6('+str(4)+')('+str(C)+'),layer_6('+str(2)+')('+str(C+1)+'));'+'\n'
n_HA=n_HA+1
F.write(stringa)
elif C==31 or C==37:
index_L=0
n=C
if C==37:
index_L=2
n=C-4
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_6('+str(3)+')('+str(C)+'),layer_6('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=s+str(n_FA)+FA_n+L[index_L+3]+str(n-6)+'),'+L[index_L+4]+str(n-8)+'),'+L[index_L+5]+str(n-10)+'),layer_6('+str(4)+')('+str(C)+'),layer_6('+str(1)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=s+str(n_FA)+FA_n+L[index_L+6]+str(n-12)+'),'+L[index_L+7]+str(n-14)+'),'+L[index_L+8]+str(n-16)+'),layer_6('+str(5)+')('+str(C)+'),layer_6('+str(2)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==32 or C==36:
index_L=0
n=C
i=3
if C==36:
index_L=1
n=C-2
i=4
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_6('+str(i)+')('+str(C)+'),layer_6('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
i=i+1
F.write(stringa)
stringa=s+str(n_FA)+FA_n+L[index_L+3]+str(n-6)+'),'+L[index_L+4]+str(n-8)+'),'+L[index_L+5]+str(n-10)+'),layer_6('+str(i)+')('+str(C)+'),layer_6('+str(1)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
i=i+1
F.write(stringa)
stringa=s+str(n_FA)+FA_n+L[index_L+6]+str(n-12)+'),'+L[index_L+7]+str(n-14)+'),'+L[index_L+8]+str(n-16)+'),layer_6('+str(i)+')('+str(C)+'),layer_6('+str(2)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
i=i+1
F.write(stringa)
stringa=HA+str(n_HA)+HA_s+L[index_L+9]+str(n-18)+'),'+L[index_L+10]+str(n-20)+'),layer_6('+str(i)+')('+str(C)+'),layer_6('+str(3)+')('+str(C+1)+'));'+'\n'
n_HA=n_HA+1
F.write(stringa)
else:
index_L=0
n=C
for R in range(4):
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_6('+str(4+R)+')('+str(C)+'),layer_6('+str(R)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
index_L=index_L+3
n=n-6
#layer6: FA&HA to generate layer5
com='--layer6: FA&HA to generate layer5\n'
F.write(com)
s6=': fulladder port map(layer_6('
for C in range(18,51):
column=col+str(C)+'\n'
F.write(column)
if C==18 or C==50:
index_L=0
n=C
if C==50:
index_L=8
n=C-16
stringa=HA+str(n_HA)+HA_s+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),layer_5('+str(0)+')('+str(C)+'),layer_5('+str(0)+')('+str(C+1)+'));'+'\n'
n_HA=n_HA+1
F.write(stringa)
elif C==19 or C==49:
index_L=0
n=C
if C==49:
index_L=8
n=C-16
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_5('+str(1)+')('+str(C)+'),layer_5('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==20 or C==48:
index_L=0
n=C
if C==48:
index_L=7
n=C-14
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_5('+str(1)+')('+str(C)+'),layer_5('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=HA+str(n_HA)+HA_s+L[index_L+3]+str(n-6)+'),'+L[index_L+4]+str(n-8)+'),layer_5('+str(2)+')('+str(C)+'),layer_5('+str(1)+')('+str(C+1)+'));'+'\n'
n_HA=n_HA+1
F.write(stringa)
elif C==21 or C==47:
index_L=0
n=C
if C==47:
index_L=7
n=C-14
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_5('+str(2)+')('+str(C)+'),layer_5('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=s+str(n_FA)+FA_n+L[index_L+3]+str(n-6)+'),'+L[index_L+4]+str(n-8)+'),'+L[index_L+5]+str(n-10)+'),layer_5('+str(3)+')('+str(C)+'),layer_5('+str(1)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==22 or C==46:
index_L=0
n=C
if C==46:
index_L=6
n=C-12
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_5('+str(2)+')('+str(C)+'),layer_5('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=s+str(n_FA)+FA_n+L[index_L+3]+str(n-6)+'),'+L[index_L+4]+str(n-8)+'),'+L[index_L+5]+str(n-10)+'),layer_5('+str(3)+')('+str(C)+'),layer_5('+str(1)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=HA+str(n_HA)+HA_s+L[index_L+6]+str(n-12)+'),'+L[index_L+7]+str(n-14)+'),layer_5('+str(4)+')('+str(C)+'),layer_5('+str(2)+')('+str(C+1)+'));'+'\n'
n_HA=n_HA+1
F.write(stringa)
elif C==23 or C==45:
index_L=0
n=C
if C==45:
index_L=6
n=C-12
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_5('+str(3)+')('+str(C)+'),layer_5('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=s+str(n_FA)+FA_n+L[index_L+3]+str(n-6)+'),'+L[index_L+4]+str(n-8)+'),'+L[index_L+5]+str(n-10)+'),layer_5('+str(4)+')('+str(C)+'),layer_5('+str(1)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=s+str(n_FA)+FA_n+L[index_L+6]+str(n-12)+'),'+L[index_L+7]+str(n-14)+'),'+L[index_L+8]+str(n-16)+'),layer_5('+str(5)+')('+str(C)+'),layer_5('+str(2)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==24 or C==44:
index_L=0
n=C
if C==44:
index_L=5
n=C-10
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_5('+str(3)+')('+str(C)+'),layer_5('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=s+str(n_FA)+FA_n+L[index_L+3]+str(n-6)+'),'+L[index_L+4]+str(n-8)+'),'+L[index_L+5]+str(n-10)+'),layer_5('+str(4)+')('+str(C)+'),layer_5('+str(1)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=s+str(n_FA)+FA_n+L[index_L+6]+str(n-12)+'),'+L[index_L+7]+str(n-14)+'),'+L[index_L+8]+str(n-16)+'),layer_5('+str(5)+')('+str(C)+'),layer_5('+str(2)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=HA+str(n_HA)+HA_s+L[index_L+9]+str(n-18)+'),'+L[index_L+10]+str(n-20)+'),layer_5('+str(6)+')('+str(C)+'),layer_5('+str(3)+')('+str(C+1)+'));'+'\n'
n_HA=n_HA+1
F.write(stringa)
elif C==25:
index_L=0
n=C
for R in range(4):
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
index_L=index_L+3
n=n-6
elif C==26 or C==43:
index_L=2
n=C-2*index_L
if C==43:
index_L=5
n=C-2*index_L
for R in range(4):
if R==0:
stringa=s+str(n_FA)+s6+str(0)+')('+str(C)+'),'+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+2
n=n-4
else:
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+3
n=n-6
n_FA=n_FA+1
F.write(stringa)
elif C==27 or C==42:
index_L=3
n=C-2*index_L
if C==42:
index_L=6
n=C-2*index_L
for R in range(4):
if R==0:
stringa=s+str(n_FA)+s6+str(0)+')('+str(C)+'),'+'layer_6('+str(1)+')('+str(C)+'),'+L[index_L]+str(n)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+1
n=n-2
else:
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+3
n=n-6
n_FA=n_FA+1
F.write(stringa)
elif C==28 or C==41:
index_L=5
if C==41:
index_L=7
n=C-2*index_L
for R in range(4):
if R==0:
stringa=s+str(n_FA)+s6+str(0)+')('+str(C)+'),'+'layer_6('+str(1)+')('+str(C)+'),'+'layer_6('+str(2)+')('+str(C)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
else:
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+3
n=n-6
n_FA=n_FA+1
F.write(stringa)
elif C==29 or C==40:
index_L=6
if C==40:
index_L=8
n=C-2*index_L
for R in range(4):
if R==0:
stringa=s+str(n_FA)+s6+str(0)+')('+str(C)+'),'+'layer_6('+str(1)+')('+str(C)+'),'+'layer_6('+str(2)+')('+str(C)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
elif R==1:
stringa=s+str(n_FA)+s6+str(3)+')('+str(C)+'),'+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+2
n=n-4
else:
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+3
n=n-6
n_FA=n_FA+1
F.write(stringa)
elif C==30 or C==39:
index_L=8
if C==39:
index_L=9
n=C-2*index_L
for R in range(4):
if R==0:
stringa=s+str(n_FA)+s6+str(0)+')('+str(C)+'),'+'layer_6('+str(1)+')('+str(C)+'),'+'layer_6('+str(2)+')('+str(C)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
elif R==1:
stringa=s+str(n_FA)+s6+str(3)+')('+str(C)+'),'+'layer_6('+str(4)+')('+str(C)+'),'+L[index_L]+str(n)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+1
n=n-2
else:
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+3
n=n-6
n_FA=n_FA+1
F.write(stringa)
elif C==31 or C==38:
index_L=9
if C==38:
index_L=10
n=C-2*index_L
for R in range(4):
if R==0:
stringa=s+str(n_FA)+s6+str(0)+')('+str(C)+'),'+'layer_6('+str(1)+')('+str(C)+'),'+'layer_6('+str(2)+')('+str(C)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
elif R==1:
stringa=s+str(n_FA)+s6+str(3)+')('+str(C)+'),'+'layer_6('+str(4)+')('+str(C)+'),'+'layer_6('+str(5)+')('+str(C)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
else:
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+3
n=n-6
n_FA=n_FA+1
F.write(stringa)
elif C==32 or C==37:
index_L=11
if C==37:
index_L=11
n=C-2*index_L
for R in range(4):
if R==0:
stringa=s+str(n_FA)+s6+str(0)+')('+str(C)+'),'+'layer_6('+str(1)+')('+str(C)+'),'+'layer_6('+str(2)+')('+str(C)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
elif R==1:
stringa=s+str(n_FA)+s6+str(3)+')('+str(C)+'),'+'layer_6('+str(4)+')('+str(C)+'),'+'layer_6('+str(5)+')('+str(C)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
elif R==2:
stringa=s+str(n_FA)+s6+str(6)+')('+str(C)+'),'+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+2
n=n-4
else:
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
else:
index_L=12
n=C-2*index_L
for R in range(4):
if R==0:
stringa=s+str(n_FA)+s6+str(0)+')('+str(C)+'),'+'layer_6('+str(1)+')('+str(C)+'),'+'layer_6('+str(2)+')('+str(C)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
elif R==1:
stringa=s+str(n_FA)+s6+str(3)+')('+str(C)+'),'+'layer_6('+str(4)+')('+str(C)+'),'+'layer_6('+str(5)+')('+str(C)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
elif R==2:
stringa=s+str(n_FA)+s6+str(6)+')('+str(C)+'),'+'layer_6('+str(7)+')('+str(C)+'),'+L[index_L]+str(n)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+1
n=n-2
else:
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_5('+str(4+R)+')('+str(C)+'),layer_5('+str(R)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
#layer5: FA&HA to generate layer4
com='--layer5: FA&HA to generate layer4\n'
F.write(com)
s5=': fulladder port map(layer_5('
for C in range(12,57):
column=col+str(C)+'\n'
F.write(column)
if C==12 or C==56:
index_L=0
n=C
if C==56:
index_L=11
n=C-2*index_L
stringa=HA+str(n_HA)+HA_s+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),layer_4('+str(0)+')('+str(C)+'),layer_4('+str(0)+')('+str(C+1)+'));'+'\n'
n_HA=n_HA+1
F.write(stringa)
elif C==13 or C==55:
index_L=0
n=C
if C==55:
index_L=11
n=C-2*index_L
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_4('+str(1)+')('+str(C)+'),layer_4('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==14 or C==54:
index_L=0
n=C
if C==54:
index_L=10
n=C-2*index_L
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_4('+str(1)+')('+str(C)+'),layer_4('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=HA+str(n_HA)+HA_s+L[index_L+3]+str(n-6)+'),'+L[index_L+4]+str(n-8)+'),layer_4('+str(2)+')('+str(C)+'),layer_4('+str(1)+')('+str(C+1)+'));'+'\n'
n_HA=n_HA+1
F.write(stringa)
elif C==15 or C==53:
index_L=0
n=C
if C==53:
index_L=10
n=C-2*index_L
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_4('+str(2)+')('+str(C)+'),layer_4('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=s+str(n_FA)+FA_n+L[index_L+3]+str(n-6)+'),'+L[index_L+4]+str(n-8)+'),'+L[index_L+5]+str(n-10)+'),layer_4('+str(3)+')('+str(C)+'),layer_4('+str(1)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==16 or C==52:
index_L=0
n=C
if C==52:
index_L=9
n=C-2*index_L
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_4('+str(2)+')('+str(C)+'),layer_4('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=s+str(n_FA)+FA_n+L[index_L+3]+str(n-6)+'),'+L[index_L+4]+str(n-8)+'),'+L[index_L+5]+str(n-10)+'),layer_4('+str(3)+')('+str(C)+'),layer_4('+str(1)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=HA+str(n_HA)+HA_s+L[index_L+6]+str(n-12)+'),'+L[index_L+7]+str(n-14)+'),layer_4('+str(4)+')('+str(C)+'),layer_4('+str(2)+')('+str(C+1)+'));'+'\n'
n_HA=n_HA+1
F.write(stringa)
elif C==17:
index_L=0
stringa=s+str(n_FA)+FA_n+L[index_L]+str(C)+'),'+L[index_L+1]+str(C-2)+'),'+L[index_L+2]+str(C-4)+'),layer_4('+str(3)+')('+str(C)+'),layer_4('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=s+str(n_FA)+FA_n+L[index_L+3]+str(C-6)+'),'+L[index_L+4]+str(C-8)+'),'+L[index_L+5]+str(C-10)+'),layer_4('+str(4)+')('+str(C)+'),layer_4('+str(1)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=s+str(n_FA)+FA_n+L[index_L+6]+str(C-12)+'),'+L[index_L+7]+str(C-14)+'),'+L[index_L+8]+str(C-16)+'),layer_4('+str(5)+')('+str(C)+'),layer_4('+str(2)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==18 or C==51:
index_L=2
if C==51:
index_L=9
n=C-2*index_L
for R in range(3):
if R==0:
stringa=s+str(n_FA)+s5+str(0)+')('+str(C)+'),'+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+2
n=n-4
else:
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+3
n=n-6
n_FA=n_FA+1
F.write(stringa)
elif C==19 or C==50:
index_L=3
if C==50:
index_L=10
n=C-2*index_L
for R in range(3):
if R==0:
stringa=s+str(n_FA)+s5+str(0)+')('+str(C)+'),'+'layer_5('+str(1)+')('+str(C)+'),'+L[index_L]+str(n)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+1
n=n-2
else:
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+3
n=n-6
n_FA=n_FA+1
F.write(stringa)
elif C==20 or C==49:
index_L=5
if C==49:
index_L=11
n=C-2*index_L
for R in range(3):
if R==0:
stringa=s+str(n_FA)+s5+str(0)+')('+str(C)+'),'+'layer_5('+str(1)+')('+str(C)+'),'+'layer_5('+str(2)+')('+str(C)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
else:
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+3
n=n-6
n_FA=n_FA+1
F.write(stringa)
elif C==21 or C==48:
index_L=6
if C==48:
index_L=12
n=C-2*index_L
for R in range(3):
if R==0:
stringa=s+str(n_FA)+s5+str(0)+')('+str(C)+'),'+'layer_5('+str(1)+')('+str(C)+'),'+'layer_5('+str(2)+')('+str(C)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
elif R==1:
stringa=s+str(n_FA)+s5+str(3)+')('+str(C)+'),'+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+2
n=n-4
else:
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+3
n=n-6
n_FA=n_FA+1
F.write(stringa)
elif C==22 or C==47:
index_L=8
if C==47:
index_L=13
n=C-2*index_L
for R in range(3):
if R==0:
stringa=s+str(n_FA)+s5+str(0)+')('+str(C)+'),'+'layer_5('+str(1)+')('+str(C)+'),'+'layer_5('+str(2)+')('+str(C)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
elif R==1:
stringa=s+str(n_FA)+s5+str(3)+')('+str(C)+'),'+'layer_5('+str(4)+')('+str(C)+'),'+L[index_L]+str(n)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+1
n=n-2
else:
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+3
n=n-6
n_FA=n_FA+1
F.write(stringa)
elif C==23 or C==46:
index_L=9
if C==46:
index_L=14
n=C-2*index_L
for R in range(3):
if R==0:
stringa=s+str(n_FA)+s5+str(0)+')('+str(C)+'),'+'layer_5('+str(1)+')('+str(C)+'),'+'layer_5('+str(2)+')('+str(C)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
elif R==1:
stringa=s+str(n_FA)+s5+str(3)+')('+str(C)+'),'+'layer_5('+str(4)+')('+str(C)+'),'+'layer_5('+str(5)+')('+str(C)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
else:
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+3
n=n-6
n_FA=n_FA+1
F.write(stringa)
elif C==24 or C==45:
index_L=11
if C==45:
index_L=15
n=C-2*index_L
for R in range(3):
if R==0:
stringa=s+str(n_FA)+s5+str(0)+')('+str(C)+'),'+'layer_5('+str(1)+')('+str(C)+'),'+'layer_5('+str(2)+')('+str(C)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
elif R==1:
stringa=s+str(n_FA)+s5+str(3)+')('+str(C)+'),'+'layer_5('+str(4)+')('+str(C)+'),'+'layer_5('+str(5)+')('+str(C)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
else:
stringa=s+str(n_FA)+s5+str(6)+')('+str(C)+'),'+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+2
n=n-4
n_FA=n_FA+1
F.write(stringa)
else:
if C==25:
index_L=12
elif C==26 or C==27:
index_L=13
elif C==28 or C==29:
index_L=14
elif C==30 or C==31:
index_L=15
else:
index_L=16
n=C-2*index_L
for R in range(3):
if R==0:
stringa=s+str(n_FA)+s5+str(0)+')('+str(C)+'),'+'layer_5('+str(1)+')('+str(C)+'),'+'layer_5('+str(2)+')('+str(C)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
elif R==1:
stringa=s+str(n_FA)+s5+str(3)+')('+str(C)+'),'+'layer_5('+str(4)+')('+str(C)+'),'+'layer_5('+str(5)+')('+str(C)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
else:
stringa=s+str(n_FA)+s5+str(6)+')('+str(C)+'),'+'layer_5('+str(7)+')('+str(C)+'),'+L[index_L]+str(n)+'),layer_4('+str(3+R)+')('+str(C)+'),layer_4('+str(R)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
#layer4: FA&HA to generate layer3
com='--layer4: FA&HA to generate layer3\n'
F.write(com)
s4=': fulladder port map(layer_4('
for C in range(8,61):
column=col+str(C)+'\n'
F.write(column)
if C==8 or C==60:
index_L=0
if C==60:
index_L=13
n=C-2*index_L
stringa=HA+str(n_HA)+HA_s+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),layer_3('+str(0)+')('+str(C)+'),layer_3('+str(0)+')('+str(C+1)+'));'+'\n'
n_HA=n_HA+1
F.write(stringa)
elif C==9 or C==59:
index_L=0
if C==59:
index_L=13
n=C-2*index_L
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_3('+str(1)+')('+str(C)+'),layer_3('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==10 or C==58:
index_L=0
if C==58:
index_L=12
n=C-2*index_L
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_3('+str(1)+')('+str(C)+'),layer_3('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=HA+str(n_HA)+HA_s+L[index_L+3]+str(n-6)+'),'+L[index_L+4]+str(n-8)+'),layer_3('+str(2)+')('+str(C)+'),layer_3('+str(1)+')('+str(C+1)+'));'+'\n'
n_HA=n_HA+1
F.write(stringa)
elif C==11:
index_L=0
stringa=s+str(n_FA)+FA_n+L[index_L]+str(C)+'),'+L[index_L+1]+str(C-2)+'),'+L[index_L+2]+str(C-4)+'),layer_3('+str(2)+')('+str(C)+'),layer_3('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
stringa=s+str(n_FA)+FA_n+L[index_L+3]+str(C-6)+'),'+L[index_L+4]+str(C-8)+'),'+L[index_L+5]+str(C-10)+'),layer_3('+str(3)+')('+str(C)+'),layer_3('+str(1)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==12 or C==57:
index_L=2
if C==57:
index_L=12
n=C-2*index_L
for R in range(2):
if R==0:
stringa=s+str(n_FA)+s4+str(0)+')('+str(C)+'),'+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),layer_3('+str(2+R)+')('+str(C)+'),layer_3('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+2
n=n-4
else:
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_3('+str(2+R)+')('+str(C)+'),layer_3('+str(R)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==13 or C==56:
index_L=3
if C==56:
index_L=13
n=C-2*index_L
for R in range(2):
if R==0:
stringa=s+str(n_FA)+s4+str(0)+')('+str(C)+'),'+'layer_4('+str(1)+')('+str(C)+'),'+L[index_L]+str(n)+'),layer_3('+str(2+R)+')('+str(C)+'),layer_3('+str(R)+')('+str(C+1)+'));'+'\n'
index_L=index_L+1
n=n-2
else:
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_3('+str(2+R)+')('+str(C)+'),layer_3('+str(R)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==14 or C==55:
index_L=5
if C==55:
index_L=14
n=C-2*index_L
for R in range(2):
if R==0:
stringa=s+str(n_FA)+s4+str(0)+')('+str(C)+'),'+'layer_4('+str(1)+')('+str(C)+'),'+'layer_4('+str(2)+')('+str(C)+'),layer_3('+str(2+R)+')('+str(C)+'),layer_3('+str(R)+')('+str(C+1)+'));'+'\n'
else:
stringa=s+str(n_FA)+FA_n+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),'+L[index_L+2]+str(n-4)+'),layer_3('+str(2+R)+')('+str(C)+'),layer_3('+str(R)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==15 or C==54:
index_L=6
if C==54:
index_L=15
n=C-2*index_L
for R in range(2):
if R==0:
stringa=s+str(n_FA)+s4+str(0)+')('+str(C)+'),'+'layer_4('+str(1)+')('+str(C)+'),'+'layer_4('+str(2)+')('+str(C)+'),layer_3('+str(2+R)+')('+str(C)+'),layer_3('+str(R)+')('+str(C+1)+'));'+'\n'
else:
stringa=s+str(n_FA)+s4+str(3)+')('+str(C)+'),'+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),layer_3('+str(2+R)+')('+str(C)+'),layer_3('+str(R)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==16 or C==53:
index_L=8
if C==53:
index_L=16
n=C-2*index_L
for R in range(2):
if R==0:
stringa=s+str(n_FA)+s4+str(0)+')('+str(C)+'),'+'layer_4('+str(1)+')('+str(C)+'),'+'layer_4('+str(2)+')('+str(C)+'),layer_3('+str(2+R)+')('+str(C)+'),layer_3('+str(R)+')('+str(C+1)+'));'+'\n'
else:
stringa=s+str(n_FA)+s4+str(3)+')('+str(C)+'),'+'layer_4('+str(4)+')('+str(C)+'),'+L[index_L]+str(n)+'),layer_3('+str(2+R)+')('+str(C)+'),layer_3('+str(R)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
else:
for R in range(2):
if R==0:
stringa=s+str(n_FA)+s4+str(0)+')('+str(C)+'),'+'layer_4('+str(1)+')('+str(C)+'),'+'layer_4('+str(2)+')('+str(C)+'),layer_3('+str(2+R)+')('+str(C)+'),layer_3('+str(R)+')('+str(C+1)+'));'+'\n'
else:
stringa=s+str(n_FA)+s4+str(3)+')('+str(C)+'),'+'layer_4('+str(4)+')('+str(C)+'),'+'layer_4('+str(5)+')('+str(C)+'),layer_3('+str(2+R)+')('+str(C)+'),layer_3('+str(R)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
#layer3: FA&HA to generate layer2
com='--layer3: FA&HA to generate layer2\n'
F.write(com)
s3=': fulladder port map(layer_3('
for C in range(6,63):
column=col+str(C)+'\n'
F.write(column)
if C==6 or C==62:
index_L=0
if C==62:
index_L=14
n=C-2*index_L
stringa=HA+str(n_HA)+HA_s+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),layer_2('+str(0)+')('+str(C)+'),layer_2('+str(0)+')('+str(C+1)+'));'+'\n'
n_HA=n_HA+1
F.write(stringa)
elif C==7:
index_L=0
stringa=s+str(n_FA)+FA_n+L[index_L]+str(C)+'),'+L[index_L+1]+str(C-2)+'),'+L[index_L+2]+str(C-4)+'),layer_2('+str(1)+')('+str(C)+'),layer_2('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==8 or C==61:
index_L=2
if C==61:
index_L=14
n=C-2*index_L
stringa=s+str(n_FA)+s3+str(0)+')('+str(C)+'),'+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),layer_2('+str(1)+')('+str(C)+'),layer_2('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==9 or C==60:
index_L=3
if C==60:
index_L=15
n=C-2*index_L
stringa=s+str(n_FA)+s3+str(0)+')('+str(C)+'),'+'layer_3('+str(1)+')('+str(C)+'),'+L[index_L]+str(n)+'),layer_2('+str(1)+')('+str(C)+'),layer_2('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
else:
stringa=s+str(n_FA)+s3+str(0)+')('+str(C)+'),'+'layer_3('+str(1)+')('+str(C)+'),'+'layer_3('+str(2)+')('+str(C)+'),layer_2('+str(1)+')('+str(C)+'),layer_2('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
#layer2: FA&HA to generate layer1
com='--layer2: FA&HA to generate layer1\n'
F.write(com)
s2=': fulladder port map(layer_2('
for C in range(4,64):
column=col+str(C)+'\n'
F.write(column)
if C==4:
index_L=0
stringa=HA+str(n_HA)+HA_s+L[index_L]+str(C)+'),'+L[index_L+1]+str(C-2)+'),layer_1('+str(0)+')('+str(C)+'),layer_1('+str(0)+')('+str(C+1)+'));'+'\n'
n_HA=n_HA+1
F.write(stringa)
elif C==5:
index_L=0
stringa=s+str(n_FA)+FA_n+L[index_L]+str(C)+'),'+L[index_L+1]+str(C-2)+'),'+L[index_L+2]+str(C-4)+'),layer_1('+str(1)+')('+str(C)+'),layer_1('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==6 or C==63:
index_L=2
if C==63:
index_L=15
n=C-2*index_L
stringa=s+str(n_FA)+s2+str(0)+')('+str(C)+'),'+L[index_L]+str(n)+'),'+L[index_L+1]+str(n-2)+'),layer_1('+str(1)+')('+str(C)+'),layer_1('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==7 or C==62:
index_L=3
if C==62:
index_L=16
n=C-2*index_L
stringa=s+str(n_FA)+s2+str(0)+')('+str(C)+'),'+'layer_2('+str(1)+')('+str(C)+'),'+L[index_L]+str(n)+'),layer_1('+str(1)+')('+str(C)+'),layer_1('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==8 or C==61:
index_L=4
if C==61:
index_L=16
n=C-2*index_L
stringa=s+str(n_FA)+s2+str(0)+')('+str(C)+'),'+'layer_2('+str(1)+')('+str(C)+'),'+L[index_L]+str(n)+'),layer_1('+str(1)+')('+str(C)+'),layer_1('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==9 or C==60:
index_L=4
if C==60:
index_L=16
n=C-2*index_L
stringa=s+str(n_FA)+s2+str(0)+')('+str(C)+'),'+'layer_2('+str(1)+')('+str(C)+'),'+L[index_L]+str(n)+'),layer_1('+str(1)+')('+str(C)+'),layer_1('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
elif C==10 or C==59:
index_L=5
if C==59:
index_L=16
n=C-2*index_L
stringa=s+str(n_FA)+s2+str(0)+')('+str(C)+'),'+'layer_2('+str(1)+')('+str(C)+'),'+L[index_L]+str(n)+'),layer_1('+str(1)+')('+str(C)+'),layer_1('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
else:
stringa=s+str(n_FA)+s2+str(0)+')('+str(C)+'),'+'layer_2('+str(1)+')('+str(C)+'),'+'layer_3('+str(3)+')('+str(C)+'),layer_1('+str(1)+')('+str(C)+'),layer_1('+str(0)+')('+str(C+1)+'));'+'\n'
n_FA=n_FA+1
F.write(stringa)
s='f_add1<=layer_1(0)(63)&'
x=63
while x:
if x==1:
s=s+'layer_1(0)('+str(x-1)+');'+'\n'
else:
s=s+'layer_1(0)('+str(x-1)+')&'
x=x-1
F.write(s)
s='f_add2<=layer_1(1)(63)&'
x=63
while x:
if x==1:
s=s+'layer_1(1)('+str(x-1)+');'+'\n'
else:
s=s+'layer_1(1)('+str(x-1)+')&'
x=x-1
F.write(s)
|
53f13961ee56f905fc74dc87c6e8343c52a7d3d0
|
[
"Tcl",
"Shell",
"Verilog",
"Python",
"VHDL"
] | 21 |
Tcl
|
FrancescoBellino97/isa_gr02_lab2
|
c7b05b77349481598efcba6178b1567408fd1c49
|
e5baedbebc2f845840ad66ae20d47bd6a44eab35
|
refs/heads/master
|
<file_sep># bootcamp
## 1. Biodata.html
#### Penjelasan program:
Program ini adalah untuk menampilkan **Format json** yang awalnya adalah objek dalam sebuahjavascript, Didalam file biodata.js terdapat program utama memiliki function myBiodata, dan objekorang bertype let, fungsi myBiodata me-return objek let orang,kemudian nilai kembali myBiodata yangberupa objek di ubah menjadi json format dengan perintah *JSON.stringify* & kemudian ditampilkan keconsole *(console.log)*.
#### Kegunaan JSON pada REST API
Kegunaan JSON pada REST API adalah Sebagai format data/resource yang dikirim antar aplikasi, atau format data/recource yang dikrim sebagai respon dari REST-Server kepada REST-Client.
##### Program yang dibutuhkan :
1. Code Editor (misal, [Visual Code Studio](https://code.visualstudio.com/))
2. Browser (misal, Mozilla Firefox)
3. [NodeJs](https://nodejs.org/)
##### Cara menjalankan :
##### Cara 1.
- Buka folder dengan terminal atau klick kanan
> pilih **Open in terminal** pada folder yang terdapat file *biodata.js*
- Ketikan **node biodata.js**
##### Cara 2.
- Buka Browser dan open link [ES6 Console](https://es6console.com/)
- klik kanan pada file **biodata.js**
> open with visual code studio
- Copy dan Paste-kan script ke link diatas
- Klik Run
---
## 2.Regex.js
#### Penjelasan program:
Regex biasa digunakan untuk validasi form.
**USERNAME**
`var usernameREGEX = /^[A-Za-z]{1}[A-Za-z0-9]{4,8}$/;`
```java
- /^[a-zA-Z]{1} = Hanya Karakter Huruf besar & kecil yang diperbolehkan diawal.(1 digit)
- [A-Za-z0-9] = Harus terdiri Huruf Besar,kecil dan angka.
- {4,8}$ = Terdiri dari 5-9 digit.(ditambah digit awal)
```
**PASSWORD**
`var passwordREGEX = /^(?=.*[A-Za-z])(?=.+[\d]+)(?=.*[=]+)(?=.*[#|?|@|!|$|%|^|&|*|-|_|=]+).{8,}$/;`
```java
- /^(?=.*[A-Za-z]) = Harus terdiri minimal masing-masing 1 kombinasi.(huruf kecil dan besar)
- (?=.*[\d]) = Harus terdiri minimal dari 1 digit angka.
- (?=.*[=]) = Harus terdiri minimal dari 1 simbol `=`.
- (?=.*[#|?|@|!|$|%|^|&|*|-|_|=]) = Harus terdiri minimal dari 1 karakter karakter spesial.
- . = Karakter sesuai ketentuan yang sudah ditulis sebelumnya.
- {8,}$/; = Harus terdiri minimal dari 8 karakter atau lebih.
```
#### Program yang dibutuhkan :
1. Browser (misal, Mozilla Firefox)
#### Cara menjalankan :
Biasanya digunakan dalam sebuah function, tapi disini saya akan menjalankannaya di online Editor
#### Cara 1.
- Buka Browser dan open link [Regexr](https://regexr.com/)
- Copy dan Paste-kan REGEX & input sesuai syarat karakternya.
- Bila dipojok kanan bertuliskan no match, berarti karakter belum memenuhi syarat regex
#### Cara 2.
- Buka folder dengan terminal atau klick kanan
> pilih **Open in terminal** pada folder yang terdapat file *2_regex.php*
- Ketikan **php 2_regex.php**
## 3_cetak_gambar.cpp
#### Penjelasan program:
Program ini terbuat dari bahasa pemrogramman C++,
#### Program yang dibutuhkan :
1. Browser (misal, Mozilla Firefox)
2. Terminal
#### Cara menjalankan :
Bisa dijalankan dionlline Editor, Terminal, Aplikasi atau program khusus tertentu.
#### Cara 1.
- Buka browser dan open link [Online Editor](https://www.onlinegdb.com/).
- Copy pastekan Code yang ada didalam file c++
#### Cara 2.
- Buka folder dengan terminal atau klick kanan
> pilih **Open in terminal** pada folder yang terdapat file *3_cetak_gambar.cpp*
- ketikan diterminal (untuk mengkompile file agar bisa dijalankan).
> g++ 3_cetak_gambar.cpp -o ./filehasilcompile
- Tunggu proses compile selesai.
> ketikan ./filehasilcompile
## 4_vowel.cpp
#### Penjelasan program:
Program ini terbuat dari bahasa pemrogramman C++,
#### Program yang dibutuhkan :
1. Browser (misal, Mozilla Firefox)
2. Terminal
#### Cara menjalankan :
Bisa dijalankan dionlline Editor, Terminal, Aplikasi atau program khusus tertentu.
#### Cara 1.
- Buka browser dan open link [Online Editor](https://www.onlinegdb.com/).
- Copy pastekan Code yang ada didalam file c++
#### Cara 2.
- Buka folder dengan terminal atau klick kanan
> pilih **Open in terminal** pada folder yang terdapat file *4_vowel.cpp*
- ketikan diterminal (untuk mengkompile file agar bisa dijalankan).
> g++ 4_vowel.cpp -o ./filehasilcompile
- Tunggu proses compile selesai.
> ketikan ./filehasilcompile
<file_sep>#include <iostream>
using namespace std;
bool isVowel(char huruf_hidup)
{
huruf_hidup = toupper(huruf_hidup);
return (huruf_hidup == 'A' || huruf_hidup == 'E' || huruf_hidup == 'I' ||
huruf_hidup == 'O' || huruf_hidup == 'U');
}
int hitungVowels(string kata)
{
int hitung = 0;
for (int i = 0; i < kata.length(); i++)
if (isVowel(kata[i])) // Check for vowel
++hitung;
return hitung;
}
// Main Calling Function
int main()
{
//string object
string kata = "programmer";
// Total numbers of Vowel
for (int i = 0; i < hitungVowels(kata); i++)
{
cout << kata << endl;
}
return 0;
}<file_sep><?php
$username_regex = '/^[A-Za-z]{1}[A-Za-z0-9]{5,31}$/';
$password_regex = '/^(?=.*[A-Za-z])(?=.+[\d]+)(?=.*[=]+)(?=.*[#|?|@|!|$|%|^|&|*|-|_|=]+).{8,}$/';
if (preg_match($username_regex, "Xrutaf888"))
{
echo 'True';
}
if (!preg_match($username_regex, "1Diana"))
{
echo 'False';
}
if (preg_match($password_regex, "<PASSWORD>="))
{
echo 'True';
}
if (!preg_match($password_regex, "<PASSWORD>!#"))
{
echo 'False';
}
?>
|
d225fcb23a63979ae345ecc388f1db877ad08c31
|
[
"Markdown",
"C++",
"PHP"
] | 3 |
Markdown
|
uznanbsr1945/BootcampArkademyBatch11-5
|
4a5149e1cf80cee990002da7eac4dda1abffd508
|
7cbeb42c6ea3afaa623c4a210bb1822aaaae1e86
|
refs/heads/master
|
<file_sep># yaf_trans
>translate yaf source code from C to PHP
# Why to do
>My english is poor, but github seems should use english. so , well , i will used to it as far as possible. maybe there will be some syntax error in the following notes, er....
>So , why I want to do this translate job?
Actually my purpose is very simple.
Framework yaf source code is written by C, when reading its code, it seems a little bit diffcult for the guy who do not familar with C, and even if master of C, you should learn HOW TO WRITE PHP EXTENSION at first. If just want to understanding the logic of the framework, it will waste some time at early stage for learning the necessary knowledage.
so, a few days earlier, when i read the yaf source code, suddenly the ideal came into my mind.
>This job will take some time to finish. welcome to exchange.
|
8739ef8e70c38760d7c65502ba8feb40d4231aba
|
[
"Markdown"
] | 1 |
Markdown
|
jonnyvr/yaf_trans
|
d4211e52b656bac058cd83d486e54fd73994c3ec
|
51f95b8e5a9dea2cc14935dd936a6484c9a297a8
|
refs/heads/master
|
<file_sep># hassio-addons
Addons for HomeAssistannt's HassIO.
<file_sep># Home Assistant Community Add-on: Portainer
[![License][license-shield]](LICENSE.md)
![Supports aarch64 Architecture][aarch64-shield]
![Supports amd64 Architecture][amd64-shield]
![Supports armhf Architecture][armhf-shield]
![Supports armv7 Architecture][armv7-shield]
![Supports i386 Architecture][i386-shield]
Manage your Docker environment with ease.
## About
Portainer is an open-source lightweight management UI which allows you to
easily manage a Docker host(s) or Docker swarm clusters.
It has never been so easy to manage Docker. Portainer provides a detailed
overview of Docker and allows you to manage containers, images, networks and
volumes.
[:books: Read the full add-on documentation][docs]
## WARNING
The Portainer add-on is really powerful and gives you access to virtually
your whole system. While this add-on is created and maintained with care and
with security in mind, in the wrong or inexperienced hands,
it could damage your system.
## Contributing
This is an active open-source project. We are always open to people who want to
use the code or contribute to it.
Thank you for being involved! :heart_eyes:
## Authors & contributors
The original addon was developed by [<NAME>][frenck]. Since he no longer develops the addon, it can be obtained here.
## License
MIT License
Copyright (c) 2018-2021 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
[aarch64-shield]: https://img.shields.io/badge/aarch64-yes-green.svg
[amd64-shield]: https://img.shields.io/badge/amd64-yes-green.svg
[armhf-shield]: https://img.shields.io/badge/armhf-yes-green.svg
[armv7-shield]: https://img.shields.io/badge/armv7-yes-green.svg
[i386-shield]: https://img.shields.io/badge/i386-no-red.svg
[license-shield]: https://img.shields.io/github/license/hassio-addons/addon-portainer.svg
[frenck]: https://github.com/frenck
[docs]: https://github.com/stefangries/hassio-addons/blob/master/portainer/README.md<file_sep># Rsync Backups add-on for Home Assistant
Transfers directories from your Home Assistant instance to a remote rsync server.
## Instalation
Go to your Add-on Store in the Supervisor panel and add https://github.com/stefangries/hassio-addons to your repositories.
Afterwards the addon can be installed via the UI.
## Configuration
This section describes each of the add-on configuration options.
Example add-on configuration:
```
server: 192.168.178.12
port: 22
directory:
- source: /backup/
destination: /volume1/NetBackup/HomeAssistant/backups/
flags: '-av'
- source: /share/NextCloud/
destination: /volume1/NetBackup/HomeAssistant/nextcloud/
flags: '-av --delete'
username: my_rsync_username
password: <PASSWORD>
auto_purge: 0
```
### Option: `server` (required)
Server host or IP, e.g. `localhost`, a Domain or an IP.
### Option: `port` (required)
Server ssh port, e.g. `22`.
### Option: `directory` (required)
A list of backup tasks. Each tasks consists of the following values:
#### Option: `source` (required)
Directory on the Home Assistant instance that should be backed up, e.g. `/share/myfolder/`.
#### Option: `destination` (required)
Directory on the destination Server where your backup should be placed, e.g. `/volume1/NetBackup/HomeAssistant/`.
#### Option: `flags` (required)
Options which should be passed to rsync, e.g. `-av`. When copying recursive directories, use `-av -r`. If you like to delete files at the destiation, which are missing at the source, use `-av --delete`.
All options are documented at https://download.samba.org/pub/rsync/rsync.1.
### Option: `username` (required)
Server ssh user, e.g. `root`.
### Option: `password` (required)
Server ssh password, e.g. `<PASSWORD>`.
### Option: `auto_purge` (required)
This addon is able to delete old backup files in your `/backup` folder after syncronizing them.
The number of recent backups keep in Home Assistant, e.g. "5". Set to "0" to disable automatic deletion of backups.
The `auto_purge` option is only available for your `/backup` folder!
## How to use
Run addon in the automation, example automation below:
```yaml
- alias: 'hassio_daily_backup'
trigger:
platform: 'time'
at: '3:00:00'
action:
- service: 'hassio.snapshot_full'
data_template:
name: "Automated Backup {{ now().strftime('%Y-%m-%d') }}"
password: !secret <PASSWORD>
# wait for snapshot done, then sync snapshots
- delay: '00:10:00'
- service: 'hassio.addon_start'
data:
addon: '69c7aa1d_rsync_backups_sgr'
```
# Credits
This Addon is based on the great work of <NAME>, available at https://github.com/tykarol/homeassistant-addon-rsync-backup.
|
32a812a2a4bf05c8c1da2ad803c9f97b30da6f82
|
[
"Markdown"
] | 3 |
Markdown
|
stefangries/hassio-addons
|
fdd603d8bd9509c0dc532e4a6e3bd7404b86ad0a
|
ba075a8614b7815ee56929102f20b8b1d5bf5cc6
|
refs/heads/master
|
<file_sep>gravatars:
-
hash: 'de89dceb54a28b2aa952663cc94d60fc'
-
hash: 'cd0c263b28fce0e1d89a0002cc75648b'
-
hash: '8f9968630845dc22fffdb581c54324e8'
-
hash: 'o-hash-md5-do-seu-amigo-aqui'
<file_sep>---
layout: default
title: Ruby on Rio
address: DTM - Travessa do Ouvidor, 17 - 501, Centro, Rio de Janeiro
events:
-
day: 15
month: Fevereiro
status: "next"
-
day: 15
month: Março
status: "future"
-
day: 19
month: Abril
status: "future"
-
day: 17
month: Maio
status: "future"
-
day: 21
month: Junho
status: "future"
-
day: 19
month: Julho
status: "future"
-
day: 20
month: Setembro
status: "future"
-
day: 18
month: Outubro
status: "future"
-
day: 20
month: Dezembro
status: "future"
---
<section class="centralized">
<article class="next-meetup">
<h2>Próximo Encontro: </h2>
<p><i class="icon-map-marker icon-white"></i>{{ page.address }}</p>
{% for event in page.events %}
{% if event.status == "next" %}
<p><i class="icon-time icon-white"></i>Sábado, {{ event.day }} de {{ event.month }} de 2014 às 13:00 ~ 18:00</p>
{% endif %}
{% endfor %}
</article>
<article class="about">
<h2>Bem vindo ao site do Ruby on Rio</h2>
<p>O Ruby on Rio é o grupo de usuários de Ruby do Rio de Janeiro. O grupo nasceu como forma de unir desenvolvedores e pessoas interessadas na linguagem de programação Ruby.</p>
<p>No grupo falamos sobre Ruby, Rails e outras tecnologias relacionadas. O grupo funciona como um meio para aproximar pessoas para de troca de conhecimento, seja para aprender ou ensinar Ruby e seu vasto ecossistema de frameworks, bibliotecas e aplicações.</p>
<h2>Encontros presenciais</h2>
<p>Realizamos encontros presencias mensalmente. Nesses encontros, fazemos apresentações, codificamos aplicações e projetos open source, regamos a muito bate papo sobre Ruby e outras tecnologias.</p>
<p>Para acompanhar o que acontece na Ruby on Rio, <a href="https://groups.google.com/forum/?fromgroupsrubyonrio#!forum/rubyonrio">faça parte da lista de discução</a>.</p>
</article>
<article class="next-meetup">
<h2>Encontros futuros: </h2>
<p><i class="icon-map-marker icon-white"></i>{{ page.address }}</p>
{% for event in page.events %}
{% if event.status == "future" %}
<p><i class="icon-time icon-white"></i>Sábado, {{ event.day }} de {{ event.month }} de 2014 às 13:00 ~ 18:00</p>
{% endif %}
{% endfor %}
</article>
</section>
|
330ae3e287319690148196960b15ef0cbb67f62f
|
[
"HTML",
"YAML"
] | 2 |
HTML
|
tauil/rubyonrio.github.com
|
5670e39a420136eb8d79931e72cb25fe95bc9ee9
|
e5f03ff0633e0b84e9cc85b88cd6650fe75b26f0
|
refs/heads/master
|
<repo_name>artushmkrtchyan/react-redux-saga<file_sep>/src/modules/auth/container/loginContainer.js
import React, {Component} from 'react'
import {Form} from 'antd';
import {Login} from '../components'
class LoginContainer extends Component {
handleSubmit = e => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
}
});
};
render () {
const { getFieldDecorator } = this.props.form;
return <Login handleSubmit = {this.handleSubmit} getFieldDecorator={getFieldDecorator}/>
}
}
export default Form.create()(LoginContainer);<file_sep>/src/modules/auth/components/login/index.js
import React from 'react';
import {Link} from "react-router-dom";
import {Form, Icon, Input, Button} from 'antd';
import styles from './login.module.css'
const Login = ({getFieldDecorator, handleSubmit}) => {
return (
<Form onSubmit={handleSubmit} className={styles.loginForm}>
<Form.Item>
{getFieldDecorator('username', {
rules: [{required: true, message: 'Please input your username!'}],
})(
<Input
prefix={<Icon type="user" style={{color: 'rgba(0,0,0,.25)'}}/>}
placeholder="Username"
/>,
)}
</Form.Item>
<Form.Item>
{getFieldDecorator('password', {
rules: [{required: true, message: 'Please input your Password!'}],
})(
<Input
prefix={<Icon type="lock" style={{color: 'rgba(0,0,0,.25)'}}/>}
type="password"
placeholder="<PASSWORD>"
/>,
)}
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" className={styles.loginFormButton}>
Log in
</Button>
Or <Link to="/register">register now!</Link>
</Form.Item>
</Form>
);
}
export default Login;<file_sep>/src/modules/auth/components/register/index.js
import React from 'react';
import {Form, Input, Tooltip, Icon, Button} from 'antd';
import styles from './register.module.css'
const Register = ({getFieldDecorator, handleSubmit, validateToNextPassword, compareToFirstPassword, handleConfirmBlur}) => {
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 8 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 16 },
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 16,
offset: 8,
},
},
};
return (
<Form {...formItemLayout} onSubmit={handleSubmit} className={styles.registerForm}>
<Form.Item label="E-mail">
{getFieldDecorator('email', {
rules: [
{
type: 'email',
message: 'The input is not valid E-mail!',
},
{
required: true,
message: 'Please input your E-mail!',
},
],
})(<Input/>)}
</Form.Item>
<Form.Item label="Password" hasFeedback>
{getFieldDecorator('password', {
rules: [
{
required: true,
message: 'Please input your password!',
},
{
validator: validateToNextPassword,
},
],
})(<Input.Password/>)}
</Form.Item>
<Form.Item label="Confirm Password" hasFeedback>
{getFieldDecorator('confirm', {
rules: [
{
required: true,
message: 'Please confirm your password!',
},
{
validator: compareToFirstPassword,
},
],
})(<Input.Password onBlur={handleConfirmBlur}/>)}
</Form.Item>
<Form.Item
label={
<span>
Nickname
<Tooltip title="What do you want others to call you?">
<Icon type="question-circle-o"/>
</Tooltip>
</span>
}
>
{getFieldDecorator('nickname', {
rules: [{required: true, message: 'Please input your nickname!', whitespace: true}],
})(<Input/>)}
</Form.Item>
<Form.Item {...tailFormItemLayout}>
<Button type="primary" htmlType="submit" className={styles.registerFormButton}>
Register
</Button>
</Form.Item>
</Form>
);
}
export default Register;<file_sep>/src/service/index.js
import { fetcher, uploadFetcher } from './fetch'
export default {
user: (id) => fetcher(`/users/${id}`),
users: (count) => fetcher(`/users?_limit=${count}`)
}<file_sep>/src/modules/users/redux/actions.js
import {createActions} from 'reduxsauce';
export const { Types: UsersTypes, Creators: UsersActionCreators} = createActions ({
getUsersRequest: ['count'],
getUsersSuccess: ['data'],
getUsersFailure: ['error'],
getUserByIdRequest: ['id'],
getUserByIdSuccess: ['data'],
getUserByIdFailure: ['error']
});<file_sep>/src/modules/auth/container/index.js
import LoginContainer from './loginContainer';
import RegisterContainer from './registerContainer';
export {
LoginContainer,
RegisterContainer
}<file_sep>/src/modules/users/container/index.js
import React, {Component} from 'react';
import {bindActionCreators} from "redux";
import {connect} from "react-redux";
import {getUsers, getUser} from "../redux/selectors";
import {UsersActionCreators} from "../redux/actions";
class Users extends Component{
componentDidMount(){
this.props.getUsersRequest(3)
this.props.getUserByIdRequest(5)
}
render(){
console.log("props: ", this.props)
return(
<div>Users list</div>
)
}
}
const mapStateToProps = (state) => ({
users: getUsers(state),
user: getUser(state),
});
const mapDispatchToProps = (dispatch) => {
return bindActionCreators(UsersActionCreators, dispatch)
};
export default connect(mapStateToProps, mapDispatchToProps)(Users);<file_sep>/src/modules/users/redux/reducers.js
import {createReducer} from 'reduxsauce';
import {UsersTypes} from './actions';
export const users = {
users: [],
error: "",
loading: false,
user: []
};
export const getUsersRequest = (state) => {
return {...state, loading: true};
};
export const getUsersSuccess = (state, action) => {
return {...state, users: action.data, error: "", loading: false};
};
export const getUsersFailure = (state, action) => {
return {...state, error: action.error, users: {}, loading: false};
};
export const getUserByIdRequest = (state) => {
return {...state};
};
export const getUserByIdSuccess = (state, action) => {
return {...state, user: action.data, error: ""};
};
export const getUserByIdFailure = (state, action) => {
return {...state, error: action.error, user: {}};
};
export const handlers = {
[UsersTypes.GET_USERS_REQUEST]: getUsersRequest,
[UsersTypes.GET_USERS_SUCCESS]:getUsersSuccess,
[UsersTypes.GET_USERS_FAILURE]: getUsersFailure,
[UsersTypes.GET_USER_BY_ID_REQUEST]: getUserByIdRequest,
[UsersTypes.GET_USER_BY_ID_SUCCESS]: getUserByIdSuccess,
[UsersTypes.GET_USER_BY_ID_FAILURE]: getUserByIdFailure
};
export default createReducer(users, handlers);<file_sep>/src/modules/auth/container/registerContainer.js
import React, {Component} from 'react'
import {Form} from 'antd';
import {Register} from '../components'
class RegisterContainer extends Component {
state = {
confirmDirty: false,
};
handleSubmit = e => {
e.preventDefault();
this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
}
});
};
handleConfirmBlur = e => {
const {value} = e.target;
this.setState({confirmDirty: this.state.confirmDirty || !!value});
};
compareToFirstPassword = (rule, value, callback) => {
const {form} = this.props;
if (value && value !== form.getFieldValue('password')) {
callback('Two passwords that you enter is inconsistent!');
} else {
callback();
}
};
validateToNextPassword = (rule, value, callback) => {
const {form} = this.props;
if (value && this.state.confirmDirty) {
form.validateFields(['confirm'], {force: true});
}
callback();
};
render() {
const {getFieldDecorator} = this.props.form;
return (
<Register
handleSubmit={this.handleSubmit}
getFieldDecorator={getFieldDecorator}
validateToNextPassword={this.validateToNextPassword}
compareToFirstPassword={this.compareToFirstPassword}
handleConfirmBlur={this.handleConfirmBlur}
/>
)
}
}
export default Form.create()(RegisterContainer);<file_sep>/src/routes/index.js
import React from 'react';
import {Router, Switch, Redirect} from 'react-router-dom';
import Home from '../modules/home';
import {history} from '../helpers';
import {PrivateRoute} from './privateRoute';
import {PublicRoute} from './publicRoute';
import {LoginContainer, RegisterContainer} from '../modules/auth/container'
import NotFound from "../modules/notFound";
class Routes extends React.Component {
render() {
return <Router history={history}>
<Switch>
<PublicRoute exact path="/" component={Home}/>
<PublicRoute exact path="/login" component={LoginContainer}/>
<PublicRoute exact path="/register" component={RegisterContainer}/>
<PublicRoute path='/404' component={NotFound}/>
<Redirect from='*' to='/404'/>
</Switch>
</Router>;
}
}
export default Routes;
<file_sep>/src/modules/users/redux/selectors.js
export const getUsers = state => state.users.users;
export const getUser = state => state.users.user;<file_sep>/src/modules/users/redux/sagas.js
import {UsersTypes, UsersActionCreators} from "./actions";
import { takeLatest, put, call } from "redux-saga/effects";
import {delay} from "../../../helpers";
import service from "../../../service";
export function* getUsers(params) {
try {
const users = yield call(() => {
return service.users(params.count)
});
yield delay(2000);
yield put(UsersActionCreators.getUsersSuccess(users));
} catch (e) {
yield put(UsersActionCreators.getUsersFailure(e.message));
}
}
export function* getUserById(params) {
try {
const users = yield call(() => {
return service.user(params.id)
});
yield delay(4000);
yield put(UsersActionCreators.getUserByIdSuccess(users));
} catch (e) {
yield put(UsersActionCreators.getUserByIdFailure(e.message));
}
}
export function* usersSaga() {
yield takeLatest(UsersTypes.GET_USERS_REQUEST, getUsers);
yield takeLatest(UsersTypes.GET_USER_BY_ID_REQUEST, getUserById);
}
export default usersSaga;
<file_sep>/src/modules/layouts/public/index.js
import React from 'react';
import {Link} from "react-router-dom";
import {Layout, Menu} from 'antd';
const { Header, Footer } = Layout;
const PublicLayout = (props) => {
return (
<div className="container">
<Layout>
<Header className="header">
<div className="logo"/>
<Menu
theme="dark"
mode="horizontal"
defaultSelectedKeys={['1']}
style={{lineHeight: '64px'}}
>
<Menu.Item key="1">nav 1</Menu.Item>
<Menu.Item key="2"><Link to="/login">Login</Link></Menu.Item>
<Menu.Item key="3"><Link to="/register">Register</Link></Menu.Item>
</Menu>
</Header>
{props.children}
<Footer>Footer</Footer>
</Layout>
</div>
);
};
export default PublicLayout<file_sep>/src/store/root-saga.js
import {all, spawn} from "redux-saga/effects";
import usersSaga from "../modules/users/redux/sagas";
export default function* rootSaga() {
yield all([
spawn(usersSaga),
]);
}
|
8c10ef30d571fad14b41f5499ad92fab7bc1b9c2
|
[
"JavaScript"
] | 14 |
JavaScript
|
artushmkrtchyan/react-redux-saga
|
9c698ae1b6150917743c2f8ddcf4104e698da9ed
|
2275fdd8d31828ef3ebd69b62fb9a407f655fb40
|
refs/heads/master
|
<file_sep><nav class="cover-navigation navigation--social">
<ul class="navigation">
<!-- Weibo -->
<li class="navigation__item">
<a href="http://weibo.com/525567789" title="微博" target="_blank">
<i class='social fa fa-weibo'></i>
<span class="label">Weibo</span>
</a>
</li>
<!-- Github -->
<li class="navigation__item">
<a href="https://github.com/liuzhiyi1992" title="Github" target="_blank">
<i class='social fa fa-github'></i>
<span class="label">Github</span>
</a>
</li>
<!-- Instagram -->
<li class="navigation__item">
<a href="https://www.instagram.com/liuzhiyilosemyself" title="Instagram" target="_blank">
<i class='social fa fa-instagram'></i>
<span class="label">Instagram</span>
</a>
</li>
<!-- Album -->
<li class="navigation__item">
<a href="http://forv.pp.163.com/" title="Album" target="_blank">
<i class='social fa fa-github-alt'></i>
<span class="label">Album</span>
</a>
</li>
<!-- Twitter -->
<!--
<li class="navigation__item">
<a href="http://twitter.com" title="@twitter" target="_blank">
<i class='social fa fa-twitter'></i>
<span class="label">Twitter</span>
</a>
</li>
-->
<!-- jianshu -->
<li class="navigation__item">
<a href="http://www.jianshu.com/users/e2ed12011d4f/latest_articles/" title="简书" target="_blank">
<i class='social fa fa-book'></i>
<span class="label">简书</span>
</a>
</li>
<!-- RSS -->
<li class="navigation__item">
<a href="{{@blog.url}}/rss/" rel="author" title="RSS订阅" target="_blank">
<i class='social fa fa-rss'></i>
<span class="label">RSS</span>
</a>
</li>
<!-- Email -->
<li class="navigation__item">
<a href="mailto:<EMAIL>" title="邮件联系我">
<i class='social fa fa-envelope'></i>
<span class="label">Email</span>
</a>
</li>
</ul>
</nav>
<file_sep><header class="panel-cover {{#if post}}panel-cover--collapsed{{/if}}" {{#if @blog.cover}}style="background-image: url({{@blog.cover}})"{{/if}}>
<div class="panel-main">
<div class="panel-main__inner panel-inverted">
<div class="panel-main__content">
{{#if @blog.logo}}
<a href="{{@blog.url}}" title="前往 {{@blog.title}} 的主页"><img src="{{@blog.logo}}" width="80" alt="{{@blog.title}} logo" class="panel-cover__logo logo" /></a>
{{/if}}
<h1 class="panel-cover__title panel-title"><a href="{{@blog.url}}" title="前往 {{@blog.title}} 的主页">{{@blog.title}}</a></h1>
<br>
<br>
<span class="panel-cover__subtitle panel-subtitle">{{@blog.description}}</span>
<hr class="panel-cover__divider" />
<br>
<p class="panel-cover__description"><a href="https://github.com/liuzhiyi1992/MyshareBlogs">前些
天博客服务器的数据出问题了,现在换了搬瓦工,部分文章丢失 </a></p>
<hr class="panel-cover__divider" />
<p class="panel-cover__description"><a href="https://github.com/liuzhiyi1992/MyshareBlogs">文章内容会同步更新在 我的Github Wiki 中,欢迎大家订阅支持!! </a></p>
<!--
<hr class="panel-cover__divider panel-cover__divider--secondary" />
-->
<div class="navigation-wrapper">
<div>
<nav class="cover-navigation cover-navigation--primary">
<ul class="navigation">
<li class="navigation__item"><a href="/#blog" title="访问博客" class="blog-button">博客</a></li>
<li class="navigation__item"><a href="https://github.com/liuzhiyi1992" target="_blank" title="我的项目">项目</a></li>
<!-- <li class="navigation__item"><a href="zyden.vicp.cc" title="了解更多关于我">关于</a></li> -->
<li class="navigation__item"><a href="http://zyden.vicp.cc/rss-reader/" title="通过rss/邮件订阅本站">订阅</a></li>
<li class="navigation__item"><a href="http://vicp.us13.list-manage.com/subscribe?u=9c7df664aaa129b72fea203f4&id=880ce224bc" title="通过邮件订阅本站">邮件订阅</a></li>
<li class="navigation__item"><a href="http://zyden.vicp.cc/friendlylink/" title="">友情链接</a></li>
</ul>
</nav>
</div>
<div>
{{> social}}
</div>
</div>
</div>
</div>
<!--
<div class="panel-cover--overlay cover-touming"></div>
-->
</div>
</header>
|
c9d0f5dd9e11f848301e684b610fdb94393e6254
|
[
"Handlebars"
] | 2 |
Handlebars
|
liuzhiyi1992/GhostTheme
|
984099c7622518b1f19f82a05067e28a31774f1c
|
c5dd1bffcbf1f3ad06224004b7fae7e9bd01770a
|
refs/heads/master
|
<repo_name>dloyd1/rails-dynamic-request-lab-nyc-web-091718<file_sep>/app/controllers/show_controller.rb
# class ShowController < ApplcationController
#
# def Show
# @s1 = Student.find(params[:id])
# @names = @s1.fist_name + " " + @s1.last_name}
#
# end
# end
#
|
2108dfc6adc01fd03868c39b7d3655c0dc48f98c
|
[
"Ruby"
] | 1 |
Ruby
|
dloyd1/rails-dynamic-request-lab-nyc-web-091718
|
27007b9150165cea5541a2656cd0d985982fbb6c
|
ca9c439112b278919e4d79af8b92efe5a9795ad8
|
refs/heads/master
|
<file_sep># winder - this is a awesome UI framwork using vue
- author: <NAME>
注意: parcel使用时需要[配置package.json](https://cn.vuejs.org/v2/guide/installation.html), 同时注意清理缓存 --no-cache
## Introduction
## Ecosystem
## Documentation
## Questions
## Issues
## Changelog
<file_sep>/**
* 暂时作为项目的入口文件
*/
import Vue from 'vue'
import Button from './button.vue'
Vue.component('w-button', Button)
new Vue({
el: '#app',
})
|
22e5709007402a0dfaa88f9228816515404ce38d
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
codevvvv9/winder
|
5b2e0057329e11ea88bbe729fcb90b001944738d
|
09f854b010845c40a168a3f2e37bbbe2c41b35dd
|
refs/heads/main
|
<file_sep># LEAP-4.0-Major-Project
|
49ccd6c23a8b1bb9d6d3801e64aef22ad3e98528
|
[
"Markdown"
] | 1 |
Markdown
|
ProLEAP-Academy/LEAP-4.0-Major-Project
|
397607d1b7a2cc4836fa2c5ca9810c3fa06a231d
|
d237e221e285dc209e41201c14c46fe86f0797f0
|
refs/heads/master
|
<repo_name>shamil-gadelshin/mock_demo_node<file_sep>/runtime/src/complex_prices/tests.rs
#![cfg(test)]
use super::*;
use frame_support::{impl_outer_origin, parameter_types, weights::Weight};
use sp_core::H256;
use sp_runtime::{
testing::Header,
traits::{BlakeTwo256, IdentityLookup},
Perbill,
};
use std::cell::RefCell;
use std::panic;
use std::rc::Rc;
impl_outer_origin! {
pub enum Origin for Test {}
}
// For testing the module, we construct most of a mock runtime. This means
// first constructing a configuration type (`Test`) which `impl`s each of the
// configuration traits of modules we want to use.
#[derive(Clone, Eq, PartialEq)]
pub struct Test;
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: Weight = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);
}
impl system::Trait for Test {
type Origin = Origin;
type Call = ();
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = ();
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
type ModuleToIndex = ();
}
impl Trait for Test {
type DiscountHandlerProvider = TestDiscountProvider;
}
impl discounts::Trait for Test {}
type ComplexPrices = Module<Test>;
// This function basically just builds a genesis storage key/value store according to
// our desired mockup.
fn new_test_ext() -> sp_io::TestExternalities {
system::GenesisConfig::default()
.build_storage::<Test>()
.unwrap()
.into()
}
// Intercepts panic method
// Returns: whether panic occurred
fn panics<F: std::panic::RefUnwindSafe + Fn()>(could_panic_func: F) -> bool {
{
let default_hook = panic::take_hook();
panic::set_hook(Box::new(|info| {
println!("{}", info);
}));
// intercept panic
let result = panic::catch_unwind(|| could_panic_func());
//restore default behaviour
panic::set_hook(default_hook);
result.is_err()
}
}
pub struct TestDiscountProvider;
impl super::DiscountHandlerProvider for TestDiscountProvider {
/// Returns StakeHandler. Mock entry point for stake module.
fn discounts() -> Rc<dyn super::DiscountHandler> {
THREAD_LOCAL_DISCOUNT_PROVIDER.with(|f| f.borrow().clone())
}
}
// 1. RefCell - thread_local! mutation pattern
// 2. Rc - ability to have multiple references
thread_local! {
pub static THREAD_LOCAL_DISCOUNT_PROVIDER:
RefCell<Rc<dyn super::DiscountHandler>> = RefCell::new(Rc::new(super::DefaultDiscountHandler{
marker: PhantomData::<Test> {},
}));
}
// Sets stake handler implementation in hiring module. Mockall frameworks integration
pub(crate) fn setup_discount_provider_mock(mock: Rc<dyn super::DiscountHandler>) {
THREAD_LOCAL_DISCOUNT_PROVIDER.with(|f| {
*f.borrow_mut() = mock.clone();
});
}
// Tests mock expectation and restores default behaviour
pub(crate) fn test_expectation_and_clear_mock() {
setup_discount_provider_mock(Rc::new(super::DefaultDiscountHandler {
marker: PhantomData::<Test> {},
}));
}
// Intercepts panic in provided function, test mock expectation and restores default behaviour
pub(crate) fn handle_mock<F: std::panic::RefUnwindSafe + Fn()>(func: F) {
let panicked = panics(func);
test_expectation_and_clear_mock();
assert!(!panicked);
}
#[test]
fn calculate_price_succeeds() {
new_test_ext().execute_with(|| {
ComplexPrices::store_price(1, 100, Some(5));
assert_eq!(ComplexPrices::calculate_price(1), 95);
});
}
#[test]
fn calculate_price_succeeds_with_custom_discount_provider() {
struct CustomDiscountHandler;
impl DiscountHandler for CustomDiscountHandler {
fn store_custom_discount(&self, _price: u32, _discount: u32) {}
fn calculate_discount(&self, _item_id: u32, _base_price: u32) -> u32 {
50
}
}
new_test_ext().execute_with(|| {
let custom_mock = Rc::new(CustomDiscountHandler {});
setup_discount_provider_mock(custom_mock);
ComplexPrices::store_price(1, 100, None);
assert_eq!(ComplexPrices::calculate_price(1), 50);
});
}
#[test]
fn calculate_price_succeeds_with_feature_rich_mocks() {
handle_mock(|| {
new_test_ext().execute_with(|| {
let mock = {
let mut mock = super::MockDiscountHandler::new();
mock.expect_calculate_discount()
.times(1)
.returning(|_, _| 70);
mock.expect_store_custom_discount()
.times(1)
.returning(|_, _| ());
Rc::new(mock)
};
setup_discount_provider_mock(mock.clone());
ComplexPrices::store_price(1, 100, Some(70));
assert_eq!(ComplexPrices::calculate_price(1), 30);
})
});
}
<file_sep>/runtime/src/complex_prices/mod.rs
use frame_support::{decl_module, decl_storage};
use super::discounts;
use sp_std::marker::PhantomData;
use sp_std::rc::Rc;
#[cfg(test)]
mod tests;
#[cfg(test)]
use mockall::predicate::*;
#[cfg(test)]
use mockall::*;
/// The module's configuration trait.
pub trait Trait: system::Trait + discounts::Trait {
type DiscountHandlerProvider: DiscountHandlerProvider;
}
decl_storage! {
trait Store for Module<T: Trait> as ComplexPrices {
PriceByItemId get(get_base_price): map u32 => Option<u32>;
}
}
decl_module! {
/// The module declaration.
pub struct Module<T: Trait> for enum Call where origin: T::Origin {}
}
impl<T: Trait> Module<T> {
pub fn store_price(item_id: u32, price: u32, custom_discount: Option<u32>) {
PriceByItemId::insert(item_id, price);
if let Some(discount) = custom_discount {
T::DiscountHandlerProvider::discounts().store_custom_discount(item_id, discount);
}
}
pub fn calculate_price(item_id: u32) -> u32 {
let base_price = PriceByItemId::get(item_id).unwrap();
let discount =
T::DiscountHandlerProvider::discounts().calculate_discount(item_id, base_price);
base_price - discount
}
}
#[cfg_attr(test, automock)]
pub trait DiscountHandler {
fn store_custom_discount(&self, item_id: u32, discount: u32);
fn calculate_discount(&self, item_id: u32, base_price: u32) -> u32;
}
pub(crate) struct DefaultDiscountHandler<T: Trait> {
marker: PhantomData<T>,
}
impl<T: Trait> DiscountHandler for DefaultDiscountHandler<T> {
fn store_custom_discount(&self, item_id: u32, discount: u32) {
<discounts::Module<T>>::store_custom_discount(item_id, discount);
}
fn calculate_discount(&self, item_id: u32, base_price: u32) -> u32 {
<discounts::Module<T>>::calculate_discount(item_id, base_price)
}
}
pub trait DiscountHandlerProvider {
fn discounts() -> Rc<dyn DiscountHandler>;
}
impl<T: Trait> DiscountHandlerProvider for Module<T> {
fn discounts() -> Rc<dyn DiscountHandler> {
Rc::new(DefaultDiscountHandler::<T> {
marker: PhantomData,
})
}
}
<file_sep>/README.md
## Substrate modules mocks
This project demostrates how to use mocks with Parity Substrate modules. It contains 'toy' examples and aims to demontrate mocking techniques.
Mocking framework:
- [Mockall](https://docs.rs/mockall/0.6.0/mockall/)
### Motivation
You can use mocks when you want to test modules independently. If module A is dependent on module B and next version of module B is not ready or it contains a bug - mocking can be very useful.
### Description
Project contains two substrate modules and their tests:
- discounts
- complex_prices
**complex_prices** modules depend on **discounts** module in order to calculate price.
### Complex_prices
If you need feature-rich mocks or stateful mocks you can create *mockall* solution, with some additional abstraction layers when use dependent **discounts** module.
Simpler example - how to test the substrate module - you can find [here.](https://substrate.dev/recipes/testing/externalities.html)
<file_sep>/runtime/src/discounts/mod.rs
use frame_support::{decl_module, decl_storage};
#[cfg(test)]
mod tests;
/// The module's configuration trait.
pub trait Trait: system::Trait {}
decl_storage! {
trait Store for Module<T: Trait> as Discounts {
DiscountByItemId get(get_discount): map u32 => Option<u32>;
}
}
decl_module! {
/// The module declaration.
pub struct Module<T: Trait> for enum Call where origin: T::Origin {}
}
impl<T: Trait> Module<T> {
pub fn store_custom_discount(item_id: u32, discount: u32) {
DiscountByItemId::insert(item_id, discount);
}
pub fn calculate_discount(item_id: u32, base_price: u32) -> u32 {
let custom_discount = DiscountByItemId::get(item_id);
if let Some(discount) = custom_discount {
discount
} else if base_price > 50 {
20
} else {
0
}
}
}
|
f3d21d21f9fab62cd4eec33af0516f0c5166c619
|
[
"Rust",
"Markdown"
] | 4 |
Rust
|
shamil-gadelshin/mock_demo_node
|
c498cbf826706b4bd83dc80db13e708c9fff6a12
|
4160f4776d2f8a4ebf2b4c7e86f483221c25c5c8
|
refs/heads/master
|
<repo_name>poliveir/so_long<file_sep>/source_files/get_next_line.c
#include "../header_files/so_long.h"
int get_next_line(int fd, char **line)
{
int ret;
char *temp;
char buf[2];
if (!line || read(fd, buf, 0) < 0)
return (-1);
if (!(*line))
*line = ft_strdup("");
while (1)
{
ret = read(fd, buf, 1);
if (ret > 0 && buf[0] != '\n')
{
buf[ret] = '\0';
temp = ft_strjoin(*line, buf);
free(*line);
*line = temp;
continue ;
}
else
break ;
}
return (ret);
}
int count_lines(char *map_file)
{
char buf[1];
int n_lines;
int fd;
n_lines = 0;
fd = open(map_file, O_RDONLY);
while (read(fd, buf, 1))
{
if (buf[0] == '\n')
n_lines++;
}
close(fd);
return (n_lines);
}
<file_sep>/source_files/read_map.c
#include "../header_files/so_long.h"
static void check_amounts(t_mlx *mlx, int c, int opt)
{
static int exit;
static int collectible;
static int player;
if (opt == 1)
{
if (c == 'E')
exit++;
else if (c == 'C')
{
collectible++;
mlx->game.collectibles++;
}
else if (c == 'P')
player++;
}
if (opt == 2)
if (!exit || !collectible || !player)
error_reading(mlx->map, 3);
}
static void check_components(t_mlx *mlx)
{
t_list *temp;
char *line;
mlx->game.exit = 0;
mlx->game.movements = 0;
mlx->game.collectibles = 0;
temp = *(mlx->map);
while (temp)
{
line = temp->content;
while (*line)
{
if (*line != '0' && *line != '1'
&& *line != 'C' && *line != 'E'
&& *line != 'P')
error_reading(mlx->map, 2);
check_amounts(mlx, *line, 1);
line++;
}
temp = temp->next;
}
check_amounts(mlx, *line, 2);
}
static void check_walls(t_mlx *mlx)
{
t_list *temp;
char *line;
temp = *(mlx->map);
line = temp->content;
while (*line)
if (*line++ != '1')
error_reading(mlx->map, 4);
temp = temp->next;
while (temp->next)
{
line = temp->content;
if (*line++ != '1')
error_reading(mlx->map, 4);
while (*(line + 1))
line++;
if (*line != '1')
error_reading(mlx->map, 4);
temp = temp->next;
}
line = temp->content;
while (*line)
if (*line++ != '1')
error_reading(mlx->map, 4);
}
static void save_map(t_win *win, t_mlx *mlx)
{
size_t length;
t_list *temp;
check_components(mlx);
check_walls(mlx);
temp = *(mlx->map);
length = ft_strlen((*(mlx->map))->content);
temp = temp->next;
while (temp)
{
if (ft_strlen(temp->content) != length)
error_reading(mlx->map, 1);
temp = temp->next;
}
win->width = ft_strlen((*(mlx->map))->content);
win->height = ft_lstsize(*(mlx->map));
if (win->height == win->width)
error_reading(mlx->map, 1);
}
void read_map(t_mlx *mlx, char *map_file)
{
int fd;
int ret;
static char *line = NULL;
mlx->map = malloc(count_lines(map_file) * sizeof(t_list *));
*(mlx->map) = NULL;
fd = open(map_file, O_RDONLY);
while (1)
{
ret = get_next_line(fd, &line);
if (ret > 0)
{
ft_lstadd_back(mlx->map, ft_lstnew(line));
line = NULL;
continue ;
}
else
break ;
}
close(fd);
if (ret == -1)
error_reading(mlx->map, 0);
else if (ret == 0 && line[0] != '\0')
ft_lstadd_back(mlx->map, ft_lstnew(line));
save_map(&(mlx->win), mlx);
}
<file_sep>/source_files/args_check.c
#include "../header_files/so_long.h"
void args_check(int argc, char **argv)
{
int argv_len;
if (argc == 2)
{
argv_len = ft_strlen(argv[1]);
if (ft_strncmp(argv[1] + (argv_len - 4), ".ber", 4) != 0)
error_args(1);
}
else
error_args(0);
}
<file_sep>/source_files/main.c
#include "../header_files/so_long.h"
int close_window(t_mlx *mlx)
{
int i;
i = 0;
while (i < mlx->win.height)
{
free((mlx->map_grid)[i]);
(mlx->map_grid)[i++] = NULL;
}
free (mlx->map_grid);
mlx->map_grid = NULL;
ft_lstclear(mlx->map, free);
exit(0);
}
static int key_pressed(int keycode, t_mlx *mlx)
{
mlx->game.move = 0;
if (keycode == 53)
close_window(mlx);
else if (keycode == 13)
mlx->game.move = 'W';
else if (keycode == 1)
mlx->game.move = 'S';
else if (keycode == 0)
mlx->game.move = 'A';
else if (keycode == 2)
mlx->game.move = 'D';
else
return (0);
update_map(mlx);
if (mlx->game.exit)
close_window(mlx);
return (0);
}
int main(int argc, char **argv)
{
t_mlx mlx;
args_check(argc, argv);
read_map(&mlx, argv[1]);
create_window(&mlx);
draw_map(&mlx);
mlx_hook(mlx.win.win, 2, 1L << 0, key_pressed, &mlx);
mlx_hook(mlx.win.win, 17, 0, close_window, &mlx);
mlx_loop(mlx.mlx);
return (0);
}
<file_sep>/source_files/utils2.c
#include "../header_files/so_long.h"
t_list *ft_lstnew(void *content)
{
t_list *ptr;
ptr = (t_list *)malloc(sizeof(t_list));
if (!ptr)
return (NULL);
ptr->content = content;
ptr->next = NULL;
return (ptr);
}
void ft_lstdelone(t_list *lst, void (*del)(void *))
{
if (lst && del)
{
del(lst->content);
free(lst);
}
}
void ft_lstclear(t_list **lst, void (*del)(void *))
{
t_list *nxt;
if (lst)
{
while (*lst)
{
nxt = (*lst)->next;
ft_lstdelone(*lst, del);
(*lst) = nxt;
}
free(lst);
lst = NULL;
}
}
t_list *ft_lstlast(t_list *lst)
{
if (lst)
{
while (lst->next)
lst = lst->next;
}
return (lst);
}
void ft_lstadd_back(t_list **lst, t_list *new)
{
t_list *ptr;
if (lst)
{
if (*lst)
{
ptr = ft_lstlast(*lst);
ptr->next = new;
}
else
*lst = new;
}
}
<file_sep>/source_files/create_window.c
#include "../header_files/so_long.h"
void create_window(t_mlx *mlx)
{
mlx->mlx = mlx_init();
mlx->win.win = mlx_new_window(mlx->mlx, mlx->win.width * 50,
mlx->win.height * 50, "so_long");
}
<file_sep>/source_files/utils1.c
#include "../header_files/so_long.h"
size_t ft_strlen(const char *s)
{
size_t i;
i = 0;
while (s[i] != '\0')
i++;
return (i);
}
char *ft_strdup(const char *s1)
{
char *ptr;
int i;
ptr = (char *)malloc((sizeof(char) * ft_strlen(s1)) + 1);
if (!ptr)
return (NULL);
else
{
i = 0;
while (*s1)
ptr[i++] = *s1++;
ptr[i] = '\0';
}
return (ptr);
}
char *ft_strjoin(char const *s1, char const *s2)
{
char *ptr;
int len;
int i;
if (!s1 || !s2)
return (NULL);
len = ft_strlen(s1) + ft_strlen(s2);
ptr = (char *)malloc(len + 1);
if (!ptr)
return (NULL);
i = 0;
while (*s1)
ptr[i++] = *s1++;
while (*s2)
ptr[i++] = *s2++;
ptr[i] = '\0';
return (ptr);
}
int ft_strncmp(const char *s1, const char *s2, size_t n)
{
int i;
if (n == 0)
return (0);
i = 0;
while ((s1[i] == s2[i]) && (s1[i] != '\0' && s2[i] != '\0') && (n > 1))
{
i++;
n--;
}
return ((unsigned char)s1[i] - (unsigned char)s2[i]);
}
int ft_lstsize(t_list *lst)
{
size_t i;
t_list *temp;
temp = lst;
i = 0;
while (temp)
{
temp = temp->next;
i++;
}
return (i);
}
<file_sep>/source_files/error.c
#include "../header_files/so_long.h"
#define RED "\033[0;31m"
#define YELLOW "\033[0;33m"
#define NORMAL "\033[0m"
void error_args(int error_nbr)
{
printf("%s[ERROR]%s ", RED, NORMAL);
if (error_nbr == 0)
{
printf("Use the program as follows: ");
printf("%s./so_long <map file>%s\n", YELLOW, NORMAL);
}
if (error_nbr == 1)
printf("Parameter must be a %s.ber%s file\n", YELLOW, NORMAL);
exit (0);
}
void error_reading(t_list **map, int error_nbr)
{
ft_lstclear(map, free);
map = NULL;
printf("%s[ERROR]%s ", RED, NORMAL);
if (error_nbr == 0)
printf("Something went wrong while reading .ber file\n");
else if (error_nbr == 1)
printf("The map must be rectangular\n");
else if (error_nbr == 2)
{
printf("The map must be composed of only 5 possible characters:\n");
printf("0 -> Empty space\n1 -> Wall\nC -> Collectible\n");
printf("E -> Map exit\nP -> Player's starting position\n");
}
else if (error_nbr == 3)
printf("The map must have at least:\n1 Exit\n1 Collectible\n1 Player");
else if (error_nbr == 4)
printf("The map must be surrounded by walls ('1')\n");
exit(0);
}
<file_sep>/Makefile
#VARIABLES:
NAME = so_long
SRCS = source_files/main.c source_files/args_check.c source_files/error.c source_files/read_map.c \
source_files/utils1.c source_files/utils2.c source_files/create_window.c \
source_files/draw_map.c source_files/get_next_line.c source_files/update_map.c
OBJS = $(SRCS:.c=.o)
CC = gcc
CFLAGS = -fsanitize=address -Wall -Werror -Wextra
#RULES:
.SILENT:
all: $(NAME)
%.o: %.c
$(CC) $(CFLAGS) -Imlx -c $< -o $@
$(NAME): $(OBJ)
$(CC) $(SRCS) $(CFLAGS) -Lmlx -lmlx -framework OpenGL -framework AppKit -o $(NAME)
clean:
rm -rf *.o $(SRCS_DIR)/*.o
fclean: clean
rm -rf $(NAME)
re: fclean all
.PHONY: all clean fclean re
<file_sep>/source_files/update_map.c
#include "../header_files/so_long.h"
static void update_game_status(t_mlx *mlx, int x, int y)
{
mlx->game.y += y;
mlx->game.x += x;
mlx->game.movements++;
}
static int save_new_position(t_mlx *mlx, int x, int y)
{
if ((mlx->map_grid)[mlx->game.y + y][mlx->game.x + x] == '0')
{
(mlx->map_grid)[mlx->game.y + y][mlx->game.x + x] = 'P';
(mlx->map_grid)[mlx->game.y][mlx->game.x] = '0';
}
else if ((mlx->map_grid)[mlx->game.y + y][mlx->game.x + x] == 'C')
{
(mlx->map_grid)[mlx->game.y + y][mlx->game.x + x] = 'P';
(mlx->map_grid)[mlx->game.y][mlx->game.x] = '0';
mlx->game.collectibles--;
}
else if ((mlx->map_grid)[mlx->game.y + y][mlx->game.x + x] == 'E'
&& !mlx->game.collectibles)
{
(mlx->map_grid)[mlx->game.y + y][mlx->game.x + x] = 'P';
(mlx->map_grid)[mlx->game.y][mlx->game.x + x] = '0';
mlx->game.exit = 1;
}
else
return (0);
update_game_status(mlx, x, y);
printf("Nº movements = |%d|\n", mlx->game.movements);
return (1);
}
static int update_grid(t_mlx *mlx)
{
int x_move;
int y_move;
x_move = 0;
y_move = 0;
if (mlx->game.move == 'W')
y_move = -1;
else if (mlx->game.move == 'S')
y_move = 1;
else if (mlx->game.move == 'A')
x_move = -1;
else if (mlx->game.move == 'D')
x_move = 1;
return (save_new_position(mlx, x_move, y_move));
}
void update_map(t_mlx *mlx)
{
int i;
int j;
if (!(update_grid(mlx)))
return ;
i = 0;
while (i < mlx->win.height)
{
j = 0;
while (j < mlx->win.width)
{
select_and_draw_img(mlx, i, j);
j++;
}
i++;
}
}
<file_sep>/header_files/so_long.h
#ifndef SO_LONG_H
# define SO_LONG_H
# include "../mlx/mlx.h"
# include <stdio.h>
# include <fcntl.h>
# include <stdlib.h>
# include <unistd.h>
/*LIBFT:*/
typedef struct s_list
{
void *content;
struct s_list *next;
} t_list;
size_t ft_strlen(const char *s);
char *ft_strdup(const char *s1);
char *ft_strjoin(char const *s1, char const *s2);
int ft_strncmp(const char *s1, const char *s2, size_t n);
t_list *ft_lstnew(void *content);
void ft_lstdelone(t_list *lst, void (*del)(void *));
void ft_lstclear(t_list **lst, void (*del)(void *));
t_list *ft_lstlast(t_list *lst);
void ft_lstadd_back(t_list **lst, t_list *new);
int ft_lstsize(t_list *lst);
/*GNL:*/
int get_next_line(int fd, char **line);
/*SO_LONG:*/
typedef struct s_game
{
int x;
int y;
int move;
int movements;
int exit;
int collectibles;
} t_game;
typedef struct s_win
{
void *win;
int height;
int width;
} t_win;
typedef struct s_img
{
void *img;
char *addr;
int bits_per_pixel;
int line_length;
int endian;
} t_img;
typedef struct s_mlx
{
void *mlx;
t_win win;
t_img img;
t_list **map;
char **map_grid;
t_game game;
} t_mlx;
void error_args(int error_nbr);
void error_reading(t_list **map, int error_nbr);
void args_check(int argc, char **argv);
void read_map(t_mlx *mlx, char *map_file);
int count_lines(char *map_file);
void create_window(t_mlx *mlx);
void create_image(t_mlx *mlx);
void draw_map(t_mlx *mlx);
void select_and_draw_img(t_mlx *mlx, int i, int j);
void draw_tile(t_mlx *mlx, char *img, int i, int j);
void register_player_pos(t_mlx *mlx, int x, int y);
void update_map(t_mlx *mlx);
int close_window(t_mlx *mlx);
#endif
<file_sep>/source_files/draw_map.c
#include "../header_files/so_long.h"
void draw_tile(t_mlx *mlx, char *img, int i, int j)
{
int height;
int width;
mlx->img.addr = mlx_get_data_addr(mlx->img.img,
&(mlx->img.bits_per_pixel), &(mlx->img.line_length),
&(mlx->img.endian));
mlx->img.img = mlx_xpm_file_to_image(mlx->mlx, img,
&width, &height);
mlx_put_image_to_window(mlx->mlx, mlx->win.win,
mlx->img.img, j * 50, i * 50);
}
void register_player_pos(t_mlx *mlx, int y, int x)
{
mlx->game.x = x;
mlx->game.y = y;
}
static void build_grid(t_mlx *mlx)
{
int i;
int j;
t_list *temp;
char *str;
mlx->map_grid = malloc(sizeof(char *) * (mlx->win.height));
i = 0;
temp = *(mlx->map);
while (i < mlx->win.height)
{
(mlx->map_grid)[i] = malloc(mlx->win.width);
j = 0;
str = temp->content;
while (*str)
{
if (*str == 'P')
register_player_pos(mlx, i, j);
(mlx->map_grid)[i][j] = *str++;
j++;
}
temp = temp->next;
i++;
}
}
void select_and_draw_img(t_mlx *mlx, int i, int j)
{
if ((mlx->map_grid)[i][j] == '1')
draw_tile(mlx, "./images/Appletree.xpm", i, j);
else if ((mlx->map_grid)[i][j] == 'E')
draw_tile(mlx, "./images/House.xpm", i, j);
else if ((mlx->map_grid)[i][j] == 'C')
draw_tile(mlx, "./images/Apple.xpm", i, j);
else if ((mlx->map_grid)[i][j] == '0')
draw_tile(mlx, "./images/Grass.xpm", i, j);
else if ((mlx->map_grid)[i][j] == 'P')
draw_tile(mlx, "./images/Littleredhood.xpm", i, j);
else
return ;
}
void draw_map(t_mlx *mlx)
{
int i;
int j;
build_grid(mlx);
j = 0;
while (j < mlx->win.height)
{
i = 0;
while (i < mlx->win.width)
{
select_and_draw_img(mlx, j, i);
i++;
}
j++;
}
}
|
4caeea31f99360d806f300cf4a8cf02c923c3158
|
[
"Makefile",
"C"
] | 12 |
Makefile
|
poliveir/so_long
|
34540129e6497e6ca2269ec5d6690960d59bb108
|
04589d58415882a443bcc217aeb692cfa9ad35c9
|
refs/heads/master
|
<file_sep>/** Test file for GitHub Event triggering */
var builder = require('botbuilder');
var restify = require('restify');
|
2c61b5a3be247cb2fe3e3a9383f747702980d211
|
[
"JavaScript"
] | 1 |
JavaScript
|
BotBuilder-Bot/TrackedRepo
|
2017ed06dcdf31edd068203a34c4fa401b3a3949
|
041f02e0e83504728c569d12db1e4cd42af4c8ab
|
refs/heads/master
|
<file_sep>/*
This is empty on purpose! Your code to build the resume will go here.
*/
var bio = {
"name": " <NAME> ",
"role": "Web Developer",
"contacts": {
"mobile": "01234-123456",
"email": "<EMAIL>",
"github": "sfiquet",
"twitter": "example",
"location": "Guildford, UK"
},
"welcomeMessage": "Hi, I'm Sylvie! I'm learning website development. This is my resume.",
"skills": [ "Programming", "Javascript", "Node.js", "Python", "TDD", "Git" ],
"biopic": "images/fry.jpg"
};
bio.display = function() {
var displayContacts = function(elementId, contacts) {
$(elementId).append(HTMLmobile.replace("%data%", contacts.mobile));
$(elementId).append(HTMLemail.replace("%data%", contacts.email));
$(elementId).append(HTMLtwitter.replace("%data%", contacts.twitter));
$(elementId).append(HTMLgithub.replace("%data%", contacts.github));
$(elementId).append(HTMLlocation.replace("%data%", contacts.location));
};
$("#header").prepend(HTMLheaderRole.replace("%data%", this.role));
$("#header").prepend(HTMLheaderName.replace("%data%", this.name));
displayContacts("#topContacts", this.contacts);
displayContacts("#footerContacts", this.contacts);
$("#header").append(HTMLbioPic.replace("%data%", this.biopic));
$("#header").append(HTMLwelcomeMsg.replace("%data%", this.welcomeMessage));
if (this.skills.length) {
$("#header").append(HTMLskillsStart);
this.skills.forEach(function(skill) {
$("#skills").append(HTMLskills.replace("%data%", skill));
});
}
};
var work = {
"jobs": [
{
"employer": "Priory Group",
"title": "Computer Science Teacher",
"location": "Godalming, UK",
"dates": "2012-2013",
"description": "Taught GCSE Computing to a very small class of autistic students with Python as the main programming language"
},
{
"employer": "Software Answers Ltd",
"title": "Software Engineer",
"location": "Farnborough, UK",
"dates": "1994-1999",
"description": "Developed desktop software for Windows in the domains of sales forecasting and analysis and optimisation of orders. Design, coding, testing, maintenance, documentation, communication with QA and trainers"
},
{
"employer": "<NAME>",
"title": "Software Development Contractor",
"location": "Marne-la-Vallée, France",
"dates": "1992-1993",
"description": "Maintain, extend and document expert system written in C, liaise with deployment team and with knowledge engineer. Prototyped migration from DOS to Windows."
},
{
"employer": "<NAME>",
"title": "Software Development Contractor",
"location": "Paris, France",
"dates": "1991-1992",
"description": "Wrote a UI generation tool for options trading applications."
}
]
};
work.display = function() {
var employer, title;
this.jobs.forEach(function(currJob){
$("#workExperience").append(HTMLworkStart);
employer = HTMLworkEmployer.replace("%data%", currJob.employer);
title = HTMLworkTitle.replace("%data%", currJob.title);
$(".work-entry:last").append(employer + title);
$(".work-entry:last").append(HTMLworkLocation.replace("%data%", currJob.location));
$(".work-entry:last").append(HTMLworkDates.replace("%data%", currJob.dates));
$(".work-entry:last").append(HTMLworkDescription.replace("%data%", currJob.description));
});
};
var projects = {
"projects": [
{
"title": "Monster Workshop",
"dates": "2015-ongoing",
"description": "Monster customisation utility for Pathfinder game masters, written with Node.js and Express",
"images": ["http://lorempixel.com/300/170/nature", "http://lorempixel.com/300/170/abstract"]
}
]
};
projects.display = function() {
$("#projects").append(HTMLprojectStart);
this.projects.forEach(function(project) {
$(".project-entry:last").append(HTMLprojectTitle.replace("%data%", project.title));
$(".project-entry:last").append(HTMLprojectDates.replace("%data%", project.dates));
$(".project-entry:last").append(HTMLprojectDescription.replace("%data%", project.description));
project.images.forEach(function(img) {
$(".project-entry:last").append(HTMLprojectImage.replace("%data%", img));
});
});
};
var education = {
"schools": [
{
"name": "University <NAME> Paris V",
"location": "Paris, France",
"degree": "Master (DESS)",
"majors": ["Computer Science"],
"dates": "1990-1991",
"url": "https://www.univ-paris5.fr/eng"
},
{
"name": "University Rennes I, Faculté de Médecine",
"location": "Rennes, France",
"degree": "dropped out",
"majors": ["Medicine"],
"dates": "1985-1990",
"url": "http://www.medecine.univ-rennes1.fr"
}
],
"onlineCourses": [
{
"title": "Intro to Computer Science",
"school": "Udacity",
"dates": 2013,
"url": "https://www.udacity.com/course/intro-to-computer-science--cs101"
},
{
"title": "Algorithms, Part I",
"school": "Coursera",
"dates": 2013,
"url": "https://www.coursera.org/course/algs4partI"
},
{
"title": "Algorithms, Part II",
"school": "Coursera",
"dates": 2013,
"url": "https://www.coursera.org/course/algs4partII"
},
{
"title": "Intro to HTML and CSS",
"school": "Udacity",
"dates": 2015,
"url": "https://www.udacity.com/course/intro-to-html-and-css--ud304"
}
]
};
education.display = function() {
this.schools.forEach(function(school) {
$("#education").append(HTMLschoolStart);
$(".education-entry:last").append(HTMLschoolName.replace("%data%", school.name) + HTMLschoolDegree.replace("%data%", school.degree));
$(".education-entry:last").append(HTMLschoolDates.replace("%data%", school.dates));
$(".education-entry:last").append(HTMLschoolLocation.replace("%data%", school.location));
school.majors.forEach(function(major) {
$(".education-entry:last").append(HTMLschoolMajor.replace("%data%", major));
});
});
if (this.onlineCourses) {
$("#education").append(HTMLonlineClasses);
this.onlineCourses.forEach(function(course) {
$("#education").append(HTMLschoolStart);
$(".education-entry:last").append(HTMLonlineTitle.replace("%data%", course.title) + HTMLonlineSchool.replace("%data%", course.school));
$(".education-entry:last").append(HTMLonlineDates.replace("%data%", course.dates));
$(".education-entry:last").append(HTMLonlineURL.replace("%data%", course.url));
});
}
};
var inName = function() {
var result = "";
var nameArr = [];
nameArr = bio.name.trim().split(" ");
console.log(nameArr);
nameArr[0] = nameArr[0].slice(0, 1).toUpperCase() + nameArr[0].slice(1).toLowerCase();
nameArr[1] = nameArr[1].toUpperCase();
result = nameArr.join(" ");
return result;
};
bio.display();
work.display();
projects.display();
education.display();
$("#mapDiv").append(googleMap);
|
f6a58dbfa1e8f3c8098e5743edc1e10423eaa490
|
[
"JavaScript"
] | 1 |
JavaScript
|
sfiquet/frontend-nanodegree-resume
|
55f656694ec486f409fdcdf6c05204958ee239fe
|
cdf1e4e92e415674e4d8e28792052a577b1e458f
|
refs/heads/main
|
<file_sep>package com.itsj.food.delivery.ui.loginandsignup
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.itsj.food.delivery.R
class LoginAndSignupActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login_and_signup)
}
}<file_sep>package com.itsj.food.delivery.ui.splash
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.itsj.food.delivery.R
class SplashActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
}
}
|
ef0960756cd67ec809f9acf9c888c56c79d3a11e
|
[
"Kotlin"
] | 2 |
Kotlin
|
akashjpro/FoodDelivery
|
8424ba400f1730c483bf4fabf8b79af54fa437c1
|
1c5ea6ec904aab8ae86e5457da9db613528391a8
|
refs/heads/master
|
<file_sep>use std::fs::File;
use std::io::Read;
fn dance(moves : &str, mut programs : String) -> String {
moves.split(",").map(|m| m.trim()).for_each(|m| {
// print!("{} {} => ", programs, m);
match m.as_bytes()[0] {
b's' => {
let value : usize = m[1..].parse().unwrap();
let split : usize = programs.len() - value;
programs = format!("{}{}", &programs[split..], &programs[..split]);
},
b'x' => {
let mut parts = m[1..].split("/");
let pos_a : usize = parts.next().unwrap().parse().unwrap();
let pos_b : usize = parts.next().unwrap().parse().unwrap();
let mut program_bytes = programs.clone().into_bytes();
let tmp = program_bytes[pos_a];
program_bytes[pos_a] = program_bytes[pos_b];
program_bytes[pos_b] = tmp;
programs = String::from_utf8_lossy(&program_bytes).to_string();
},
b'p' => {
let mut parts = m[1..].split("/");
let pos_a : usize = programs.find(parts.next().unwrap()).unwrap();
let pos_b : usize = programs.find(parts.next().unwrap()).unwrap();
let mut program_bytes = programs.clone().into_bytes();
let tmp = program_bytes[pos_a];
program_bytes[pos_a] = program_bytes[pos_b];
program_bytes[pos_b] = tmp;
programs = String::from_utf8_lossy(&program_bytes).to_string();
},
_ => panic!("wtf")
}
// println!("{}", programs);
});
programs.clone()
}
#[test]
fn dance_test() {
let moves = "s1,x3/4,pe/b";
let programs = "abcde";
assert_eq!(dance(&moves, programs.to_string()), "baedc");
}
fn many_dances(moves : &str, programs : String) {
let mut solutions : Vec<String> = Vec::new();
let mut input = programs.clone();
solutions.push(input.clone());
//
// Find the size of the cycle
//
let mut i = 0;
loop {
let solution = dance(&moves, input.clone());
println!("{:04}: {} -> {}", i, input, solution);
match solutions.iter().find(|s| s == &&solution) {
Some(s) => break,
None => ()
}
solutions.push(solution.clone());
input = solution;
i += 1;
}
i += 1;
println!("cycle_size: {}", i);
// Calculate the 1_000_000_000 iteration by using the power of the %
let mut input = programs.clone();
for i in 0..(1_000_000_000 % i) {
input = dance(&moves, input.clone());
}
println!("{}", input);
}
fn main() {
let mut moves = String::new();
let mut file = File::open("input.txt").expect("can't open file");
file.read_to_string(&mut moves);
let mut programs : String = "abcdefghijklmnop".to_string();
println!("{}", programs);
many_dances(&moves, "abcdefghijklmnop".to_string());
}
<file_sep>
fn reallocate(input : &mut Vec<i32>) {
let mut index_for_redistribution = 0;
let mut max_value : i32 = input[0].clone();
for (index, value) in input.iter().enumerate() {
if value > &max_value {
max_value = value.clone();
index_for_redistribution = index;
}
}
input[index_for_redistribution] = 0;
while max_value > 0 {
index_for_redistribution = (index_for_redistribution + 1) % input.len();
input[index_for_redistribution] += 1;
max_value -= 1;
}
}
fn cycle_size(states : &Vec<Vec<i32>>, current_state : &Vec<i32>) -> Option<usize> {
let mut res = states
.iter()
.enumerate()
.filter(|&(index, state)| state == current_state);
match res.nth(0) {
Some((index, _)) => Some(states.len() - index),
None => None
}
}
fn cycle_count(input : &mut Vec<i32>) -> (usize, i32) {
let mut cycles = 0;
let mut seen_states : Vec<Vec<i32>> = vec![];
loop {
seen_states.push(input.clone());
cycles += 1;
reallocate(input);
println!("{:?}", input);
let cycle_size = cycle_size(&seen_states, &input);
match cycle_size {
Some(size) => return (size, cycles),
None => ()
}
}
}
#[test]
fn cycle_count_test() {
let mut input : Vec<i32> = vec![0, 2, 7, 0];
let (size, iterations ) = cycle_count(&mut input);
assert_eq!(iterations, 5);
assert_eq!(size, 4);
}
fn main() {
let mut input : Vec<i32> = vec![14, 0, 15, 12, 11, 11, 3, 5, 1, 6, 8, 4, 9, 1, 8, 4];
let cycles = cycle_count(&mut input);
println!("Cycles {:?}", cycles);
}
<file_sep>use std::iter::*;
use std::fs::File;
use std::io::*;
fn checksum(sheet : String) -> u32 {
let numbers : Vec<Vec<u32>> = sheet.trim().split("\n").map(|row| {
row.split(" ").filter_map(|number| number.parse().ok()).collect()
}).collect();
numbers.iter().fold(0, |result, row| {
let max = row.iter().max().unwrap();
let min = row.iter().min().unwrap();
result + (max - min)
})
}
// returns the division result of the only two integers in the
// array that divide eachother
fn dividers(row : &Vec<u32>) -> Option<u32> {
for i in 0..row.len()-1 {
for j in (i+1)..row.len() {
let a = row[i];
let b = row[j];
if a % b == 0 {
return Some(a/b);
} else if b % a == 0 {
return Some(b/a);
}
}
}
None
}
fn checksum2(sheet : String) -> u32 {
let numbers : Vec<Vec<u32>> = sheet.trim().split("\n").map(|row| {
row.split(" ").filter_map(|number| number.parse().ok()).collect()
}).collect();
numbers.iter().fold(0, |result, row| result + dividers(row).unwrap() )
}
fn main() {
let mut file = File::open("part1_input.txt").expect("Failed to open file");
let mut content = String::new();
file.read_to_string(&mut content).expect("Failed to read file content");
println!("{}", checksum(content));
let mut file = File::open("part2_input.txt").expect("Failed to open file");
let mut content = String::new();
file.read_to_string(&mut content).expect("Failed to read file content");
println!("{}", checksum2(content));
}
#[cfg(test)]
mod test {
use super::checksum;
use super::checksum2;
#[test]
fn part1_example1() {
let sheet = "5 1 9 5
7 5 3
2 4 6 8";
assert_eq!(checksum(sheet.to_string()), 18);
}
#[test]
fn part2_example1() {
let sheet = " 5 9 2 8
9 4 7 3
3 8 6 5";
assert_eq!(checksum2(sheet.to_string()), 9);
}
}
<file_sep>use std::fs::File;
use std::io::Read;
fn dist(a : (i32, i32, i32), b : (i32, i32, i32)) -> i32 {
((a.0 - b.0).abs() + (a.1 - b.1).abs() + (a.2 - b.2).abs()) / 2
}
#[test]
fn dist_test() {
assert_eq!(dist((0,0,0), (3, 0, -3)), 3);
assert_eq!(dist((0,0,0), (0, 0, 0)), 0);
assert_eq!(dist((0,0,0), (2, -2, 0)), 2);
assert_eq!(dist((0,0,0), (-1, -2, 3)), 3);
}
fn traverse(directions : &Vec<&str>) -> (i32, i32, i32) {
let mut max_dist = 0;
let pos = directions.iter().fold((0, 0, 0), |pos, &dir| {
let x = pos.0;
let y = pos.1;
let z = pos.2;
let new_pos = match dir {
"ne" => (x+1, y, z-1),
"n" => (x, y+1, z-1),
"nw" => (x-1, y+1, z),
"sw" => (x-1, y, z+1),
"s" => (x, y-1, z+1),
"se" => (x+1, y-1, z),
_ => panic!("unknown direction")
};
let d = dist((0, 0, 0), new_pos);
if d > max_dist {
max_dist = d;
}
new_pos
});
println!("{}", max_dist);
pos
}
#[test]
fn traverse_test() {
assert_eq!(traverse(&vec!("ne", "ne", "ne")), (3, 0, -3));
assert_eq!(traverse(&vec!("ne", "ne", "sw", "sw")), (0, 0, 0));
assert_eq!(traverse(&vec!("ne", "ne", "s", "s")), (2, -2, 0));
assert_eq!(traverse(&vec!("se", "sw", "se", "sw", "sw")), (-1, -2, 3));
}
fn main() {
let mut content = String::new();
let mut file = File::open("input.txt").expect("file not found");
file.read_to_string(&mut content).expect("can't read file");
let steps = content.trim().split(",").collect();
let d = dist((0, 0, 0), traverse(&steps));
println!("{}", d);
}
<file_sep>fn reverse(array : &mut Vec<i32>, position: i32, size: i32) {
let mut iterations = size / 2;
let mut start = position;
let mut end = (position + size - 1) % (array.len() as i32);
while iterations > 0 {
let tmp = array[start as usize];
array[start as usize] = array[end as usize];
array[end as usize] = tmp;
start = (start + 1 + (array.len() as i32)) % (array.len() as i32);
end = (end - 1 + (array.len() as i32)) % (array.len() as i32);
iterations -= 1;
}
}
#[test]
fn reverse_test() {
let mut a = vec![0, 1, 2, 3, 4];
reverse(&mut a, 0, 3);
assert_eq!(a, vec![2, 1, 0, 3, 4]);
let mut b = vec![0, 1, 2, 3, 4];
reverse(&mut b, 3, 4);
assert_eq!(b, vec![4, 3, 2, 1, 0]);
}
fn dense(array : &Vec<i32>) -> String {
let mut result = "".to_string();
for i in 0..16 {
let mut d = 0;
for j in 0..16 {
d = d ^ array[i*16 + j];
}
if d < 16 {
result = format!("{}0{:x}", result, d);
} else {
result = format!("{}{:x}", result, d);
}
}
result
}
pub fn hash(input: &str) -> String {
let salt = [17, 31, 73, 47, 23];
let mut current_pos = 0;
let mut skip_size = 0;
let mut array : Vec<i32> = Vec::new();
let mut lengths = Vec::new();
for i in 0..256 {
array.push(i);
}
for c in input.bytes() {
lengths.push(c as i32);
}
for s in salt.iter() {
lengths.push(*s);
}
for _ in 0..64 {
for l in &lengths {
// println!("{:?}, {}, {}, {}", array, current_pos, skip_size, l);
reverse(&mut array, current_pos, *l);
current_pos = (current_pos + l + skip_size) % (array.len() as i32);
skip_size += 1;
}
}
dense(&array)
}
<file_sep>[package]
name = "particles"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
[dependencies]
regex = "0.2"
<file_sep>#[derive(Debug)]
pub struct Program {
pub name : String,
pub weight: i32,
pub subprograms: Vec<String>,
}
impl Program {
pub fn parse_all(input : &str) -> Vec<Self> {
input.lines().map(|line| Program::parse(line)).collect()
}
fn parse(line : &str) -> Self {
let parts : Vec<&str> = line.split("->").collect();
let name_and_weight : Vec<&str> = parts[0].split_whitespace().collect();
let name : String = name_and_weight[0].to_string();
let weight : i32 = name_and_weight[1][1..name_and_weight[1].len()-1].parse().unwrap();
if parts.len() == 2 {
Program::new(name.clone(), weight, Program::parse_subprogram_names(parts[1]))
} else {
Program::new(name.clone(), weight, vec![])
}
}
fn parse_subprogram_names(names : &str) -> Vec<String> {
names.split(',').map(|subprogram| subprogram.trim().to_string()).collect()
}
pub fn new(name : String, weight : i32, subprograms : Vec<String>) -> Self {
Program { name, weight, subprograms }
}
}
impl PartialEq for Program {
fn eq(&self, other: &Program) -> bool {
self.name == other.name
}
}
#[test]
fn parse_test() {
let input = "pbga (66)\n fwft (72) -> ktlj, cntj, xhth";
let programs = Program::parse_all(&input);
assert_eq!(programs[0], Program::new("pbga".to_string(), 66, vec![]));
assert_eq!(programs[1], Program::new("fwft".to_string(), 72, vec!["ktlj".to_string(), "cntj".to_string(), "xhth".to_string()]));
}
<file_sep>extern crate regex;
use std::fs::File;
use std::io::Read;
use regex::Regex;
use std::cmp::Ordering;
#[derive(Eq, Debug, Clone)]
struct Particle {
index : usize,
pos: (i64, i64, i64),
vel: (i64, i64, i64),
acc: (i64, i64, i64),
}
impl PartialOrd for Particle {
fn partial_cmp(&self, other: &Particle) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Particle {
fn eq(&self, other: &Particle) -> bool {
self.pos == other.pos && self.vel == other.vel && self.acc == other.acc
}
}
impl Ord for Particle {
fn cmp(&self, other : &Particle) -> Ordering {
let acc_dist_1 = taxi_dist(self.acc);
let acc_dist_2 = taxi_dist(other.acc);
if acc_dist_1 != acc_dist_2 {
return acc_dist_1.cmp(&acc_dist_2);
}
let vel_dist_1 = taxi_dist(self.vel);
let vel_dist_2 = taxi_dist(other.vel);
if vel_dist_1 != vel_dist_2 {
return vel_dist_1.cmp(&vel_dist_2);
}
let dist_1 = taxi_dist(self.pos);
let dist_2 = taxi_dist(other.pos);
dist_1.cmp(&dist_2)
}
}
impl Particle {
fn advance(&mut self) {
self.vel = (self.vel.0 + self.acc.0, self.vel.1 + self.acc.1, self.vel.2 + self.acc.2);
self.pos = (self.pos.0 + self.vel.0, self.pos.1 + self.vel.1, self.pos.2 + self.vel.2);
}
}
fn parse(filename : &str) -> Vec<Particle> {
let mut file = File::open(filename).expect("Can't open file");
let mut content = String::new();
file.read_to_string(&mut content).expect("Can't read from file");
let regex = Regex::new(r"p=<(.*),(.*),(.*)>, v=<(.*),(.*),(.*)>, a=<(.*),(.*),(.*)>").unwrap();
content.lines().enumerate().map(|(index, line)| {
let captures = regex.captures(line).unwrap();
let fetch_num = |index| { captures.get(index).unwrap().as_str().trim().parse().unwrap() };
Particle {
index : index,
pos : (fetch_num(1), fetch_num(2), fetch_num(3)),
vel : (fetch_num(4), fetch_num(5), fetch_num(6)),
acc : (fetch_num(7), fetch_num(8), fetch_num(9)),
}
}).collect()
}
fn taxi_dist(point : (i64, i64, i64)) -> i64 {
point.0.abs() + point.1.abs() + point.2.abs()
}
fn closest(filename : &str) -> usize {
let particles = parse(filename);
particles.iter().min_by(|p1, p2| p1.cmp(&p2)).unwrap().index
}
fn simulate(filename : &str) -> usize {
let mut particles = parse(filename);
let mut count = 0;
let mut non_changed_count = 0;
loop {
println!("{}, {}", count, non_changed_count);
for p in particles.iter_mut() {
p.advance();
}
let mut new_particles = Vec::new();
for p in particles.iter() {
let collided = particles.iter().filter(|other| p.index != other.index).any(|other| { other.pos == p.pos });
if !collided {
new_particles.push(p.clone());
}
}
particles = new_particles;
if count == particles.len() {
non_changed_count += 1;
if non_changed_count > 500 {
break;
}
} else {
non_changed_count = 0;
count = particles.len();
}
}
count
}
fn main() {
println!("{:?}", simulate("input.txt"));
}
#[test]
fn parse_test() {
assert_eq!(closest("test_input.txt"), 0);
}
<file_sep>// use std::fs::File;
// use std::io::Read;
// use std::collections::HashMap;
// type Commands = Vec<Command>;
// enum Command {
// Set(String, String),
// Sub(String, String),
// Mul(String, String),
// Jnz(String, String)
// }
// fn parse(filename : &str) -> Commands {
// let mut file = File::open(filename).expect("can't open file");
// let mut content = String::new();
// file.read_to_string(&mut content).expect("can't read from file");
// content.lines().map(|line| {
// let mut parts = line.split_whitespace();
// let cmd = parts.next().unwrap();
// let a = parts.next().unwrap();
// let b = parts.next().unwrap();
// match cmd {
// "set" => Command::Set(a.to_string(), b.to_string()),
// "mul" => Command::Mul(a.to_string(), b.to_string()),
// "sub" => Command::Sub(a.to_string(), b.to_string()),
// "jnz" => Command::Jnz(a.to_string(), b.to_string()),
// _ => panic!("unrecognized patter")
// }
// }).collect()
// }
// fn execute(filename : &str) -> i64 {
// let commands = parse(filename);
// let mut current : i64 = 0;
// let mut registers : HashMap<String, i64> = HashMap::new();
// registers.insert("a".to_string(), 1);
// loop {
// for (a, b) in registers.iter() {
// print!("{}: {}, ", a, b);
// }
// println!("");
// match commands.get(current as usize).unwrap() {
// &Command::Set(ref a, ref b) => {
// println!("set {} {}", a, b);
// let val_b = match b.parse() {
// Ok(number) => {
// number
// },
// Err(_) => {
// match registers.get(b) {
// Some(v) => *v,
// None => 0
// }
// }
// };
// registers.insert(a.clone(), val_b);
// current += 1;
// },
// &Command::Mul(ref a, ref b) => {
// println!("mul {} {}", a, b);
// let val_a = match a.parse() {
// Ok(number) => {
// number
// },
// Err(_) => {
// match registers.get(a) {
// Some(v) => *v,
// None => 0
// }
// }
// };
// let val_b = match b.parse() {
// Ok(number) => {
// number
// },
// Err(_) => {
// match registers.get(b) {
// Some(v) => *v,
// None => 0
// }
// }
// };
// registers.insert(a.clone(), val_a * val_b);
// current += 1;
// },
// &Command::Sub(ref a, ref b) => {
// println!("sub {} {}", a, b);
// let val_a = match a.parse() {
// Ok(number) => {
// number
// },
// Err(_) => {
// match registers.get(a) {
// Some(v) => *v,
// None => 0
// }
// }
// };
// let val_b = match b.parse() {
// Ok(number) => {
// number
// },
// Err(_) => {
// match registers.get(b) {
// Some(v) => *v,
// None => 0
// }
// }
// };
// registers.insert(a.clone(), val_a - val_b);
// current += 1;
// },
// &Command::Jnz(ref a, ref b) => {
// println!("jnz {} {}", a, b);
// let val_a = match a.parse() {
// Ok(number) => {
// number
// },
// Err(_) => {
// match registers.get(a) {
// Some(v) => *v,
// None => 0
// }
// }
// };
// let val_b = match b.parse() {
// Ok(number) => {
// number
// },
// Err(_) => {
// match registers.get(b) {
// Some(v) => *v,
// None => 0
// }
// }
// };
// if val_a != 0 {
// current += val_b;
// } else {
// current += 1;
// }
// }
// }
// if current < 0 || current >= (commands.len() as i64) {
// break;
// }
// }
// match registers.get("h") {
// Some(v) => *v,
// None => 0
// }
// }
fn calculate() -> i64 {
let mut h = 0;
let mut b = 79 * 100 + 100_000;
let limit = b + 17_000;
loop {
for d in 2..b {
if b % d == 0 {
h += 1;
break;
}
}
b += 17;
if b > limit { break; }
}
h
}
fn main() {
// println!("{}", execute("input.txt"));
println!("{}", calculate());
}
<file_sep>use std::fs::File;
use std::io::Read;
use std::fmt;
type Image = Vec<Vec<char>>;
struct Rule {
input: Image,
output: Image,
}
fn rotate_image(image: &Image) -> Image {
let mut result = image.clone();
for i in 0..image.len() {
for j in 0..image.len() {
result[i][j] = image[image.len() - j - 1][i];
}
}
result
}
fn flip_x_image(image: &Image) -> Image {
let mut result = image.clone();
for i in 0..image.len() {
for j in 0..image.len() {
result[i][j] = image[i][image.len() - j - 1];
}
}
result
}
fn flip_y_image(image: &Image) -> Image {
let mut result = image.clone();
for i in 0..image.len() {
for j in 0..image.len() {
result[i][j] = image[image.len() - i - 1][j];
}
}
result
}
impl Rule {
fn matches(&self, image: &Image) -> bool {
if image.len() != self.input.len() {
return false;
}
if image.len() != self.input[0].len() {
return false;
}
for i in 0..self.input.len() {
for j in 0..self.input.len() {
if image[i][j] != self.input[i][j] {
return false;
}
}
}
true
}
fn rotate(&self) -> Rule {
Rule {
input: rotate_image(&self.input),
output: self.output.clone()
}
}
fn flip_x(&self) -> Rule {
Rule {
input: flip_x_image(&self.input),
output: self.output.clone()
}
}
fn flip_y(&self) -> Rule {
Rule {
input: flip_y_image(&self.input),
output: self.output.clone()
}
}
}
#[test]
fn matches_test() {
let image = vec![
vec!['#', '#'],
vec!['.', '#'],
];
let rule = Rule {
input: vec![
vec!['#', '#'],
vec!['.', '#'],
],
output: vec![
vec!['.', '.'],
vec!['#', '#'],
]
};
assert!(rule.matches(&image));
let image = vec![
vec!['#', '#', '#'],
vec!['#', '#', '#'],
vec!['#', '#', '#'],
];
let rule = Rule {
input: vec![
vec!['#', '#'],
vec!['.', '#'],
],
output: vec![
vec!['.', '.'],
vec!['#', '#'],
]
};
assert!(!rule.matches(&image));
}
#[test]
fn rotate_test() {
let rule = Rule {
input: vec![
vec!['#', '#'],
vec!['.', '#'],
],
output: vec![
vec!['.', '.', '#'],
vec!['#', '#', '.'],
vec!['.', '#', '.'],
]
};
let rotated = rule.rotate();
assert_eq!(rotated.input, vec![
vec!['.', '#'],
vec!['#', '#'],
]);
}
impl fmt::Display for Rule {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?} => {:?}", self.input, self.output)
}
}
fn parse(filename : &str) -> Vec<Rule> {
let mut file = File::open(filename).expect("can't open file");
let mut content = String::new();
file.read_to_string(&mut content).expect("can't read from file");
content.lines().map(|line| {
let mut parts = line.split("=>");
let input = parts.next().unwrap().trim().split("/").map(|p| p.chars().collect()).collect();
let output = parts.next().unwrap().trim().split("/").map(|p| p.chars().collect()).collect();
Rule { input, output }
}).collect()
}
fn display(image : &Image) {
for row in image {
println!("{:?}", row);
}
}
fn count_pixels(image : &Image) -> i64 {
let mut sum = 0;
for row in image {
for pixel in row {
if pixel == &'#' {
sum += 1;
}
}
}
sum
}
#[test]
fn count_pixels_test() {
let image = vec![
vec!['.', '#', '.'],
vec!['.', '.', '#'],
vec!['#', '#', '#'],
];
assert_eq!(count_pixels(&image), 5);
}
fn extract_segment(image: &Image, x: usize, y: usize, w: usize, h: usize) -> Image {
let mut result = vec![];
for i in y..(y+h) {
let mut row = vec![];
for j in x..(x+w) {
row.push(image[i][j]);
}
result.push(row);
}
result
}
#[test]
fn extract_segment_test() {
let image = vec![
vec!['.', '#', '.'],
vec!['.', '.', '#'],
vec!['#', '#', '#'],
];
assert_eq!(extract_segment(&image, 1, 1, 2, 2), vec![
vec!['.', '#'],
vec!['#', '#'],
]);
}
fn split_into_segments(image: &Image) -> Vec<Vec<Image>> {
let mut segments = vec![];
let segment_size = if image.len() % 2 == 0 { 2 } else { 3 };
let segment_count = image.len() / segment_size;
for i in 0..segment_count {
let mut row = vec![];
for j in 0..segment_count {
let image = extract_segment(&image, j * segment_size, i * segment_size, segment_size, segment_size);
row.push(image);
}
segments.push(row);
}
segments
}
#[test]
fn split_into_segments_test() {
let image = vec![
vec!['.', '#', '.', '#'],
vec!['.', '.', '#', '.'],
vec!['#', '#', '#', '#'],
vec!['#', '.', '.', '#'],
];
assert_eq!(split_into_segments(&image), vec![
vec![
vec![
vec!['.', '#'],
vec!['.', '.'],
],
vec![
vec!['.', '#'],
vec!['#', '.'],
],
],
vec![
vec![
vec!['#', '#'],
vec!['#', '.'],
],
vec![
vec!['#', '#'],
vec!['.', '#'],
],
],
]);
let image = vec![
vec!['.', '#', '.'],
vec!['.', '.', '#'],
vec!['#', '#', '#'],
];
assert_eq!(split_into_segments(&image), vec![
vec![
vec![
vec!['.', '#', '.'],
vec!['.', '.', '#'],
vec!['#', '#', '#'],
],
],
]);
}
fn join_segments(segments : &Vec<Vec<Image>>) -> Image {
let mut image = vec![];
let segment_size = segments[0][0].len();
let image_width = segment_size * segments.len();
let image_height = image_width;
for i in 0..image_width {
let mut row = vec![];
for j in 0..image_height {
let seg_x = j / segment_size;
let seg_y = i / segment_size;
let x = j % segment_size;
let y = i % segment_size;
row.push(segments[seg_y][seg_x][y][x]);
}
image.push(row);
}
image
}
#[test]
fn join_segments_test() {
let segments = vec![
vec![
vec![
vec!['.', '#'],
vec!['.', '.'],
],
vec![
vec!['.', '#'],
vec!['#', '.'],
],
],
vec![
vec![
vec!['#', '#'],
vec!['#', '.'],
],
vec![
vec!['#', '#'],
vec!['.', '#'],
],
],
];
assert_eq!(join_segments(&segments), vec![
vec!['.', '#', '.', '#'],
vec!['.', '.', '#', '.'],
vec!['#', '#', '#', '#'],
vec!['#', '.', '.', '#'],
]);
}
fn process_segment(segment : &Image, rules : &Vec<Rule>) -> Image {
for rule in rules.iter() {
if rule.matches(segment) {
return rule.output.clone();
}
}
panic!("No pattern found");
}
#[test]
fn process_segment_test() {
let image = vec![
vec!['#', '#'],
vec!['.', '#'],
];
let rules = vec![
Rule {
input: vec![
vec!['#', '#'],
vec!['.', '#'],
],
output: vec![
vec!['.', '.', '#'],
vec!['#', '#', '.'],
vec!['#', '#', '.'],
]
}
];
assert_eq!(process_segment(&image, &rules), vec![
vec!['.', '.', '#'],
vec!['#', '#', '.'],
vec!['#', '#', '.'],
]);
}
fn process(image : &Image, rules: &Vec<Rule>) -> Image {
let segments : Vec<Vec<Image>> = split_into_segments(image).iter().map(|row : &Vec<Image>| {
row.iter().map(|segment : &Image| process_segment(segment, &rules)).collect()
}).collect();
join_segments(&segments)
}
#[test]
fn process_test() {
let rules = parse("test_input.txt");
let mut image = vec![
vec!['.', '#', '.'],
vec!['.', '.', '#'],
vec!['#', '#', '#'],
];
for _ in 0..2 {
image = process(&image, &rules);
println!("-------------------------------------");
display(&image);
}
assert_eq!(count_pixels(&image), 12);
}
fn generate_all_rule_variations(rules : &Vec<Rule>) -> Vec<Rule> {
let mut result : Vec<Rule> = vec![];
for rule in rules.iter() {
let mut flips : Vec<Rule> = vec![];
flips.push(rule.flip_x().flip_x());
flips.push(rule.flip_x());
flips.push(rule.flip_y());
flips.push(rule.flip_x().flip_y());
flips.push(rule.flip_y().flip_x());
for flip in flips.iter() {
let mut rotations : Vec<Rule> = vec![];
rotations.push(flip.rotate());
rotations.push(flip.rotate().rotate());
rotations.push(flip.rotate().rotate().rotate());
rotations.push(flip.rotate().rotate().rotate().rotate());
for rotation in rotations.iter() {
result.push(rotation.flip_x().flip_x());
}
}
}
result
}
fn main() {
let rules = parse("input.txt");
let all_rules = generate_all_rule_variations(&rules);
let mut image = vec![
vec!['.', '#', '.'],
vec!['.', '.', '#'],
vec!['#', '#', '#'],
];
// for r in rules.iter() {
// println!("{}", r);
// }
println!("=====================================");
display(&image);
for i in 0..18 {
println!("{}", i);
image = process(&image, &all_rules);
println!("-------------------------------------");
display(&image);
}
println!("{}", count_pixels(&image));
}
<file_sep>use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
struct Registers {
values: HashMap<String, i32>,
max_value: i32
}
impl Registers {
fn new() -> Self {
Registers { values: HashMap::new(), max_value: 0 }
}
fn get(&self, name : &str) -> i32 {
match self.values.get(name) {
Some(v) => *v,
None => 0
}
}
fn inc(&mut self, name: &str, value: i32) {
let new_value = self.get(&name) + value;
if new_value > self.max_value {
self.max_value = new_value;
}
self.values.insert(name.to_string(), new_value);
}
fn dec(&mut self, name: &str, value: i32) {
let new_value = self.get(&name) - value;
if new_value > self.max_value {
self.max_value = new_value;
}
self.values.insert(name.to_string(), new_value);
}
}
fn execute(registers : &mut Registers, command : &str) {
let mut parts = command.split_whitespace();
let reg_name : &str = parts.next().unwrap();
let cmd : &str = parts.next().unwrap();
let value : i32 = parts.next().unwrap().parse().unwrap();
parts.next(); // ignore 'if'
let test_reg_name : &str = parts.next().unwrap();
let test_operator : &str = parts.next().unwrap();
let test_value : i32 = parts.next().unwrap().parse().unwrap();
println!("{}, {}, {} - {}, {}, {}", reg_name, cmd, value, test_reg_name, test_operator, test_value);
let test_result = match test_operator {
">" => registers.get(test_reg_name) > test_value,
"<" => registers.get(test_reg_name) < test_value,
">=" => registers.get(test_reg_name) >= test_value,
"<=" => registers.get(test_reg_name) <= test_value,
"!=" => registers.get(test_reg_name) != test_value,
"==" => registers.get(test_reg_name) == test_value,
_ => panic!("Unknown operator")
};
if test_result {
match cmd {
"inc" => registers.inc(reg_name, value),
"dec" => registers.dec(reg_name, value),
_ => panic!("Unknown command")
};
}
}
#[test]
fn execute_test() {
let mut registers = Registers::new();
execute(&mut registers, "b inc 5 if a > 1");
execute(&mut registers, "a inc 1 if b < 5");
execute(&mut registers, "c dec -10 if a >= 1");
execute(&mut registers, "b inc -20 if c == 10");
assert_eq!(registers.get("a"), 1);
assert_eq!(registers.get("b"), -20);
assert_eq!(registers.get("c"), 10);
}
fn main() {
let mut content = String::new();
let mut file = File::open("prog.txt").expect("No such file");
file.read_to_string(&mut content);
let mut registers = Registers::new();
content.lines().for_each(|l| execute(&mut registers, l));
println!("max values during the operation: {:?}", registers.max_value);
println!("current max value: {:?}", registers.values.values().max().unwrap());
}
<file_sep>use std::fs::File;
use std::io::Read;
struct Magnet {
index: usize,
a: i64,
b: i64
}
impl Magnet {
fn value(&self) -> i64 {
self.a + self.b
}
}
fn parse(filename : &str) -> Vec<Magnet> {
let mut file = File::open(filename).expect("Can't open file");
let mut content = String::new();
file.read_to_string(&mut content).expect("can't read from file");
content.lines().enumerate().map(|(index, line)| {
let mut parts = line.split("/");
let a = parts.next().unwrap().parse().unwrap();
let b = parts.next().unwrap().parse().unwrap();
Magnet { index: index, a: a, b: b }
}).collect()
}
fn dfs(start : i64, magnets: Vec<&Magnet>) -> (i64, i64) {
let mut connectable = vec![];
for m in magnets.iter() {
if m.a == start || m.b == start {
connectable.push(m.clone());
}
}
let size = connectable.len();
if size == 0 {
return (0, 0);
} else {
connectable.iter().map(|m| {
let mut others = vec![];
for m2 in magnets.iter() {
if m.index != m2.index {
others.push(m2.clone());
}
}
if m.a == start {
// print!("--{}/{}", m.a, m.b);
let (len, strength) = dfs(m.b, others);
(len+1, strength + m.value())
} else {
// print!("--{}/{}", m.a, m.b);
let (len, strength) = dfs(m.a, others);
(len+1, strength + m.value())
}
}).max_by(|a, b| {
if a.0 == b.0 {
a.1.cmp(&b.1)
} else {
a.0.cmp(&b.0)
}
}).unwrap()
}
}
fn calculate(filename : &str) -> i64 {
let magnets = parse(filename);
for m in magnets.iter() {
println!("{}/{}", m.a, m.b);
}
let (_, strength) = dfs(0, magnets.iter().collect());
strength
}
#[test]
fn calculate_test() {
assert_eq!(calculate("test_input.txt"), 19);
}
fn main() {
println!("{}", calculate("input.txt"));
}
<file_sep>fn jugde(input_a : i64, input_b : i64) -> i32 {
let mut result = 0;
let mut a = input_a;
let mut b = input_b;
for i in 0..40_000_000 {
a = (a * 16807) % 2147483647;
b = (b * 48271) % 2147483647;
// println!("{} : {:0b}", a, (a & 65535));
// println!("{} : {:0b}", b, (b & 65535));
// println!("-------------------");
if (a & 65535) == (b & 65535) {
result += 1;
}
}
result
}
fn jugde2(input_a : i64, input_b : i64) -> i32 {
let mut result = 0;
let mut a = input_a;
let mut b = input_b;
let i = 0;
for _ in 0..5_000_000 {
loop {
a = (a * 16807) % 2147483647;
if a % 4 == 0 { break; }
}
loop {
b = (b * 48271) % 2147483647;
if b % 8 == 0 { break; }
}
if (a & 65535) == (b & 65535) {
result += 1;
}
}
result
}
#[test]
fn judge_test() {
assert_eq!(jugde(65, 8921), 588);
assert_eq!(jugde2(65, 8921), 309);
}
fn main() {
println!("{}", jugde(618, 814));
println!("{}", jugde2(618, 814));
}
<file_sep>// You're standing in a room with "digitization quarantine"
// written in LEDs along one wall. The only door is locked, but
// it includes a small interface. "Restricted Area - Strictly
// No Digitized Users Allowed."
//
// It goes on to explain that you may only leave by solving a
// captcha to prove you're not a human. Apparently, you only
// get one millisecond to solve the captcha: too fast for a
// normal human, but it feels like hours to you.
//
// The captcha requires you to review a sequence of digits
// (your puzzle input) and find the sum of all digits that
// match the next digit in the list. The list is circular, so
// the digit after the last digit is the first digit in the
// list.
//
// For example:
//
// 1122 produces a sum of 3 (1 + 2) because the first digit
// (1) matches the second digit and the third digit (2) matches
// the fourth digit.
//
// 1111 produces 4 because each digit (all 1) matches the next.
//
// 1234 produces 0 because no digit matches the next.
//
// 91212129 produces 9 because the only digit that matches
// the next one is the last digit, 9.
//
// What is the solution to your captcha?
//
// Input file: part1-input.txt
//
// --- Part Two ---
//
// You notice a progress bar that jumps to 50% completion. Apparently, the door
// isn't yet satisfied, but it did emit a star as encouragement. The instructions
// change:
//
// Now, instead of considering the next digit, it wants you to consider the digit
// halfway around the circular list. That is, if your list contains 10 items, only
// include a digit in your sum if the digit 10/2 = 5 steps forward matches it.
// Fortunately, your list has an even number of elements.
//
// For example:
//
// 1212 produces 6: the list contains 4 items, and all four digits match the
// digit 2 items ahead. 1221 produces 0, because every comparison is between a 1
// and a 2. 123425 produces 4, because both 2s match each other, but no other
// digit has a match. 123123 produces 12. 12131415 produces 4.
//
// What is the solution to your new captcha?
//
// Input file: part2-input.txt
//
use std::fs::File;
use std::io::prelude::*;
use std::iter::*;
// converts characters into vector of numbers
fn to_digits(captcha : String) -> Vec<u32> {
captcha.chars().filter_map(|s| s.to_digit(10)).collect()
}
// takes [1, 2, 3, 4],
// returns [(1, 2), (2, 3), (3, 4), (4, 1)] if step is 1
// returns [(1, 3), (2, 4), (3, 2), (4, 1)] if step is 2
fn each_pair_circular(digits : Vec<u32>, step : usize) -> Vec<(u32, u32)> {
(0..digits.len())
.map(|index| (index, (index+step) % digits.len()))
.map(|(index, next_index)| (digits[index], digits[next_index]))
.collect()
}
fn calculate(captcha : String) -> u32 {
let digits = to_digits(captcha);
let pairs = each_pair_circular(digits, 1);
pairs.iter()
.filter(|&&(a, b)| a == b) // return pairs that have the same element
.map(|&(a, _)| a) // take the first element from array
.sum()
}
fn calculate2(captcha : String) -> u32 {
let digits = to_digits(captcha);
let step = digits.len() / 2;
let pairs = each_pair_circular(digits, step);
pairs.iter()
.filter(|&&(a, b)| a == b) // return pairs that have the same element
.map(|&(a, _)| a) // take the first element from array
.sum()
}
fn main() {
let mut part1_file = File::open("part1_input.txt").expect("File not found");
let mut part1_input = String::new();
part1_file.read_to_string(&mut part1_input).expect("Failed to read input file");
println!("Part 1 Solution: {}", calculate(part1_input));
let mut part2_file = File::open("part2_input.txt").expect("File not found");
let mut part2_input = String::new();
part2_file.read_to_string(&mut part2_input).expect("Failed to read input file");
println!("Part 2 Solution: {}", calculate2(part2_input));
}
#[cfg(test)]
mod test {
use super::calculate;
use super::calculate2;
#[test]
fn part1_first_sample_input() {
assert_eq!(calculate("1122".to_string()), 3);
}
#[test]
fn part1_second_sample_input() {
assert_eq!(calculate("1111".to_string()), 4);
}
#[test]
fn part1_third_sample_input() {
assert_eq!(calculate("1234".to_string()), 0);
}
#[test]
fn part1_fourth_sample_input() {
assert_eq!(calculate("91212129".to_string()), 9);
}
#[test]
fn part1_fifth_sample_input() {
assert_eq!(calculate("11223311".to_string()), 8);
}
#[test]
fn part2_first_sample() {
assert_eq!(calculate2("1212".to_string()), 6);
}
#[test]
fn part2_second_sample() {
assert_eq!(calculate2("1221".to_string()), 0);
}
#[test]
fn part2_third_sample() {
assert_eq!(calculate2("123425".to_string()), 4);
}
#[test]
fn part2_fourth_sample() {
assert_eq!(calculate2("123123".to_string()), 12);
}
#[test]
fn part2_fifth_sample() {
assert_eq!(calculate2("12131415".to_string()), 4);
}
}
<file_sep>fn spin(steps : usize) -> i64 {
let mut current_pos : usize = 0;
let mut res : i64 = 0;
for i in 1..50_000_000 {
if i % 100_000 == 0 {
println!("{}", i);
}
current_pos = (current_pos + steps) % i;
if current_pos == 0 {
res = i as i64;
}
current_pos += 1;
}
res
}
#[test]
fn spin_test() {
assert_eq!(spin(3), 638);
}
fn main() {
println!("{}", spin(303));
}
<file_sep>use std::fs::File;
use std::io::Read;
const STATE_START : i32 = 1;
const STATE_GROUP_START : i32 = 2;
const STATE_GROUP_OVER : i32 = 3;
const STATE_GARBAGE_START : i32 = 4;
const STATE_GARBAGE_OVER : i32 = 5;
const STATE_GARBAGE_IGNORE_NEXT : i32 = 6;
const STATE_COMMA : i32 = 7;
fn debug(state: i32, c : char) {
let name = match state {
STATE_START => "START",
STATE_GROUP_START => "GROUP_START",
STATE_GROUP_OVER => "GROUP_OVER",
STATE_GARBAGE_START => "GARBAGE_START",
STATE_GARBAGE_OVER => "GARBAGE_OVER",
STATE_GARBAGE_IGNORE_NEXT => "GARBGE_IGNORE_NEXT",
STATE_COMMA => "COMMA",
_ => "INVALID"
};
println!("char: {}, state: {}", c, name);
}
fn parser(content : &str) -> (i32, i32) {
let mut state = STATE_START;
let mut depth = 0;
let mut sum = 0;
let mut garbage = 0;
for c in content.chars() {
debug(state, c);
match state {
STATE_START => match c {
'{' => {
state = STATE_GROUP_START;
depth += 1;
},
_ => panic!("Invalid character")
},
STATE_GROUP_START => match c {
'{' => {
state = STATE_GROUP_START;
depth += 1;
},
'}' => {
state = STATE_GROUP_OVER;
sum += depth;
depth -= 1;
},
'<' => {
state = STATE_GARBAGE_START;
},
_ => panic!("Invalid character")
},
STATE_GARBAGE_START => match c {
'>' => {
state = STATE_GARBAGE_OVER;
},
'!' => {
state = STATE_GARBAGE_IGNORE_NEXT;
},
_ => {
state = STATE_GARBAGE_START;
garbage += 1;
}
},
STATE_GARBAGE_IGNORE_NEXT => match c {
_ => {
state = STATE_GARBAGE_START;
}
},
STATE_GARBAGE_OVER | STATE_GROUP_OVER => match c {
',' => {
state = STATE_COMMA;
},
'}' => {
state = STATE_GROUP_OVER;
sum += depth;
depth -= 1;
},
_ => panic!("Invalid character")
},
STATE_COMMA => match c {
'{' => {
state = STATE_GROUP_START;
depth += 1;
},
'<' => {
state = STATE_GARBAGE_START;
},
_ => panic!("Invalid character")
},
_ => panic!("Invalid state")
}
}
(sum, garbage)
}
#[test]
fn parser_test() {
assert_eq!(parser("{}"), (1, 0));
assert_eq!(parser("{{{}}}"), (6, 0));
assert_eq!(parser("{{},{}}"), (5, 0));
assert_eq!(parser("{{{},{},{{}}}}"), (16, 0));
assert_eq!(parser("{<a>,<a>,<a>,<a>}"), (1, 4));
assert_eq!(parser("{{<ab>},{<ab>},{<ab>},{<ab>}}"), (9, 8));
assert_eq!(parser("{{<!!>},{<!!>},{<!!>},{<!!>}}"), (9, 0));
assert_eq!(parser("{{<a!>},{<a!>},{<a!>},{<ab>}}"), (3, 16));
}
fn main() {
let mut content = String::new();
let mut file = File::open("input.txt").expect("no file");
file.read_to_string(&mut content).expect("can't read from file");
println!("sum: {:?}", parser(content.trim()));
}
<file_sep># Advent Of Code 2017
This time in Rust.
https://adventofcode.com

<file_sep>use std::fs::File;
use std::io::Read;
#[derive(Debug)]
struct Header {
start: String,
steps: i64
}
#[derive(Debug, PartialEq, Eq)]
enum Direction {
Left,
Right
}
struct Action {
write: i64,
movement: Direction,
continue_with: String
}
struct State {
name: String,
action_on_zero: Action,
action_on_one: Action
}
struct Program {
header: Header,
states: Vec<State>
}
fn parse_header(header: &str) -> Header {
let mut lines = header.lines();
let first_line = lines.next().unwrap().to_string();
let second_line = lines.next().unwrap().to_string();
let numbers_in_second_line : String = second_line.chars().filter(|c| c.is_numeric()).collect();
Header {
start: first_line.chars().skip(first_line.len() - 2).take(1).collect(),
steps: numbers_in_second_line.parse().unwrap()
}
}
#[test]
fn parse_header_test() {
let header = "Begin in state A.
Perform a diagnostic checksum after 12794428 steps.";
assert_eq!(parse_header(header).start, "A");
assert_eq!(parse_header(header).steps, 12794428);
}
fn parse_action(lines: &mut std::str::Lines) -> Action {
lines.next(); // skip first line
let first_line = lines.next().unwrap();
let write : String = first_line.chars().skip(first_line.len()-2).take(1).collect();
let last_word_on_second_line = lines.next().unwrap().split_whitespace().rev().next().unwrap();
let movement = if last_word_on_second_line == "left." {
Direction::Left
} else {
Direction::Right
};
let last_line = lines.next().unwrap();
let continue_with = last_line.chars().skip(last_line.len()-2).take(1).collect();
Action {
write: write.parse().unwrap(),
movement: movement,
continue_with: continue_with
}
}
fn parse_state(state: &str) -> State {
let mut lines = state.lines();
let first_line = lines.next().unwrap();
let name = first_line.chars().skip(first_line.len()-2).take(1).collect();
let action0 = parse_action(&mut lines);
let action1 = parse_action(&mut lines);
State {
name: name,
action_on_zero: action0,
action_on_one: action1
}
}
#[test]
fn parse_state_test() {
let state = "In state A:
If the current value is 0:
- Write the value 1.
- Move one slot to the right.
- Continue with state B.
If the current value is 1:
- Write the value 0.
- Move one slot to the left.
- Continue with state F.";
assert_eq!(parse_state(state).name, "A");
assert_eq!(parse_state(state).action_on_zero.write, 1);
assert_eq!(parse_state(state).action_on_zero.movement, Direction::Right);
assert_eq!(parse_state(state).action_on_zero.continue_with, "B");
assert_eq!(parse_state(state).action_on_one.write, 0);
assert_eq!(parse_state(state).action_on_one.movement, Direction::Left);
assert_eq!(parse_state(state).action_on_one.continue_with, "F");
}
fn parse(filename : &str) -> Program {
let mut file = File::open(filename).expect("Can't open file");
let mut content = String::new();
file.read_to_string(&mut content).expect("Can't read file");
let mut paragraphs = content.split("\n\n");
let header = parse_header(paragraphs.next().unwrap());
let mut states = vec![];
for state in paragraphs {
states.push(parse_state(state));
}
Program {
header: header,
states: states
}
}
fn turing(filename : &str) -> i64 {
let program = parse(filename);
let mut tape = vec![];
let tape_len : usize = (program.header.steps as usize) * 2;
tape.resize(tape_len, 0);
let mut current = tape_len / 2;
let mut state_name = program.header.start;
for _ in 0..program.header.steps {
let value = tape[current];
let state = program.states.iter().find(|s| s.name == state_name).unwrap();
// println!("{}, {}", value, state.name);
let action = if value == 0 {
&state.action_on_zero
} else {
&state.action_on_one
};
tape[current] = action.write;
if action.movement == Direction::Left {
current += 1;
} else {
current -= 1;
}
state_name = action.continue_with.clone();
}
tape.iter().sum()
}
fn main() {
println!("{}", turing("input.txt"));
}
<file_sep>use std::fs::File;
use std::io::prelude::*;
fn count_jumps(array : &mut Vec<i32>) -> i32 {
let mut jumps : i32 = 0;
let mut current_position : usize = 0;
let len = array.len();
loop {
jumps += 1;
let instruction = array[current_position];
let next_position : i32 = (current_position as i32) + instruction;
if next_position >= (len as i32) || next_position < 0 {
break;
} else {
array[current_position] += 1;
}
current_position = next_position as usize;
}
jumps
}
#[test]
fn count_jumps_test() {
assert_eq!(count_jumps(&mut vec![0, 3, 0, 1, -3]), 5);
}
fn count_jumps_2(array : &mut Vec<i32>) -> i32 {
let mut jumps : i32 = 0;
let mut current_position : usize = 0;
let len = array.len();
loop {
jumps += 1;
let instruction = array[current_position];
let next_position : i32 = (current_position as i32) + instruction;
if next_position >= (len as i32) || next_position < 0 {
break;
} else {
if instruction >= 3 {
array[current_position] -= 1;
} else {
array[current_position] += 1;
}
}
current_position = next_position as usize;
}
jumps
}
#[test]
fn count_jumps_test2() {
assert_eq!(count_jumps_2(&mut vec![0, 3, 0, 1, -3]), 10);
}
fn main() {
let mut file = File::open("input-part1.txt").expect("Could not open file");
let mut content = String::new();
file.read_to_string(&mut content).expect("Could not read file");
let mut array : Vec<i32> = content.lines().filter_map(|l| l.parse().ok()).collect();
let mut array2 : Vec<i32> = array.clone();
let jumps = count_jumps(&mut array);
println!("Jumps: {}", jumps);
let jumps2 = count_jumps_2(&mut array2);
println!("Jumps: {}", jumps2);
}
<file_sep>use parser::Program;
use std::collections::HashSet;
pub struct Tree {
pub root : Program,
pub children: Vec<Box<Tree>>,
}
impl Tree {
pub fn find_root_name(programs : &Vec<Program>) -> String {
let mut set : HashSet<String> = HashSet::new();
for p in programs.iter() {
set.insert(p.name.clone());
}
for p in programs.iter() {
for sp in p.subprograms.iter() {
set.remove(sp);
}
}
set.iter().nth(0).unwrap().clone()
}
pub fn construct(mut programs : &mut Vec<Program>, root_name : &String) -> Self {
let index = programs.iter().position(|p| p.name == *root_name ).unwrap();
let program = programs.remove(index);
let mut children : Vec<Box<Tree>> = vec![];
for s in program.subprograms.iter() {
children.push(Box::new(Tree::construct(&mut programs, s)));
}
Tree { root : program, children : children }
}
pub fn display(&self, depth : i32) {
for _ in 0..depth {
print!(" ");
}
println!("{} ({})", self.root.name, self.root.weight);
for c in self.children.iter() {
c.display(depth + 2);
}
}
pub fn total_weight(&self) -> i32 {
let child_weight : i32 = self.children.iter().map(|c| c.total_weight() ).sum();
self.root.weight + child_weight
}
pub fn diss(&self) -> i32 {
if self.children.len() == 0 { return 0; }
let c_diss = self.children.iter().map(|c| c.diss()).filter(|v| *v != 0).nth(0);
println!("{}: {:?}", self.root.name, c_diss);
match c_diss {
None => {
let min : i32 = self.children.iter().map(|c| c.total_weight() ).min().unwrap();
let max : i32 = self.children.iter().map(|c| c.total_weight() ).max().unwrap();
if min == max {
0
} else {
if self.children.iter().filter(|c| c.total_weight() == min ).count() > self.children.iter().filter(|c| c.total_weight() == max ).count() {
self.children.iter().filter(|c| c.total_weight() == max ).nth(0).unwrap().root.weight - (max - min)
} else {
self.children.iter().filter(|c| c.total_weight() == min ).nth(0).unwrap().root.weight - (min - max)
}
}
},
Some(diss) => diss
}
}
}
#[test]
fn tree_test() {
let mut programs : Vec<Program> = vec![
Program::new("pbga".to_string(), 66, vec![]),
Program::new("xhth".to_string(), 57, vec![]),
Program::new("ebii".to_string(), 61, vec![]),
Program::new("havc".to_string(), 66, vec![]),
Program::new("ktlj".to_string(), 57, vec![]),
Program::new("fwft".to_string(), 72, vec!["ktlj".to_string(), "cntj".to_string(), "xhth".to_string()]),
Program::new("qoyq".to_string(), 66, vec![]),
Program::new("padx".to_string(), 45, vec!["pbga".to_string(), "havc".to_string(), "qoyq".to_string()]),
Program::new("tknk".to_string(), 41, vec!["ugml".to_string(), "padx".to_string(), "fwft".to_string()]),
Program::new("jptl".to_string(), 61, vec![]),
Program::new("ugml".to_string(), 68, vec!["gyxo".to_string(), "ebii".to_string(), "jptl".to_string()]),
Program::new("gyxo".to_string(), 61, vec![]),
Program::new("cntj".to_string(), 57, vec![]),
];
let root_name = Tree::find_root_name(&mut programs);
let tree = Tree::construct(&mut programs, &root_name);
tree.display(0);
let w = tree.diss();
println!("{}", w);
assert_eq!(root_name, "tknk");
}
<file_sep>use std::fs::File;
use std::io::Read;
#[derive(Clone)]
enum Direction {
Up,
Down,
Left,
Right
}
#[derive(Clone)]
enum State {
Clean,
Weakened,
Infected,
Flagged
}
struct Map {
field: Vec<Vec<State>>,
x: usize,
y: usize,
direction: Direction,
}
impl Map {
fn turn_right(&mut self) {
match self.direction {
Direction::Up => self.direction = Direction::Right,
Direction::Down => self.direction = Direction::Left,
Direction::Left => self.direction = Direction::Up,
Direction::Right => self.direction = Direction::Down,
}
}
fn turn_left(&mut self) {
match self.direction {
Direction::Up => self.direction = Direction::Left,
Direction::Down => self.direction = Direction::Right,
Direction::Left => self.direction = Direction::Down,
Direction::Right => self.direction = Direction::Up,
}
}
fn advance(&mut self) {
match self.direction {
Direction::Up => self.y -= 1,
Direction::Down => self.y += 1,
Direction::Left => self.x -= 1,
Direction::Right => self.x += 1,
}
}
}
fn parse(filename : &str) -> Map {
let mut file = File::open(filename).expect("Can't open file");
let mut content = String::new();
file.read_to_string(&mut content).expect("Can't read from file");
let mut field : Vec<Vec<State>> = Vec::with_capacity(1_000);
println!("A");
for _ in 0..1_000 {
let mut row : Vec<State> = vec![];
row.resize(1_000, State::Clean);
field.push(row);
}
println!("B");
content.lines().enumerate().for_each(|(i, line)| {
line.chars().enumerate().for_each(|(j, chr)| {
if chr == '#' {
field[500 + i][500 + j] = State::Infected;
} else {
field[500 + i][500 + j] = State::Clean;
}
});
});
println!("C");
let height : usize = content.lines().count();
let width : usize = content.lines().next().unwrap().chars().count();
println!("D");
Map {
field: field,
x: 500 + width/2,
y: 500 + height/2,
direction: Direction::Up
}
}
fn walk(filename : &str) -> i64 {
let mut map = parse(filename);
let mut infection_count = 0;
for index in 0..10_000_000 {
// for i in 490..510 {
// for j in 490..510 {
// let symbol = match map.field[i][j] {
// State::Clean => '.',
// State::Weakened => 'W',
// State::Infected => '#',
// State::Flagged => 'F',
// };
// if i == map.y && j == map.x {
// print!("[{}]", symbol);
// } else {
// print!(" {} ", symbol);
// }
// }
// println!("");
// }
// println!("-------");
if index % 10_000 == 0 {
println!("{}, {}, {}", index, map.x, map.y);
}
match map.field[map.y][map.x] {
State::Clean => {
map.turn_left();
map.field[map.y][map.x] = State::Weakened;
},
State::Weakened => {
map.field[map.y][map.x] = State::Infected;
infection_count += 1;
},
State::Infected => {
map.turn_right();
map.field[map.y][map.x] = State::Flagged;
},
State::Flagged => {
map.turn_right();
map.turn_right();
map.field[map.y][map.x] = State::Clean;
}
}
map.advance()
}
infection_count
}
#[test]
fn walk_test() {
let infection_count = walk("test_input.txt");
assert_eq!(infection_count, 2511944);
}
fn main() {
println!("{}", walk("input.txt"));
}
<file_sep>use std::collections::HashMap;
#[derive(PartialEq, Debug)]
pub enum State {
Pending,
Running,
Locked,
Finished
}
pub struct Program<'a> {
pub name: String,
pub instructions: Vec<&'a str>,
pub registers: HashMap<&'a str, i64>,
pub sent: Vec<i64>,
pub incomming: Vec<i64>,
pub current: i64,
pub result: i64,
pub state: State,
pub sent_count: i64
}
impl<'a> Program<'a> {
pub fn new(id: i64, source: &'a str) -> Self {
let mut p = Program {
name: format!("P{}", id),
instructions : source.lines().collect(),
registers: HashMap::new(),
sent: Vec::new(),
incomming: Vec::new(),
state: State::Pending,
current: 0,
result: 0,
sent_count: 0
};
p.registers.insert("p", id);
p
}
pub fn run(&mut self) {
self.state = State::Running;
while self.current >= 0 && self.current < (self.instructions.len() as i64) {
let mut words = self.instructions[self.current as usize].split_whitespace();
print!("{}: {} ---- ", self.name, self.instructions[self.current as usize]);
match words.next() {
Some("snd") => {
let word = words.next().unwrap();
let value = match word.parse() {
Ok(value) => value,
Err(_) => *self.registers.entry(word.clone()).or_insert(0)
};
self.sent_count += 1;
self.sent.push(value);
self.current += 1;
},
Some("set") => {
let name = words.next().unwrap();
let word = words.next().unwrap();
let value : i64 = match word.parse() {
Ok(value) => value,
Err(_) => *self.registers.entry(word.clone()).or_insert(0)
};
self.registers.insert(name, value);
self.current += 1;
},
Some("add") => {
let name = words.next().unwrap();
let word = words.next().unwrap();
let value : i64 = match word.parse() {
Ok(value) => value,
Err(_) => *self.registers.entry(word.clone()).or_insert(0)
};
*self.registers.entry(name.clone()).or_insert(0) += value;
self.current += 1;
},
Some("mul") => {
let name = words.next().unwrap();
let word = words.next().unwrap();
let value : i64 = match word.parse() {
Ok(value) => value,
Err(_) => *self.registers.entry(word.clone()).or_insert(0)
};
*self.registers.entry(name.clone()).or_insert(0) *= value;
self.current += 1;
},
Some("mod") => {
let name = words.next().unwrap();
let word = words.next().unwrap();
let value : i64 = match word.parse() {
Ok(value) => value,
Err(_) => *self.registers.entry(word.clone()).or_insert(0)
};
*self.registers.entry(name.clone()).or_insert(0) %= value;
self.current += 1;
},
Some("rcv") => {
let word = words.next().unwrap();
if self.incomming.len() == 0 {
self.state = State::Locked;
return;
} else {
let value = self.incomming.pop().unwrap();
self.registers.insert(word.clone(), value);
self.current += 1;
}
},
Some("jgz") => {
let name = words.next().unwrap();
let word = words.next().unwrap();
let value : i64 = match name.parse() {
Ok(v) => v,
Err(_) => self.registers[name]
};
let offset : i64 = match word.parse() {
Ok(v) => v,
Err(_) => *self.registers.entry(word.clone()).or_insert(0)
};
if value > 0 {
self.current = self.current + offset;
} else {
self.current += 1;
}
},
Some(_) | None => panic!("error")
}
for (k, v) in &self.registers {
print!("{}:{} ", k, v);
}
println!("");
}
self.state = State::Finished;
}
}
<file_sep>use std::collections::HashMap;
use std::collections::HashSet;
use std::fs::File;
use std::io::Read;
struct Graph {
nodes: HashMap<i32, HashSet<i32>>
}
impl Graph {
fn new() -> Self {
Graph { nodes : HashMap::new() }
}
fn connect(&mut self, a : i32, b : i32) {
self.nodes.entry(a).or_insert(HashSet::new()).insert(b);
self.nodes.entry(b).or_insert(HashSet::new()).insert(a);
}
fn nodes(&self) -> Vec<&i32> {
self.nodes.keys().collect()
}
}
fn parse(input : &str) -> Graph {
let mut result = Graph::new();
input.lines().for_each(|l| {
let mut parts = l.split("<->");
let a : i32 = parts.next().unwrap().trim().parse().unwrap();
parts.next().unwrap().split(",").map(|n| n.trim().parse().unwrap()).for_each(|b| {
result.connect(a, b);
});
});
result
}
fn reachable_from(root: i32, graph : &Graph) -> HashSet<i32> {
let mut visited : HashSet<i32> = HashSet::new();
let mut edge : Vec<i32> = vec![root];
while edge.len() > 0 {
let node = graph.nodes.get(&edge.pop().unwrap()).unwrap();
node.iter().for_each(|n| {
if !visited.contains(n) {
edge.push(*n);
visited.insert(*n);
}
})
}
visited
}
fn group_count(graph : &Graph) -> i32 {
let mut nodes = graph.nodes().clone();
let mut groups = 0;
while nodes.len() > 0 {
let root = nodes.pop().unwrap();
let reachable = reachable_from(*root, graph);
nodes = nodes.iter().filter(|n| { !reachable.contains(n) }).map(|n| *n).collect();
groups += 1;
}
groups
}
fn main() {
let mut content = String::new();
let mut file = File::open("input.txt").expect("no such file");
file.read_to_string(&mut content).expect("can't read from file");
let g = parse(&content);
println!("{}", reachable_from(0, &g).len());
println!("{}", group_count(&g));
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn reachable_from_root_test() {
let input = "0 <-> 2
1 <-> 1
2 <-> 0, 3, 4
3 <-> 2, 4
4 <-> 2, 3, 6
5 <-> 6
6 <-> 4, 5
";
let g = parse(input);
println!("{:?}", g.nodes());
assert_eq!(reachable_from(0, &g).len(), 6);
assert_eq!(group_count(&g), 2);
}
}
<file_sep>mod knot;
fn construct(input : &str) -> Vec<Vec<i32>> {
let mut grid : Vec<Vec<i32>> = Vec::new();
for i in 0..128 {
let mut row : Vec<i32> = Vec::new();
let hash = knot::hash(&format!("{}-{}", input, i));
for (index, c) in hash.chars().enumerate() {
let b1 = if i32::from_str_radix(&c.to_string(), 16).unwrap() & (1 << 0) != 0 { 1 } else { 0 };
let b2 = if i32::from_str_radix(&c.to_string(), 16).unwrap() & (1 << 1) != 0 { 1 } else { 0 };
let b3 = if i32::from_str_radix(&c.to_string(), 16).unwrap() & (1 << 2) != 0 { 1 } else { 0 };
let b4 = if i32::from_str_radix(&c.to_string(), 16).unwrap() & (1 << 3) != 0 { 1 } else { 0 };
row.push(b4);
row.push(b3);
row.push(b2);
row.push(b1);
}
grid.push(row);
}
grid
}
fn used(input : &str) -> i32 {
let grid = construct(input);
grid.iter().map(|row : &Vec<i32>| {
let sum : i32 = row.iter().sum();
sum
}).sum()
}
fn display(grid : &Vec<Vec<i32>>) {
for i in 0..30 {
for j in 0..30 {
if grid[i][j] == 0 {
print!("... ");
} else {
print!("{:3} ", grid[i][j]);
}
}
println!("");
}
}
fn display_visited(grid : &Vec<Vec<bool>>) {
for i in 0..20 {
for j in 0..20 {
if grid[i][j] {
print!(".");
} else {
print!("#");
}
}
println!("");
}
}
fn dfs(i : usize, j : usize, mut visited : &mut Vec<Vec<bool>>, mut numbers : &mut Vec<Vec<i32>>, counter : i32) -> bool{
if visited[i][j] {
return false;
}
visited[i][j] = true;
numbers[i][j] = counter;
dfs(i-1, j, &mut visited, &mut numbers, counter);
dfs(i+1, j, &mut visited, &mut numbers, counter);
dfs(i, j-1, &mut visited, &mut numbers, counter);
dfs(i, j+1, &mut visited, &mut numbers, counter);
true
}
fn regions(input : &str) -> i32 {
let grid = construct(input);
display(&grid);
let mut visited : Vec<Vec<bool>> = vec![];
let mut numbers : Vec<Vec<i32>> = vec![];
let mut counter = 1;
for i in 0..130 {
let mut v_row = vec![];
let mut n_row = vec![];
for j in 0..130 {
n_row.push(0);
if i == 0 || j == 0 || i == 129 || j == 129 {
v_row.push(true);
} else {
v_row.push(grid[i-1][j-1] == 0);
}
}
numbers.push(n_row);
visited.push(v_row);
}
display_visited(&visited);
for i in 1..129 {
for j in 1..129 {
if dfs(i, j, &mut visited, &mut numbers, counter) {
counter += 1;
}
}
}
display(&numbers);
// numbers.iter().map(|row| { let r : i32 = *row.iter().max().unwrap(); r }).max().unwrap()
counter - 1
}
#[test]
fn used_test() {
assert_eq!(used("flqrgnkx"), 8108);
}
#[test]
fn regions_test() {
assert_eq!(regions("flqrgnkx"), 1242);
}
fn main() {
println!("{}", used("nbysizxe"));
println!("{}", regions("nbysizxe"));
}
<file_sep>use std::io::prelude::*;
use std::fs::File;
use std::collections::HashSet;
use std::iter::FromIterator;
fn has_duplicate_words(string: &str) -> bool {
let mut words = HashSet::new();
for word in string.split_whitespace() {
if words.contains(word) {
return true;
} else {
words.insert(word);
}
}
false
}
fn has_matching_anagrams(string: &str) -> bool {
let words_with_sorted_chars : Vec<String> = string.split_whitespace().map(|s| {
let mut sorted_chars: Vec<char> = s.chars().collect();
sorted_chars.sort();
String::from_iter(sorted_chars)
}).collect();
let mut words = HashSet::new();
for word in words_with_sorted_chars {
if words.contains(&word) {
return true;
} else {
words.insert(word.clone());
}
}
false
}
#[test]
fn has_matching_anagrams_test() {
assert_eq!(has_matching_anagrams("abcde fghij"), false);
assert_eq!(has_matching_anagrams("abcde xyz ecdab is not valid"), true);
assert_eq!(has_matching_anagrams("a ab abc abd abf abj"), false);
}
fn main() {
let mut file = File::open("input-part1.txt").expect("Can't open file");
let mut content = String::new();
file.read_to_string(&mut content).expect("Reading from file failed");
let valid_count = content.lines().filter(|p| { !has_duplicate_words(p) }).count();
println!("Valid Password count: {}", valid_count);
let valid_count2 = content.lines().filter(|p| { !has_matching_anagrams(p) }).count();
println!("Valid Password count: {}", valid_count2);
}
<file_sep>use std::io::Read;
use std::fs::File;
#[derive(PartialEq, Debug)]
enum Direction {
Up,
Left,
Right,
Down
}
fn load_map(filename : &str) -> Vec<Vec<char>> {
let mut file = File::open(filename).expect("Can't open file");
let mut content = String::new();
let mut result = Vec::new();
file.read_to_string(&mut content).expect("Can't read from file");
content.lines().for_each(|line| {
result.push(line.chars().collect());
});
result
}
fn route(filename : &str) -> (String, i64) {
let map : Vec<Vec<char>> = load_map(filename);
let mut path = String::new();
let mut x = map[0].iter().position(|c| *c == '|').unwrap();
let mut y = 0;
let mut dir = Direction::Down;
let mut steps = 0;
while map[y][x] != ' ' {
steps += 1;
println!("{},{}", x, y);
if map[y][x].is_alphabetic() {
path.push(map[y][x]);
}
match dir {
Direction::Up => {
if map[y-1][x] != ' ' {
y -= 1;
} else if map[y][x-1] != ' ' {
x -= 1;
dir = Direction::Left;
} else if map[y][x+1] != ' ' {
x += 1;
dir = Direction::Right;
} else {
break;
}
},
Direction::Down => {
if map[y+1][x] != ' ' {
y += 1;
} else if map[y][x-1] != ' ' {
x -= 1;
dir = Direction::Left;
} else if map[y][x+1] != ' ' {
x += 1;
dir = Direction::Right;
} else {
break;
}
},
Direction::Right => {
if map[y][x+1] != ' ' {
x += 1;
} else if map[y-1][x] != ' ' {
y -= 1;
dir = Direction::Up;
} else if map[y+1][x] != ' ' {
y += 1;
dir = Direction::Down;
} else {
break;
}
},
Direction::Left => {
if map[y][x-1] != ' ' {
x -= 1;
} else if map[y-1][x] != ' ' {
y -= 1;
dir = Direction::Up;
} else if map[y+1][x] != ' ' {
y += 1;
dir = Direction::Down;
} else {
break;
}
}
}
}
(path, steps)
}
fn main() {
println!("{:?}", route("input.txt"));
}
#[test]
fn route_test() {
assert_eq!(route("test_input.txt"), ("ABCDEF".to_string(), 38));
}
<file_sep>use std::fs::File;
use std::io::Read;
#[derive(Debug)]
struct Layer {
position: i32,
depth: i32,
}
impl Layer {
fn is_deadly(&self, delay : i32) -> bool {
let time = self.position + delay;
let pos = time % ((self.depth - 1) * 2);
// println!("{}, {}, {}", self.position, self.depth, pos);
// println!("{}, {}", time, pos);
pos == 0
}
fn penatly(&self) -> i32 {
// println!("penalty: {}", self.position * self.depth);
self.position * self.depth
}
}
struct Layers {
layers : Vec<Layer>
}
impl Layers {
fn new(input: &str) -> Self {
let mut layers = Vec::new();
input.lines().for_each(|l| {
let mut parts = l.split(":").map(|part| part.trim().parse().unwrap());
let position = parts.next().unwrap();
let depth = parts.next().unwrap();
layers.push(Layer { position : position, depth : depth });
});
Layers { layers : layers }
}
fn score(&self) -> i32 {
self.layers
.iter()
.filter(|l| l.is_deadly(0))
.map(|l| l.penatly())
.sum()
}
fn safe_delay(&self) -> i32 {
let mut delay = 0;
loop {
let has_dedly = self.layers.iter().any(|l| l.is_deadly(delay));
println!("{}", delay);
if !has_dedly {
break;
}
delay += 1;
}
delay
}
}
#[test]
fn calculate_test() {
let input = "0: 3
1: 2
4: 4
6: 4
";
let layers = Layers::new(input);
assert_eq!(layers.score(), 24);
}
#[test]
fn safe_delay() {
let input = "0: 3
1: 2
4: 4
6: 4
";
let layers = Layers::new(input);
assert_eq!(layers.safe_delay(), 10);
}
fn main() {
let mut content = String::new();
let mut file = File::open("input.txt").expect("can't open file");
file.read_to_string(&mut content).expect("can't read from file");
println!("{}", Layers::new(&content).score());
println!("{}", Layers::new(&content).safe_delay());
}
<file_sep>use std::fs::File;
use std::io::prelude::*;
mod parser;
mod tree;
fn main() {
let mut file = File::open("input.txt").expect("Can't open file");
let mut content = String::new();
file.read_to_string(&mut content).expect("Can't read file");
let mut programs = parser::Program::parse_all(&content);
let root_name = tree::Tree::find_root_name(&programs);
let tree = tree::Tree::construct(&mut programs, &root_name);
tree.display(9);
let dissbalance = tree.diss();
println!("part 1: {}", tree.root.name);
println!("part 2: {}", dissbalance);
}
<file_sep>fn radius(location : i32) -> i32 {
let mut result = 0;
loop {
if result * result < location {
result += 1;
} else {
break;
}
}
result / 2
}
fn access_cost(location: i32) -> i32 {
let r = radius(location);
let up = (2 * r + 1) * (2 * r + 1);
let down = (2 * r - 1) * (2 * r - 1);
let len = (up - down) / 4;
let (x, y) = if down < location && location <= down + len {
(r, location - down - len/2)
} else if down + len < location && location <= down + 2 * len {
(location - down - len - len/2, r)
} else if down + 2 * len < location && location <= down + 3 * len {
(-r, location - down - 2*len - len/2)
} else {
(location - down - 3*len - len/2, -r)
};
x.abs() + y.abs()
}
fn adj_sum(table : &Vec<Vec<i32>>, x : usize, y : usize) -> i32 {
table[y+1][x-1] + table[y+1][x] + table[y+1][x+1] +
table[y ][x-1] + 0 + table[y ][x+1] +
table[y-1][x-1] + table[y-1][x] + table[y-1][x+1]
}
fn show_table(table : &Vec<Vec<i32>>) {
for row in table.iter().rev() {
println!("{:?}", row);
}
println!("------------------------");
}
//
// horible code. kill me please
//
fn access_cost_part2(location: i32) -> i32 {
let mut table = Vec::with_capacity(20);
for _ in 0..20 {
table.push(vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
}
table[10][10] = 1;
let mut x = 10;
let mut y = 10;
let mut len = 2;
for r in (1..5) {
len = r * 2;
x += 1;
for i in 0..len {
let s = adj_sum(&table, x, y + i);
if s > location {
return s;
}
table[y+i][x] = s;
}
x -= 1;
y += len - 1;
for i in 0..len {
let s = adj_sum(&table, x-i, y);
if s > location {
return s;
}
table[y][x-i] = s;
}
x -= len - 1;
y -= 1;
for i in 0..len {
let s = adj_sum(&table, x, y-i);
if s > location {
return s;
}
table[y-i][x] = s;
}
y -= len - 1;
x += 1;
for i in 0..len {
let s = adj_sum(&table, x+i, y);
if s > location {
return s;
}
table[y][x+i] = s;
}
x += len - 1;
}
show_table(&table);
0
}
fn main() {
println!("Result part 1: {}", access_cost(277678));
println!("Result part 2: {}", access_cost_part2(277678));
}
#[cfg(test)]
mod test {
use super::access_cost;
#[test]
fn part1_example1() {
assert_eq!(access_cost(1), 0)
}
#[test]
fn part1_example2() {
assert_eq!(access_cost(12), 3)
}
#[test]
fn part1_example3() {
assert_eq!(access_cost(23), 2)
}
#[test]
fn part1_example4() {
assert_eq!(access_cost(1024), 31)
}
}
<file_sep>use std::fs::File;
use std::io::Read;
mod program;
use program::{Program,State};
fn transfer(p1 : &mut Program, p2 : &mut Program) {
for v in &p1.sent {
p2.incomming.insert(0, v.clone());
}
p1.sent = Vec::new();
}
fn is_finished(p1 : &Program, p2 : &Program) -> bool {
println!("STATES: {:?}, {:?}, {:?}, {:?}", p1.state, p2.state, p1.incomming, p2.incomming);
if p1.state == State::Finished && p2.state == State::Finished {
return true;
}
// deadlock
if p1.state == State::Locked && p1.incomming.len() == 0 && p2.state == State::Locked && p2.incomming.len() == 0 {
return true;
}
false
}
fn execute(source : &str) -> i64 {
let mut p1 = Program::new(0, source);
let mut p2 = Program::new(1, source);
while !is_finished(&p1, &p2) {
p1.run();
println!("BEFORE TRANSFER: {:?}", p1.sent);
transfer(&mut p1, &mut p2);
println!("AFTER TRANSFER: {:?}", p2.incomming);
p2.run();
transfer(&mut p2, &mut p1);
}
p2.sent_count
}
fn main() {
let mut content = String::new();
let mut file = File::open("input.txt").expect("file not found");
file.read_to_string(&mut content).expect("can't read file");
println!("{}", execute(&content));
}
#[test]
fn transfer_test() {
let mut p1 = Program::new(0, "");
let mut p2 = Program::new(1, "");
p1.sent.push(1);
p1.sent.push(2);
p1.sent.push(3);
p2.incomming.push(4);
p2.incomming.push(5);
transfer(&mut p1, &mut p2);
assert_eq!(p1.sent, vec![]);
assert_eq!(p2.incomming, vec![3, 2, 1, 4, 5]);
}
#[test]
fn execute_test() {
let source = "snd 1
snd 2
snd p
rcv a
rcv b
rcv c
rcv d
";
assert_eq!(execute(source), 3);
}
|
7236dfcd0d1f58db398dc589967980c974b71267
|
[
"Rust",
"TOML",
"Markdown"
] | 30 |
Rust
|
shiroyasha/advent-of-code-2017
|
a234808f7ef628499361fdc3711315bd0df15d29
|
c84c351d27343ef72eac9974a85f712206bd39f2
|
refs/heads/master
|
<repo_name>Thunder07/Init-Setup<file_sep>/Ubuntu.sh
#!/bin/sh
if [ "$(id -u)" != "0" ]; then
echo "This script must be run as root" 1>&2
sudo $0
exit
fi
sudo apt-add-repository -y ppa:paolorotolo/android-studio
sudo apt-get -y update
sudo apt-get -y install bison build-essential curl flex git gnupg gperf libesd0-dev liblz4-tool libncurses5-dev libsdl1.2-dev libwxgtk2.8-dev libxml2 libxml2-utils lzop openjdk-6-jdk openjdk-6-jre pngcrush schedtool squashfs-tools xsltproc zip zlib1g-dev
sudo apt-get -y install g++-multilib gcc-multilib lib32ncurses5-dev lib32readline-gplv2-dev lib32z1-dev
sudo apt-get install libc6-i386 lib32stdc++6 lib32gcc1 lib32ncurses5 lib32z1
sudo apt-get -y install git wget hexchat html-xml-utils html2text
sudo apt-get -y install p7zip-rar p7zip-full unace unrar zip unzip sharutils rar uudeview mpack arj cabextract file-roller
sudo apt-get -y install unity-tweak-tool gnome-tweak-tool
sudo apt-get -y install android-tools-adb android-tools-fastboot
sudo apt-get -y install android-studio
sudo wget -O /etc/pm/sleep.d/11_fan_3.11.0 https://raw.githubusercontent.com/Thunder07/Init-Setup/master/11_fan_3.11.0
sudo chmod 755 /etc/pm/sleep.d/11_fan_3.11.0
sudo wget -O /etc/udev/rules.d/51-android.rules https://raw.githubusercontent.com/NicolasBernaerts/ubuntu-scripts/master/android/51-android.rules
sudo chmod a+r /etc/udev/rules.d/51-android.rules
exit
git clone https://github.com/Thunder07/apk2gold.git
cd apk2gold
./make.sh
cd ..
exit
mkdir -p ~/bin
PATH="$HOME/bin:$PATH"
curl https://storage.googleapis.com/git-repo-downloads/repo > ~/bin/repo
chmod a+x ~/bin/repo
droid_root="~/android/omni"
mkdir -p ~/$droid_root
cd $droid_root
repo init -u https://github.com/marduk191/recovery_manifest.git
cd $droid_root
rm -Rf ./bootable/recovery
git clone https://github.com/Thunder07/Team-Win-Recovery-Project.git bootable/recovery
cd ./bootable/recovery/
git remote add Tas https://github.com/Tasssadar/Team-Win-Recovery-Project.git
cd $droid_root
git clone https://github.com/Thunder07/AROMA-Filemanager.git bootable/recovery/aromafm
git clone https://github.com/Thunder07/multirom.git system/extras/multirom
git clone https://github.com/Tasssadar/libbootimg.git system/extras/libbootimg
cd system/extras/multirom
git remote add Tas https://github.com/Tasssadar/multirom.git
git submodule update --init
<file_sep>/VPSCentOSSetup.sh
#!/bin/bash
if [ "$(id -u)" != "0" ]; then
echo "This script must be run as root" 1>&2
exit 1
fi
IP=`who am i | awk '{print $5}' | sed 's/[()]//g'`
ttypts=`who am i | awk '{print $2}' | sed 's|\/[1-9]||g'`
if [["$ttypts" != "pts"]]; then
IP="127.0.0.1"
echo "we've detected that you're not connected through SSH"
echo "Thus for whitelisting we will assume your IP is 127.0.0.1"
read -p "Continue(y) or Enter a new IP(n)??[y/n]" ans1
if [[$ans1 == "n"]]; then
clear
read -p "Please Enter IP:" IP
elif [[$ans1 == "y"]]; then
clear
echo "Quitting"
return 0 2> /dev/null || exit 0
else
clear
echo "Answer Unclear Quitting"
return 0 2> /dev/null || exit 0
fi
fi
echo "This script was made to be used with Centos7/RH7"
echo "This automated script will install & setup:"
echo "Ajenti(+V Addons), Denyhosts, EPEL repo, mysql & Knock"
echo "While also configurating ports assoicated with them"
echo "Your IP ($IP) will be whitelisted from denyhosts and granted access to ssh through the firewall."
read -p "Do you want to start??[y/n]" ans2
if [[$ans2 == "y"]] ; then
echo "Starting....."
else
echo "Quitting"
return 0 2> /dev/null || exit 0
if
rpm -Uvh http://mirror-fpt-telecom.fpt.net/repoforge/redhat/el7/en/x86_64/rpmforge/RPMS/denyhosts-2.6-5.el7.rf.noarch.rpm
cp /etc/hosts.allow hosts.allow.bak
echo "sshd: $IP">>/etc/hosts.allow
systemctl restart denyhosts
systemctl enable denyhosts
echo ':: Adding EPEL repo'
rpm -ivh https://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-2.noarch.rpm || true
echo ':: Adding Ajenti repo'
rpm -ivh http://repo.ajenti.org/ajenti-repo-1.0-1.noarch.rpm
rpm -ivh http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm
yum install mysql-server -y
echo ':: Installing Ajenti package'
yum install ajenti -y
yum install ajenti-v ajenti-v-nginx ajenti-v-mysql ajenti-v-php-fpm php-mysql ajenti-v-ftp-pureftpd -y
cp /var/lib/ajenti/plugins/vh-pureftpd/pureftpd.py pureftpd.py.bak
cd /var/lib/ajenti/plugins/vh-pureftpd/
cat pureftpd.py | sed -e 's|clf:/var/log/pureftpd.log|clf:/var/log/pureftpd.log\nPassivePortRange 40110 40510\nTLS 2\nTLSCipherSuite HIGH:MEDIUM:+TLSv1:!SSLv2:+SSLv3|g'>pureftpd.py.new
cat pureftpd.py.new>pureftpd.py
rm pureftpd.py.new -f
python -m pureftpd.py
cd ~
firewall-cmd --permanent --zone=public --add-port=21/tcp
firewall-cmd --permanent --zone=public --add-service=ftp
firewall-cmd --permanent --zone=public --add-port=40110-40510/tcp
firewall-cmd --permanent --zone=public --add-port=80/tcp
firewall-cmd --permanent --zone=public --add-service=http
firewall-cmd --permanent --zone=public --add-port=8000/tcp
firewall-cmd --reload
echo ':: Done! Open https://<address>:8000 in browser'
systemctl restart pure-ftpd
systemctl restart ajenti
systemctl restart nginx
systemctl enable pure-ftpd
systemctl enable ajenti
systemctl enable nginx
#For security, changing sshd port
#You should manually disable ssh root login and create a 2nd root usr
echo "Securing Root Access, Disabling Remote Root For Security, changing ssh port."
echo "If You Use SSH, Please Create A 2nd SU before proceeding."
read -p "Do you want to continue??[y/n]" ans
if [[$ans == "y"]] ; then
cp /etc/ssh/sshd_config sshd_config.bak
echo "PermitRootLogin no">>/etc/ssh/sshd_config
echo "Protocol 2">>/etc/ssh/sshd_config
else
echo "Skipping"
fi
#Extras
yum install wget -y
echo "Downloading, Building, Updating & Setting up Knock"
#Knock is not avalible for Centos7, Thus we must build it then update it.
yum install rpm-build redhat-rpm-config make gcc -y
#wget http://www.invoca.ch/pub/packages/knock/RPMS/ils-5/SRPMS/knock-0.5-7.el5.src.rpm
#rpmbuild --rebuild knock-0.5-7.el5.src.rpm
systemctl stop knockd
wget https://github.com/jvinet/knock/archive/master.zip
unzip master.zip
cd knock-master
autoreconf -fi
./configure --prefix=/usr
make
make install
cd ..
cp /etc/knockd.conf knockd.conf.bak
sed 's|/usr/sbin/iptables -A INPUT -s %IP% -p tcp --syn --dport 22 -j ACCEPT|/usr/bin/firewall-cmd --zone=public --add-rich-rule="rule family="ipv4" source address="%IP%" port protocol="tcp" port="22" accept"|' /etc/knockd.conf >/etc/knockd.conf.1
sed 's|/usr/sbin/iptables -D INPUT -s %IP% -p tcp --syn --dport 22 -j ACCEPT|/usr/bin/firewall-cmd --zone=public --remove-rich-rule="rule family="ipv4" source address="%IP%" port protocol="tcp" port="22" accept"|' /etc/knockd.conf.1 >/etc/knockd.conf.2
sed 's/syn,ack/syn/' /etc/knockd.conf.2 >/etc/knockd.conf
rm -f /etc/knockd.conf.*
firewall-cmd --permanent --remove-service=ssh
firewall-cmd --permanent --remove-port=22/tcp
firewall-cmd --reload
systemctl start knockd
systemctl enable knockd
echo "Yum Update"
yum update -y
<file_sep>/README.md
VPSCentOSSetup
==============
<file_sep>/11_fan_3.11.0
#!/bin/sh
#
# Reset fan speeds after resume, otherwise they blow at maximum speed
#
# Used as work-around for ACPI kernel bug 58301
# https://bugzilla.kernel.org/show_bug.cgi?id=58301
#
# The idea for this fix was taken from
# http://ubuntuforums.org/showthread.php?t=1761370
#
# Author: <EMAIL>
#
# To be saved as /etc/pm/sleep.d/11_fan_3.11.0
case "$1" in
thaw|resume)
for i in /sys/class/thermal/cooling_device* ; do
type=`cat $i/type`
if [ "$type" = "Fan" ] ; then
echo 0 > $i/cur_state
fi
done
;;
esac
<file_sep>/Addon.sh
#!/bin/bash
rpm -Uvh http://mirror.karneval.cz/pub/linux/fedora/epel/7/x86_64/e/epel-release-7-2.noarch.rpm
rpm -Uvh http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el7.rf.x86_64.rpm
|
615d36695b642441a540d091a0f5ed9b1ab116f8
|
[
"Markdown",
"Shell"
] | 5 |
Markdown
|
Thunder07/Init-Setup
|
b6d273a206ee2a7b0e2391c608b618e62dc631eb
|
0cc7e1cdc8b8f825bbef7177abe2baa077c361d4
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<html lang="zxx">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sujon - Single Blog</title>
<!-- css include -->
<link rel="stylesheet" type="text/css" href="../css/materialize.css">
<link rel="stylesheet" type="text/css" href="../css/icofont.css">
<link rel="stylesheet" type="text/css" href="../css/owl.carousel.min.css">
<link rel="stylesheet" type="text/css" href="../css/owl.theme.default.min.css">
<link rel="stylesheet" href="../font/iconfont.css">
<!-- my css include -->
<link rel="stylesheet" type="text/css" href="../css/custom-menu.css">
<link rel="stylesheet" type="text/css" href="../css/style.css">
<link rel="stylesheet" type="text/css" href="../css/responsive.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
</head>
<body>
<div id="app">
<div class="thetop"></div>
<!-- for back to top -->
<div class='backToTop'>
<a href="#" class='scroll'>
<span class="go-up">
<i class="icofont icofont-long-arrow-up"></i>
</span>
</a>
</div>
<!-- backToTop -->
<!-- ==================== header-section Start ====================-->
<header id="header-section" class="header-section w100dt navbar-fixed">
<nav class="nav-extended main-nav">
<div class="container">
<div class="row">
<div class="nav-wrapper w100dt">
<div class="logo left">
<a href="../index.html" class="brand-logo">
<img src="../img/logo/logo.png" alt="brand-logo">
</a>
</div>
<!-- logo -->
<div>
<a data-activates="mobile-demo" class="button-collapse">
<i class="icofont icofont-navigation-menu"></i>
</a>
<ul id="nav-mobile" class="main-menu center-align hide-on-med-and-down">
<li class=""><a href="../index.html">主页</a></li>
<li><a href="../cateogry.html">Html教程</a></li>
<!-- <li class="dropdown">
<a >PAGES <i class="icofont icofont-simple-down"></i></a>
<ul class="dropdown-container">
<li><a href="404.html">404 Page</a></li>
</ul>
</li> -->
<li><a href="../single-blog.html">Javascript教程</a></li>
<li><a href="../contact.html">联系我</a></li>
</ul>
<!-- /.main-menu -->
<!-- ******************** sidebar-menu ******************** -->
<ul class="side-nav" id="mobile-demo">
<li class="snavlogo center-align"><img src="../img/logo/logo.png" alt="logo"></li>
<li class="active"><a href="../index.html">主页</a></li>
<li><a href="../cateogry.html">Html教程</a></li>
<li><a href="../single-blog.html">Javascript教程</a></li>
<li><a href="../contact.html">联系我</a></li>
</ul>
</div>
<!-- main-menu -->
<a class="search-trigger right">
<i class="icofont icofont-search"></i>
</a>
<!-- search -->
<div id="myNav" class="overlay">
<a href="javascript:void(0)" class="closebtn">×</a>
<div class="overlay-content">
<form>
<input type="text" name="search" placeholder="Search...">
<br>
<button class="waves-effect waves-light" type="submit"
name="action">Search</button>
</form>
</div>
</div>
</div>
<!-- /.nav-wrapper -->
</div>
<!-- row -->
</div>
<!-- container -->
</nav>
</header>
<!-- /#header-section -->
<!-- ==================== header-section End ====================-->
<!-- ==================== header-section Start ====================-->
<section id="breadcrumb-section" class="breadcrumb-section w100dt mb-30">
<div class="container">
<nav class="breadcrumb-nav w100dt">
<div class="page-name hide-on-small-only left">
<h4>SINGLE BLOG</h4>
</div>
<div class="nav-wrapper right">
<a href="index.html" class="breadcrumb">Home</a>
<a href="single-blog.html" class="breadcrumb active">Blog Single</a>
</div>
<!-- /.nav-wrapper -->
</nav>
<!-- /.breadcrumb-nav -->
</div>
<!-- container -->
</section>
<!-- /.breadcrumb-section -->
<!-- ==================== header-section End ====================-->
<!-- ==================== single-blog-section start ====================-->
<section id="single-blog-section" class="single-blog-section w100dt mb-50">
<div class="container">
<div class="row">
<div class="col m8 s12">
<div class="blogs mb-30">
<div class="card">
<div class="card-image">
<img src="img/selfie.jpg" alt="Image">
</div>
<!-- /.card-image -->
<div class="card-content w100dt">
<p>
<a href="#" class="tag left w100dt l-blue mb-30">Lifestyle</a>
</p>
<a href="#" class="card-title mb-30">
Labore Etdolore Magna Aliqua Utero Ratione
</a>
<p class="mb-30">
Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur
adipisci velit sed quia non numquam eius modi tempora incidunt ut labore et
dolore magnam aliquam.
</p>
<ul class="post-mate-time left mb-30">
<li>
<p class="hero left">
By - <a href="#" class="l-blue">SujonMaji</a>
</p>
</li>
<li>
<i class="icofont icofont-ui-calendar"></i> 5 February'17
</li>
</ul>
<ul class="post-mate right mb-30">
<li class="like">
<a href="#">
<i class="icofont icofont-heart-alt"></i> 55
</a>
</li>
<li class="comment">
<a href="#">
<i class="icofont icofont-comment"></i> 32
</a>
</li>
</ul>
<p class="w100dt mb-10">
Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur
adipisci velit sed quia non numquam eius modi tempora incidunt ut labore et
dolore magnam aliquam.Neque porro quisquam est qui dolorem ipsum quia dolor sit
amet, consectetur adipisci velit sed quia non numquam eius modi tempora incidunt
ut labore et dolore magnam aliquam.
</p>
<p class="w100dt mb-50">
Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur
adipisci velit sed quia non numquam eius modi tempora incidunt ut labore et
dolore magnam aliquam.
</p>
<img class="mb-30" src="img/fashion.jpg" alt="Image">
<p class="w100dt">
Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur
adipisci velit sed quia non numquam eius modi tempora incidunt ut labore et
dolore magnam aliquam.Neque porro quisquam est qui dolorem ipsum quia dolor sit
amet, consectetur adipisci velit sed quia non numquam eius modi tempora incidunt
ut labore et dolore magnam aliquam.
</p>
<blockquote class="grey lighten-2">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Unde error cumque
voluptatibus autem voluptatum corrupti cum facilis reprehenderit fugiat beatae.
</blockquote>
<p class="w100dt mb-50">
Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur
adipisci velit sed quia non numquam eius modi tempora incidunt ut labore et
dolore magnam aliquam.
</p>
<img class="mb-10" src="img/travel2.jpg" alt="Image">
<p class="w100dt mb-50">
Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur
adipisci velit sed quia non numquam eius modi tempora incidunt ut labore et
dolore magnam aliquam.Neque porro quisquam est qui dolorem ipsum quia dolor sit
amet, consectetur adipisci velit sed quia non numquam eius modi tempora incidunt
ut labore et dolore magnam aliquam.
</p>
<ul class="tag-list left">
<li><a href="#!" class="waves-effect">#Fashion</a></li>
<li><a href="#!" class="waves-effect">#Lifestyle</a></li>
<li><a href="#!" class="waves-effect">#Travel</a></li>
</ul>
<!--
<ul class="share-links right">
<li><a href="#" class="facebook"><i
class="icofont icofont-social-facebook"></i></a></li>
<li><a href="#" class="twitter"><i
class="icofont icofont-social-twitter"></i></a></li>
<li><a href="#" class="google-plus"><i
class="icofont icofont-social-google-plus"></i></a></li>
<li><a href="#" class="linkedin"><i
class="icofont icofont-brand-linkedin"></i></a></li>
<li><a href="#" class="pinterest"><i
class="icofont icofont-social-pinterest"></i></a></li>
<li><a href="#" class="instagram"><i
class="icofont icofont-social-instagram"></i></a></li>
</ul> -->
</div>
<!-- /.card-content -->
</div>
<!-- /.card -->
</div>
<!-- /.blogs -->
<div class="peoples-comments w100dt mb-30">
<div class="sidebar-title center-align">
<h2>评论</h2>
</div>
<div class="comment-area w100dt">
<div id="gitalk-container"></div>
</div>
<!-- /.comment-area -->
</div>
<!-- /.peoples-comments -->
<!-- /.leave-comment -->
</div>
<!-- colm8 -->
<div class="col s12 m4 l4">
<div class="sidebar-testimonial mb-30">
<div class="sidebar-title center-align">
<h2>Hi Its Me!</h2>
</div>
<!-- /.sidebar-title -->
<div class="carousel carousel-slider center" data-indicators="true">
<div class="carousel-item">
<div class="item-img">
<span></span>
</div>
<h2>王志超</h2>
<small>前端码农</small>
<p>
学无止境
</p>
</div>
</div>
</div>
<!-- /.sidebar-testimonial -->
<div class="sidebar-followme w100dt mb-30">
<div class="sidebar-title center-align">
<h2>关注我</h2>
</div>
<!-- /.sidebar-title -->
<ul class="followme-links w100dt">
<li class="mrb15">
<a class="facebook" target="_blank" href="https://www.cnblogs.com/wangzhichao/">
<i class="iconfont icon-bokeyuan"></i>
<small class="Followers white-text">354 Likes</small>
</a>
</li>
<li class="mrb15">
<a class="twitter" target="_blank" href="https://github.com/wzc570738205">
<i class="iconfont icon-git"></i>
<small class="Followers white-text">8 Follows</small>
</a>
</li>
<li>
<a class="google-plus" target="_blank"
href="//shang.qq.com/wpa/qunwpa?idkey=<KEY>">
<i class="iconfont icon-qq"></i>
<small class="Followers white-text">256 Follows</small>
</a>
</li>
</ul>
</div>
<!-- /.sidebar-followme -->
<!-- /.featured-posts -->
<!-- /.top-post -->
</div>
<!-- colm4 -->
</div>
<!-- row -->
</div>
<!-- container -->
</section>
<!-- /#single-blog-section -->
<!-- ==================== single-blog-section end ====================-->
<!-- ==================== instag leftram-section Start ====================-->
<section id="instagram-section" class="instagram-section w100dt">
<div class="instagram-link w100dt">
<a href="//shang.qq.com/wpa/qunwpa?idkey=<KEY>"
target="_blank" rel="noopener noreferrer">
<span>你可以在这里找到我</span><br>
@wangzc
</a>
</div>
</section>
<!-- /#instag leftram-section -->
<!-- ==================== instag leftram-section End ====================-->
<!-- ==================== footer-section Start ====================-->
<footer id="footer-section" class="footer-section w100dt">
<div class="container">
<div class="footer-logo w100dt center-align mb-30">
<a href="#" class="brand-logo">
<img src="../img/logo/logo.png" alt="brand-logo">
</a>
</div>
<!-- /.footer-logo -->
<p class="center-align">
<i class="icofont icofont-heart-alt l-blue"></i>
All Right Reserved, Deasined by
<a href="#" class="l-blue">SujonMaji</a>
</p>
</div>
<!-- container -->
</footer>
<!-- /#footer-section -->
<!-- ==================== footer-section End ====================-->
</div>
</body>
</html>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui@2.13.0/lib/index.js"></script>
<script src="../js/index.js"></script>
<!-- my custom js -->
<script type="text/javascript" src="../js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="../js/materialize.js"></script>
<script type="text/javascript" src="../js/owl.carousel.min.js"></script>
<!-- my custom js -->
<script type="text/javascript" src="../js/custom.js"></script>
<script>
var gitalk = new Gitalk({
clientID: 'be18b06eea7b7021c473',
clientSecret: '<KEY>',
repo: 'wangzc',
owner: 'wzc570738205',
admin: ['wzc570738205'],
id: location.pathname, // Ensure uniqueness and length less than 50
distractionFreeMode: false // Facebook-like distraction free mode
})
gitalk.render('gitalk-container')
</script><file_sep>var Main = {
data() {
return {
banner1List: [
{
url: './img/banner/banner8.jpg',
tag: 'HTML5',
href:'./act/html/index.html',
title: 'HTML5 是定义 HTML 标准的最新的版本',
detile: '它是一个新版本的HTML语言,具有新的元素,属性和行为,\n\r\b它有更大的技术集,允许构建更多样化和更强大的网站和应用程序。这个集合有时称为HTML5和它的朋友们,不过大多数时候仅缩写为一个词 HTML5。'
},
{
url: './img/banner/banner5.jpg',
tag: 'JavaScript',
title:
'JavaScript是一种具有函数优先的轻量级,解释型或即时编译型的编程语言',
detile: '因为你没有选择。在Web世界里,只有JavaScript能跨平台、跨浏览器驱动网页,与用户交互'
},
{
url: './img/banner/banner7.jpg',
tag: 'Angular',
title: '渐进式应用',
detile: '充分利用现代 Web 平台的各种能力,提供 App 式体验。高性能、离线使用、免安装'
}
],
banner2List: [
{
url: './img/banner2/banner1.png',
name: 'wangzc',
number:2,
title: 'Html基础',
detile: '详细介绍html的标签'
},
{
url: './img/banner2/banner2.png',
name: 'wangzc',
number:12,
title: 'Css3',
detile: '网页的护肤品'
}, {
url: './img/banner2/banner3.png',
name: 'wangzc',
number:36,
title: 'javascript',
detile: '轻量级,解释型或即时编译型的编程语言'
}, {
url: './img/banner2/banner4.png',
name: 'wangzc',
number:66,
title: 'Angular2.0+',
detile: '企业级应用框架详细教程'
}, {
url: './img/banner2/banner5.png',
name: 'wangzc',
number:106,
title: 'Vue2.0',
detile: '渐进式JavaScript 框架使用指南'
},
],
blogs: [{
url:'./img/artilce/banner1.jpeg',
tag: 'Html、Css',
href:'./act/html/index.html',
title: 'HTML 超文本标记语言',
detile: 'HTML是一种基础技术,常与CSS、JavaScript一起被众多网站用于设计网页、网页应用程序以及移动应用程序的用户界面[3]。网页浏览器可以读取HTML文件,并将其渲染成可视化网页。HTML描述了一个网站的结构语义随着线索的呈现,使之成为一种标记语言而非编程语言。',
name: 'wangzc',
time: '2016/02/03',
like: '1.1k',
number: 150
}, {
url:'./img/artilce/banner2.jpg',
tag: 'Javascript',
title: 'JavaScript编程语言',
detile: 'JavaScript是一门基于原型、函数先行的语言[6],是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持I/O,比如网络、存储和图形等,但这些都可以由它的宿主环境提供支持。它已经由ECMA(欧洲电脑制造商协会)通过ECMAScript实现语言的标准化[5]。它被世界上的绝大多数网站所使用,也被世界主流浏览器(Chrome、IE、Firefox、Safari、Opera)支持',
name: 'wangzc',
time: '2016/03/26',
like: 6890,
number: 65
},{
url:'./img/artilce/banner3.jpeg',
tag: 'Javascript、Typescript',
title: 'TypeScript编程语言',
detile: 'TypeScript是JavaScript的一个严格超集,并添加了可选的静态类型和使用看起来像基于类的面向对象编程语法操作 Prototype,它的设计目标是开发大型应用,然后转译成JavaScript',
name: 'wangzc',
time: '2017/12/03',
like: 260,
number:20
},{
url:'./img/artilce/banner4.jpg',
tag: 'Angular、Mvc',
title: 'Angular8.0新特性',
detile: '在今天早些时候Angular团队发布了8.0.0稳定版。其实早在NgConf 2019大会上,演讲者就已经提及了从工具到差分加载的许多内容以及更多令人敬畏的功能。下面是我对8.0.0一些新功能的简单介绍,希望可以帮助大家快速了解新版本。',
name: 'wangzc',
time: '2019/05/30',
like: 35,
number:1
},]
};
},
methods: {
gotoPage(e) {
if (!e.href) {
this.open();
return
}
location.href = e.href
},
open() {
this.$message('系统维护中');
},
openVn() {
const h = this.$createElement;
this.$message({
message: h('p', null, [
h('span', null, '内容可以是 '),
h(
'i',
{
style: 'color: teal'
},
'VNode'
)
])
});
}
}
};
var Ctor = Vue.extend(Main);
new Ctor().$mount('#app');
|
eec71a69c6fdd9df5d0d7cb685988d0b04871527
|
[
"HTML",
"JavaScript"
] | 2 |
HTML
|
wzc570738205/wangzc
|
6bfedb16f88767864592b5ffcdeaa9f9f26b5151
|
2dc6922cbe02fd2879ec2c0371d211be90e0fce3
|
refs/heads/main
|
<repo_name>bsakshi831/SAKSHI-BHONGADE_EH_INTERNSHIP-STUDIO<file_sep>/README.md
# SAKSHI-BHONGADE_EH_INTERNSHIP-STUDIO
|
4730141a7f8c073b7754bc9212ee36a47f518976
|
[
"Markdown"
] | 1 |
Markdown
|
bsakshi831/SAKSHI-BHONGADE_EH_INTERNSHIP-STUDIO
|
f8139c66a5d05304b421100e253ff49fb13e8d98
|
eb724c528f49552791ad1d68673899dbf77a7f5a
|
refs/heads/master
|
<file_sep>package handler
func ValidatePage(page int32) int32 {
default_page := 1
if page > 1 {
return page
}
return int32(default_page)
}
func ValidatetCount(count int32) int32 {
default_count := 20
if count > 0 {
return count
}
return int32(default_count)
}
func GetLimitOffset(page int32, count int32, total int32) (int32, int32) {
page = ValidatePage(page)
count = ValidatetCount(count)
offset := (page - 1) * count
limit := count
return limit, offset
}<file_sep>package models
import (
"log"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"fmt"
"github.com/spf13/viper"
)
var (
driver = "mysql"
path = "root@tcp(127.0.0.1:3306)/scores?charset=utf8&parseTime=True"
)
func GetDB() (*gorm.DB, error) {
db, err := gorm.Open(viper.GetString("database_driver"), viper.GetString("database_datasource"))
if err != nil {
fmt.Println(err)
log.Fatal(err)
return nil, err
}
db.LogMode(true)
Migrate(db)
return db, nil
}<file_sep>package store
import "io"
// Store interface to save scores
type Store interface {
Save(name string, reader io.Reader, contentType string) (string, error)
}
// New create store
func New() (Store, error) {
return newMinioStore()
}
<file_sep>package: code.xxxxxx.com/micro/scores-srv
import:
- package: code.xxxxxx.com/micro/common
- package: github.com/golang/protobuf
repo: https://github.com/micro/protobuf.git
subpackages:
- proto
- package: github.com/micro/go-log
- package: github.com/micro/go-micro
version: ~0.1.1
subpackages:
- client
- server
- package: github.com/micro/go-plugins
version: ~0.1.1
subpackages:
- broker/kafka
- broker/rabbitmq
- broker/redis
- registry/etcdv3
- transport/grpc
- transport/rabbitmq
- package: github.com/tidwall/gjson
- package: golang.org/x/net
repo: https://github.com/golang/net.git
subpackages:
- context
- package: golang.org/x/sys
repo: https://github.com/golang/sys.git
- package: golang.org/x/text
repo: https://github.com/golang/text.git
- package: github.com/hashicorp/go-uuid
- package: github.com/boombuler/barcode
- package: github.com/minio/minio-go
version: ~2.1.0
- package: github.com/jinzhu/gorm
version: ^1.0.0
- package: github.com/spf13/viper
- package: github.com/go-sql-driver/mysql
version: ^1.3.0
- package: gopkg.in/gormigrate.v1
version: ^1.1.2
- package: gopkg.in/gormigrate.v1
version: ^1.2.0
<file_sep>FROM alpine:3.4
ADD scores-srv /scores-srv
ENTRYPOINT [ "/scores-srv" ]
<file_sep>package models
import (
"time"
)
const (
defaultTimeLayout = "Mon Jan 02 15:04:05 -0700 2006"
)
func StringToTime(str string) *time.Time {
t, err := time.Parse(defaultTimeLayout, str)
if err != nil {
return nil
}
utc := t.UTC()
return &utc
}
func TimeToString(t time.Time) string {
return t.Format(defaultTimeLayout)
}<file_sep>package handler
import (
proto "code.xxxxxx.com/micro/proto/scores"
)
func CheckExchangeRequest(req *proto.ExchangeRequest) (string, bool) {
var ( msg string; ok bool )
msg, ok = CheckUserId(req.GetUserId()); if !ok { return msg, false }
msg, ok = CheckScore(req.GetScore()); if !ok { return msg, false }
msg, ok = CheckGiftId(req.GetGiftId()); if !ok { return msg, false }
msg, ok = CheckGiftName(req.GetGiftName()); if !ok { return msg, false }
return "", true
}
func CheckStatRequest(req *proto.StatRequest) (string, bool) {
msg, ok := CheckUserId(req.GetUserId()); if !ok { return msg, false }
return "", true
}
func CheckListRequest(req *proto.ListRequest) (string, bool) {
var ( msg string; ok bool )
msg, ok = CheckPage(req.GetPage()); if !ok { return msg, false }
msg, ok = CheckCount(req.GetCount()); if !ok { return msg, false }
return "", true
}
func CheckCreateRequest(req *proto.CreateRequest) (string, bool) {
var ( msg string; ok bool )
msg, ok = CheckUserId(req.GetUserId()); if !ok { return msg, false }
msg, ok = CheckScore(req.GetScore()); if !ok { return msg, false }
msg, ok = CheckNote(req.GetNote()); if !ok { return msg, false }
return "", true
}
func CheckUserId(user_id int64) (string, bool) {
if user_id == 0 {
msg := "'user_id' is required"
return msg, false
}
return "", true
}
func CheckScore(score int32) (string, bool) {
if score == 0 {
msg := "'score' is required"
return msg, false
}
return "", true
}
func CheckNote(note string) (string, bool) {
if note == "" {
msg := "'note' is required"
return msg, false
}
return "", true
}
func CheckPage(page int32) (string, bool) {
if page <= 0 {
msg := "'page' must more than zero"
return msg, false
}
return "", true
}
func CheckCount(count int32) (string, bool) {
if count <= 0 {
msg := "'count' must more than zero"
return msg, false
}
return "", true
}
func CheckGiftId(gift_id int64) (string, bool) {
if gift_id == 0 {
msg := "'gift_id' is required"
return msg, false
}
return "", true
}
func CheckGiftName(gift_name string) (string, bool) {
if gift_name == "" {
msg := "'gift_name' is required"
return msg, false
}
return "", true
}
<file_sep>package main
import (
// registry
_ "github.com/micro/go-plugins/registry/etcdv3"
// transport
_ "github.com/micro/go-plugins/transport/grpc"
_ "github.com/micro/go-plugins/transport/rabbitmq"
// broker
_ "github.com/micro/go-plugins/broker/kafka"
_ "github.com/micro/go-plugins/broker/rabbitmq"
_ "github.com/micro/go-plugins/broker/redis"
)
<file_sep>package store
import (
"fmt"
"io"
"time"
minio "github.com/minio/minio-go"
)
// MinioStore for save scores
type MinioStore struct {
bucketName string
client *minio.Client
}
func (store *MinioStore) initMonio() (*minio.Client, error) {
endpoint := "s3.meimor.com"
accessKeyID := "<KEY>"
secretAccessKey := "<KEY>"
useSSL := false
// Initialize minio client object.
minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
if err != nil {
return nil, err
}
bucketName := store.bucketName
location := "us-east-1"
exists, err := minioClient.BucketExists(bucketName)
if err == nil && !exists {
err = minioClient.MakeBucket(bucketName, location)
if err != nil {
return nil, err
}
}
return minioClient, nil
}
// Save save
func (store *MinioStore) Save(name string, reader io.Reader, contentType string) (string, error) {
now := time.Now()
objectName := fmt.Sprintf("%s/%s", now.Format("2006/01/02"), name)
_, err := store.client.PutObject(store.bucketName, objectName, reader, contentType)
if err != nil {
return "", err
}
return fmt.Sprintf("http://s3.meimor.com/%s/%s", store.bucketName, objectName), nil
}
func newMinioStore() (*MinioStore, error) {
store := &MinioStore{bucketName: "scores"}
client, err := store.initMonio()
if err != nil {
return nil, err
}
store.client = client
return store, nil
}
<file_sep>package handler
import (
"golang.org/x/net/context"
"github.com/jinzhu/gorm"
proto "code.xxxxxx.com/micro/proto/scores"
m "code.xxxxxx.com/micro/scores-srv/models"
"code.xxxxxx.com/micro/scores-srv/store"
)
const (
success = "SUCCESS"
fail = "FAIL"
)
// Handler the Scores Handler
type Handler struct {
store store.Store
DB *gorm.DB
}
func (h *Handler) Create(ctx context.Context, req *proto.CreateRequest, rsp *proto.ScoreResponse) error {
msg, ok := CheckCreateRequest(req); if !ok {
rsp.Code = fail
rsp.Msg = msg
return nil
}
change_faild := m.CreateOrUpdateScore(h.DB, req.GetScore(), req.GetUserId()); if change_faild {
rsp.Code = fail
rsp.Msg = "user score deficiency"
} else {
record := m.ScoresRecord{
UserId: req.GetUserId(),
Score: req.GetScore(),
Note: req.GetNote(),
}
h.DB.Create(&record)
rsp.UserId = record.UserId
rsp.Score = record.Score
rsp.Note = record.Note
rsp.CreatedAt = m.TimeToString(record.CreatedAt)
rsp.Code = success
}
return nil
}
func (h *Handler) List(ctx context.Context, req *proto.ListRequest, rsp *proto.ListResponse) error {
var (
records []m.ScoresRecord
results []*proto.ScoreResponse
)
db, total := m.GetRecordDB(h.DB, req)
limit, offset := GetLimitOffset(req.GetPage(), req.GetCount(), total)
db = db.Offset(offset).Limit(limit).Order("created_at desc")
db.Find(&records)
for _, record := range records {
results = append(results, record.ToProto())
}
rsp.Results, rsp.Total = results, total
return nil
}
func (h *Handler) Stat(ctx context.Context, req *proto.StatRequest, rsp *proto.StatResponse) error {
msg, ok := CheckStatRequest(req); if !ok {
rsp.Code = fail
rsp.Msg = msg
return nil
}
rsp.Code = success
rsp.Score = m.GetUserScore(h.DB, req.UserId)
return nil
}
func (h *Handler) Exchange(ctx context.Context, req *proto.ExchangeRequest, rsp *proto.ExchangeResponse) error {
msg, ok := CheckExchangeRequest(req); if !ok {
rsp.Code = fail
rsp.Msg = msg
return nil
}
score := req.GetScore()
if score > 0 {
score = -score
}
change_faild := m.CreateOrUpdateScore(h.DB, score, req.GetUserId()); if change_faild {
rsp.Code = fail
rsp.Msg = "user score deficiency"
} else {
note := "积分兑换"
record := m.ScoresRecord{
UserId: req.GetUserId(),
Score: score,
Note: note,
GiftId: req.GetGiftId(),
GiftName: req.GetGiftName(),
}
h.DB.Create(&record)
rsp.UserId = record.UserId
rsp.Score = record.Score
rsp.Note = record.Note
rsp.GiftId = record.GiftId
rsp.GiftName = record.GiftName
rsp.CreatedAt = m.TimeToString(record.CreatedAt)
rsp.Code = success
}
return nil
}
// New create handler
func New(s store.Store, db *gorm.DB) *Handler {
return &Handler{
store: s,
DB: db,
}
}
<file_sep>package main
import (
proto "code.xxxxxx.com/micro/proto/scores"
"code.xxxxxx.com/micro/scores-srv/handler"
"github.com/micro/go-log"
"code.xxxxxx.com/micro/common"
"code.xxxxxx.com/micro/scores-srv/store"
"code.xxxxxx.com/micro/scores-srv/models"
"github.com/spf13/viper"
"github.com/kardianos/osext"
)
func readConfig() {
path, _ := osext.ExecutableFolder()
viper.AddConfigPath("/etc/scores")
viper.AddConfigPath(path)
viper.AutomaticEnv()
viper.SetConfigName("config")
viper.SetDefault("addr", ":8080")
viper.SetDefault("database_driver", "mysql")
viper.SetDefault("database_datasource", "root@tcp(127.0.0.1:3306)/scores?charset=utf8&parseTime=True")
viper.ReadInConfig()
}
func main() {
readConfig()
service := common.NewService("latest", "scores", common.NilInit)
store, err := store.New()
if err != nil {
log.Fatal(err)
}
db, err := models.GetDB()
if err != nil {
log.Fatal(err)
}
defer db.Close()
proto.RegisterScoreHandler(service.Server(), handler.New(store, db))
// Run service
if err := service.Run(); err != nil {
log.Fatal(err)
}
}
<file_sep>all: build
.PHONY: gen
gen:
protoc --go_out=plugins=micro:. proto/scores/*.proto
.PHONY: build
build:
CGO_ENABLED=0 go build -a -installsuffix cgo -ldflags '-w' -i -o scores-srv ./main.go ./plugins.go
.PHONY: docker-build
docker-build:
CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags '-w' -i -o scores-srv ./main.go ./plugins.go
.PHONY: docker-docker
docker: docker-build
docker build --no-cache -t micro/scores-srv .<file_sep>package models
import (
"log"
"github.com/jinzhu/gorm"
gormigrate "gopkg.in/gormigrate.v1"
)
var migrations = []*gormigrate.Migration{
// you migrations here
{
ID: "create_score",
Migrate: func(tx *gorm.DB) error {
return tx.AutoMigrate(&Scores{}).Error
},
Rollback: func(tx *gorm.DB) error {
return tx.DropTable(&Scores{}).Error
},
},
{
ID: "create_score_record",
Migrate: func(tx *gorm.DB) error {
return tx.AutoMigrate(&ScoresRecord{}).Error
},
Rollback: func(tx *gorm.DB) error {
return tx.DropTable(&ScoresRecord{}).Error
},
},
}
// Migrate do migrate for service
func Migrate(db *gorm.DB) {
options := gormigrate.DefaultOptions
options.IDColumnSize = 128
m := gormigrate.New(db, options, migrations)
err := m.Migrate()
if err == nil {
log.Printf("Migration did run successfully")
} else {
log.Printf("Could not migrate: %v", err)
}
}<file_sep>package models
import (
"math"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
proto "code.xxxxxx.com/micro/proto/scores"
)
type Scores struct {
gorm.Model
UserId int64 `gorm:"unique_index"`
Score int64 `gorm:"default:0"`
}
func GetUserScore (db *gorm.DB, user_id int64) int64 {
score := Scores{UserId: user_id, Score: 0}
db.Where(score).FirstOrInit(&score)
return score.Score
}
type ScoresRecord struct {
gorm.Model
UserId int64
Score int32
Note string
GiftId int64
GiftName string
}
func CreateOrUpdateScore(db *gorm.DB, rscore int32, user_id int64) (change_faild bool) {
tx := db.Begin()
score := Scores{UserId: user_id}
tx.Set("gorm:query_option", "FOR UPDATE").Where(score).First(&score)
if rscore < 0 {
rscore = int32(math.Abs(float64(rscore)))
expr := gorm.Expr("score - ?", rscore)
tx.Model(&score).Where("score > ?", rscore).UpdateColumn("score", expr)
} else {
tx.Model(&score).UpdateColumn("score", gorm.Expr("score + ?", rscore))
}
tx.Commit()
score_after := Scores{UserId: user_id}
db.Where(score_after).FirstOrCreate(&score_after)
return score.Score == score_after.Score
}
func (record *ScoresRecord) AfterSave(db *gorm.DB) (err error) {
// CreateOrUpdateScore(db, record.Score, record.UserId)
return nil
}
func (record *ScoresRecord) AfterUpdate(db *gorm.DB) (err error) {
// CreateOrUpdateScore(db, record.Score, record.UserId)
return nil
}
func (record *ScoresRecord) ToProto() *proto.ScoreResponse {
return &proto.ScoreResponse{
UserId: record.UserId,
Score: record.Score,
Note: record.Note,
GiftId: record.GiftId,
GiftName: record.GiftName,
CreatedAt: TimeToString(record.CreatedAt),
}
}
func GetRecordDB (db *gorm.DB, req *proto.ListRequest) (*gorm.DB, int32) {
var total int32
db = db.Model(&ScoresRecord{})
db = GetRecordUserDB(db, req.GetUserId())
db = GetRecordTimeDB(db, req.GetStart(), req.GetEnd())
db = GetRecordScoreDB(db, req.GetScoreStart(), req.GetScoreEnd())
db.Count(&total)
return db, total
}
func GetRecordUserDB (db *gorm.DB, user_id int64) *gorm.DB {
if user_id != 0 {
db = db.Where(&ScoresRecord{UserId: user_id})
}
return db
}
func GetRecordTimeDB (db *gorm.DB, start string, end string) *gorm.DB {
if start != "" {
start := StringToTime(start)
if start != nil {
db = db.Where("created_at >= ?", start)
}
}
if end != "" {
end := StringToTime(end)
if end != nil {
db = db.Where("created_at < ?", end)
}
}
return db
}
func GetRecordScoreDB (db *gorm.DB, start int64, end int64) *gorm.DB {
if start > 0 {
db = db.Where("score >= ?", start)
}
if end > 0 {
db = db.Where("score < ?", end)
}
return db
}
<file_sep>package handler
import (
"bytes"
"image/png"
"strings"
"github.com/boombuler/barcode"
"github.com/boombuler/barcode/qr"
"code.xxxxxx.com/micro/scores-srv/store"
)
func encode(content string, level qr.ErrorCorrectionLevel, size int) ([]byte, error) {
code, err := qr.Encode(content, level, qr.Unicode)
if err != nil {
return nil, err
}
code, err = barcode.Scale(code, size, size)
if err != nil {
return nil, err
}
var b bytes.Buffer
err = png.Encode(&b, code)
if err != nil {
return nil, err
}
return b.Bytes(), nil
}
func generate(name, context string, size int, store store.Store) (string, error) {
png, err := encode(context, qr.M, size)
if err != nil {
return "", err
}
if !strings.HasSuffix(name, ".ping") {
name = name + ".png"
}
url, err := store.Save(name, bytes.NewReader(png), "image/png")
if err != nil {
return "", err
}
return url, nil
}
|
f0b2e8f4b81b4b431e2b9d98f335a4b2375d020f
|
[
"Makefile",
"Dockerfile",
"YAML",
"Go"
] | 15 |
Makefile
|
kilinger/micro-score-srv
|
96a498836550d0f276a263e1fbfcd7e55296c164
|
6391cd42186edf6ac48b341dc8ad8c75e73e6ffe
|
refs/heads/main
|
<repo_name>BingQuanChua/algorithm-design<file_sep>/algo-design-2/program3.cpp
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
#include <cmath>
using namespace std;
struct Planet // Struct for storing planet info
{
string name;
int x;
int y;
int z;
int weight;
int profit;
};
struct KruskalPlanet //Struct to store edge of the planet
{
int planet1;
int planet2;
};
class PlanetMap //Class to store the planet map
{
public:
PlanetMap(int node);
void addEdge(int planetOne, int planetTwo, double weight);
KruskalPlanet* kruskal();
private:
int *parent;
int node;
typedef pair<int, int> planetName;
vector< pair<double, planetName> > edgePair;
int findPlanet (int planet);
void mergeSet(int set1, int set2);
};
PlanetMap:: PlanetMap(int node)
{
this->node = node;
parent = new int[node+1];
for (int i = 0; i <= node; i++)
{
parent[i] = i;
}
}
void PlanetMap::addEdge(int planetOne, int planetTwo, double weight) //Add planet edge into a vector
{
edgePair.push_back({weight, {planetOne, planetTwo}});
}
KruskalPlanet* PlanetMap::kruskal() //Function to perform kruskal's algorithm
{
sort(edgePair.begin(), edgePair.end());
static KruskalPlanet kp[10];
int i = 0;
vector< pair<double, planetName> >::iterator a;
for (a=edgePair.begin(); a!=edgePair.end(); a++)
{
double eWeight = a->first;
int pOne = a->second.first;
int pTwo = a->second.second;
int set_pOne = findPlanet(pOne);
int set_pTwo = findPlanet(pTwo);
if (set_pOne != set_pTwo)
{
kp[i].planet1 = pOne;
kp[i].planet2 = pTwo;
cout << char(65+pOne) << " - " << char(65+pTwo) << "\t Weight = " << eWeight <<endl;
mergeSet(set_pOne, set_pTwo);
i++;
}
}
return kp;
}
int PlanetMap::findPlanet(int planet) //Find the parent of the planet
{
if (planet != parent[planet])
parent[planet] = findPlanet(parent[planet]);
return parent[planet];
}
void PlanetMap::mergeSet(int set1, int set2) //Merge two set into one set
{
parent[set1] = parent[set2];
}
double getWeight(Planet one, Planet two) //Calculate the weight of the edges
{
double weight;
weight = sqrt(pow((two.x - one.x),2) + pow((two.y - one.y),2) + pow((two.z - one.z),2));
return weight;
}
void initmap(char g[7][13]) //Initialize the graph map
{
for (int i=0; i<7; i++)
{
for (int j=0; j<13; j++)
{
g[i][j] = ' ';
}
}
g[0][6] = 'A';
g[4][0] = 'B';
g[4][12] = 'C';
g[2][0] = 'D';
g[6][6] = 'E';
g[2][12] = 'F';
g[4][3] = 'G';
g[2][9] = 'H';
g[4][9] = 'I';
g[2][3] = 'J';
}
void displayGraph(char g[7][13]) //Display the graph
{
cout << endl;
for (int i=0; i<7; i++)
{
cout << " ";
for (int j=0; j<13; j++)
cout << g[i][j];
cout << endl;
}
}
void connect(char g[7][13], int a, int b) //Connect the edges of the graph
{
switch (a) {
case 0: // A
if (b == 3) // connect to D
{
g[0][0] = '+';
g[0][1] = '-';
g[0][2] = '-';
g[0][3] = '+';
g[0][4] = '-';
g[0][5] = '-';
g[1][0] = '|';
}
if (b == 5) // connect to F
{
g[0][12] = '+';
g[0][11] = '-';
g[0][10] = '-';
g[0][9] = '+';
g[0][8] = '-';
g[0][7] = '-';
g[1][12] = '|';
}
if (b == 9) // connect to J
{
g[0][3] = '+';
g[0][4] = '-';
g[0][5] = '-';
g[1][3] = '|';
}
if (b == 7) // connect to H
{
g[0][9] = '+';
g[0][8] = '-';
g[0][7] = '-';
g[1][9] = '|';
}
break;
case 1: // B
if (b == 3) // connect to B
{
g[3][0] = '|';
}
if (b == 4) // connect to E
{
g[6][0] = '+';
g[6][1] = '-';
g[6][2] = '-';
g[6][3] = '+';
g[6][4] = '-';
g[6][5] = '-';
g[5][0] = '|';
}
if (b == 6) // connect to G
{
g[4][1] = '-';
g[4][2] = '-';
}
break;
case 2: // C
if (b == 4) // connect to E
{
g[6][12] = '+';
g[6][11] = '-';
g[6][10] = '-';
g[6][9] = '+';
g[6][8] = '-';
g[6][7] = '-';
g[5][12] = '|';
}
if (b == 5) // connect to F
{
g[3][12] = '|';
}
if (b == 8) // connect to C
{
g[4][10] = '-';
g[4][11] = '-';
}
break;
case 3: // D
if (b == 9) // connect to J
{
g[2][1] = '-';
g[2][2] = '-';
}
break;
case 5: // F
if (b == 7) // connect to H
{
g[2][10] = '-';
g[2][11] = '-';
}
break;
case 6: // G
if (b == 4) // connect to E
{
g[6][3] = '+';
g[6][4] = '-';
g[6][5] = '-';
g[5][3] = '|';
}
if (b == 8) // connect to I
{
g[4][4] = '-';
g[4][5] = '-';
g[4][6] = '-';
g[4][7] = '-';
g[4][8] = '-';
}
break;
case 7: // H
if (b == 8) // connect to I
{
g[3][9] = '|';
}
if (b == 9) // connect to H
{
g[2][4] = '-';
g[2][5] = '-';
g[2][6] = '-';
g[2][7] = '-';
g[2][8] = '-';
}
break;
case 8: //I
if (b == 4) // connect to E
{
g[6][9] = '+';
g[6][8] = '-';
g[6][7] = '-';
g[5][9] = '|';
}
break;
case 9: // J
if (b == 6) // connect to G
{
g[3][3] = '|';
}
}
}
int main()
{
const int planetNum = 10;
Planet planetList[planetNum];
string tempName;
int tempX, tempY, tempZ, tempWeight, tempProfit, edge, tempP1, tempP2;
KruskalPlanet *kp;
KruskalPlanet ep[100];
fstream planetFile;
fstream edgeFile;
PlanetMap map(10);
char graph[7][13];
char graphAfter[7][13];
initmap(graph);
initmap(graphAfter);
planetFile.open("generated-data/A2planets.txt", ios::in);
edgeFile.open("generated-data/planet-edges.txt", ios::in);
if(planetFile) //Load data from the file into an array of Planet class
{
for(int i=0; i<planetNum; i++)
{
Planet temp;
planetFile >> tempName;
temp.name = tempName;
planetFile >> tempX;
temp.x = tempX;
planetFile >> tempY;
temp.y = tempY;
planetFile >> tempZ;
temp.z = tempZ;
planetFile >> tempWeight;
temp.weight = tempWeight;
planetFile >> tempProfit;
temp.profit = tempProfit;
planetList[i] = temp;
}
planetFile.close();
}
else
{
cout << "File not found" << endl;
}
if(edgeFile) //Load data from the file into an array of Planet class
{
edgeFile >> edge;
for(int i=0; i<edge; i++)
{
KruskalPlanet tempEdge;
edgeFile >> tempP1;
tempEdge.planet1 = tempP1;
edgeFile >> tempP2;
tempEdge.planet2 = tempP2;
ep[i] = tempEdge;
}
edgeFile.close();
}
else
{
cout << "File not found" << endl;
}
for(int i=0; i<edge; i++)
{
map.addEdge(ep[i].planet1, ep[i].planet2, getWeight(planetList[ep[i].planet1], planetList[ep[i].planet2]));
connect(graph, ep[i].planet1, ep[i].planet2);
cout << char(65+ep[i].planet1) << " - " << char(65+ep[i].planet2) << "\t Weight = " << getWeight(planetList[ep[i].planet1], planetList[ep[i].planet2]) <<endl;
}
cout << "\n\nThe graph of the planet location: ";
displayGraph(graph);
cout << "\n\n------------------------------------------------------------------" << endl;
cout << "After applying Kruskal Algorithm" << endl;
cout << "Edges of Minimum Spanning Tree are: " << endl;;
kp = map.kruskal();
for(int i=0; i<sizeof(kp)+1;i++)
{
connect(graphAfter, kp[i].planet1, kp[i].planet2);
}
cout << "\n\nGraph of the Minimum Spanning Tree: ";
displayGraph(graphAfter);
return 0;
}
<file_sep>/algo-design-1/node.cpp
#include <iostream>
#include <string>
using namespace std;
struct node {
string d;
struct node *left;
struct node *right;
// deallocate memory to prevent memory leak
~node() {
delete left;
delete right;
}
};<file_sep>/algo-design-2/program1.cpp
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cmath>
#include <math.h>
#include "planet.cpp"
#include "edge.cpp"
#include "linkedlist.cpp"
using namespace std;
const int N = 10;
char characters[] = "ABCDEFGHIJ";
LinkedList<Planet> readPlanetDetails(Planet *planets, LinkedList<Planet> planetValues);
LinkedList<Edge> readPlanetEdges(Planet *planets, LinkedList<Edge> planetEdges, double adjMatrix[][N], LinkedList<Planet> *adjList);
void addEdge(double adjMatrix[][N], int a, int b, double value);
void printAdjacencyMatrix(double adjMatrix[][N]);
void printAdjacencyList(LinkedList<Planet> *adjList);
void writeDistance(double adjMatrix[][N]);
int main() {
Planet planets[N]; // array of planets
LinkedList<Planet> planetValues; // list of planet values
LinkedList<Edge> planetEdges; // list of planet distances
double adjMatrix[N][N] = {0}; // adjacency matrix of planets
LinkedList<Planet> adjList[N]; // adjacency list of planets
// read planet details from file
planetValues = readPlanetDetails(planets, planetValues);
// read planet edges from file
planetEdges = readPlanetEdges(planets, planetEdges, adjMatrix, adjList);
// print adjacency matrix
printAdjacencyMatrix(adjMatrix);
// print adjacency list
printAdjacencyList(adjList);
// write planet distances to a text file
writeDistance(adjMatrix);
// list of planet distances
cout << endl << "List of Planet Distances: " << endl;
cout << planetEdges << endl;
// does merge sort on edge
// ascending order of distance
planetEdges.startMergeSort(0);
cout << endl << "List of Planet Distances sorted ascendingly: " << endl;
cout << planetEdges << endl << endl;
// list of planet values
cout << endl << "List of Planet Values: " << endl;
cout << planetValues << endl;
// does merge sort on value
// descending order of value
planetValues.startMergeSort(1);
cout << endl << "List of Planet Values sorted descendingly: " << endl;
cout << planetValues << endl << endl << endl;
return 0;
}
// read planet details from the generated planet data
LinkedList<Planet> readPlanetDetails(Planet *planets, LinkedList<Planet> planetValues) {
string name;
int x, y, z, weight, profit;
int c = 0;
double value = 0;
ifstream file("generated-data/A2planets.txt");
if(file) {
cout << "\nPlanet details:" << endl << endl;
cout << " Planet\t\t Coordinates\tWeight\tProfit\t Value" << endl;
while(file >> name >> x >> y >> z >> weight >> profit){
Planet p;
p.name = name;
p.planetCharacter = name.at(7);
p.x = x;
p.y = y;
p.z = z;
p.weight = weight;
p.profit = profit;
cout << name << "\t(" << x << "," << y << "," << z << ") \t" << setw(4) << weight << " \t" << setw(4) << profit;
if(weight != 0) {
// not planet A, it does not have weight
// insert to planet values
value = p.calculateValue();
planetValues.insert(p, value);
}
// stores each planet into the array
planets[c] = p;
c++;
cout << "\t" << setw(7) << value << endl;
}
file.close();
cout << endl << endl;
}
else {
cout << "\n<ERROR>\nFile A2planets.txt not found.\nPlease check /generated-data directory\n\n" << endl;
exit(0);
}
return planetValues;
}
// read planet details from the planet edges data
LinkedList<Edge> readPlanetEdges(Planet *planets, LinkedList<Edge> planetEdges, double adjMatrix[][N], LinkedList<Planet> *adjList) {
int numOfEdges;
int p1, p2;
ifstream file("generated-data/planet-edges.txt");
if (file) {
cout << "Planet edges:" << endl << endl;
file >> numOfEdges;
for (int i = 0; i < numOfEdges; i++) {
file >> p1 >> p2;
// create new edge
Edge e;
e.p1 = planets[p1];
e.p2 = planets[p2];
double distance = e.calculateDistance();
cout << e.p1 << e.p2 << ": " << distance << endl;
// insert edge into edges linkedlist
planetEdges.insert(e, distance);
// insert into adjacency matrix
addEdge(adjMatrix, p1, p2, distance);
// insert into adjacency list
adjList[p1].insert(planets[p2], distance);
adjList[p2].insert(planets[p1], distance);
}
cout << endl << endl;
}
else {
cout << "\n<ERROR>\nFile planet-edges.txt not found.\nPlease check /generated-data directory\n\n" << endl;
exit(0);
}
return planetEdges;
}
// (for adjacency matrix) adds a new edge in the map
void addEdge(double adjMatrix[][N], int a, int b, double value) {
adjMatrix[a][b] = value;
adjMatrix[b][a] = value;
}
// print adjacency matrix
void printAdjacencyMatrix(double adjMatrix[][N]) {
cout << "Adjacency Matrix of the Planets:" << endl << endl;
cout << " ";
for (int i = 0; i < 10; i++) {
cout << " " << setw(9) << characters[i];
}
cout << endl;
for (int j = 0; j < 10; j++) {
cout << characters[j] << " ";
for (int i = 0; i < 10; i++) {
cout << setw(9) << adjMatrix[j][i] << " ";
}
cout << endl;
}
cout << endl << endl;
}
// print adjacency list
void printAdjacencyList(LinkedList<Planet> *adjList) {
cout << "Adjacency List of the Planets:" << endl << endl;
for (int i = 0; i < 10; i++) {
cout << characters[i] << "- ";
cout << adjList[i] << endl;
}
cout << endl << endl;
}
// generate planet distance to a text file
void writeDistance(double adjMatrix[][N]) {
ofstream file;
file.open("generated-data/planet-distances.txt");
for (int j = 0; j < 10; j++) {
for (int i = 0; i < 10; i++) {
file << adjMatrix[j][i] << " ";
}
file << endl;
}
file << endl;
file.close();
}
<file_sep>/algo-design-2/edge.cpp
#include <iostream>
#include <string>
using namespace std;
struct Edge
{
Planet p1;
Planet p2;
double distance; // distance in this case
double calculateDistance() {
distance = sqrt(pow((p1.x - p2.x),2)
+ pow((p1.y - p2.y),2)
+ pow((p1.z - p2.z),2));
return distance;
}
};
// print the edge ("XX") when it is called
ostream &operator<< (ostream &os, const Edge &e) {
string edge = "";
edge += e.p1.planetCharacter;
edge += e.p2.planetCharacter;
os << edge;
return os;
}<file_sep>/algo-design-1/emailgenerator.cpp
// Simple email address generator
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <algorithm>
#include <fstream>
#include <chrono>
using namespace std;
static char all[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
void generateEmail(string filename, int num);
string charGenerator(int l);
string alphaGenerator(int l);
string domainGenerator();
bool duplicateValidate(string &str, vector<string> &vect);
int main() {
srand(time(NULL));
bool exit = false;
int choice = 0;
do{
cout << "****************" << endl;
cout << "Data Generation" << endl;
cout << "****************" << endl;
cout << "Please select one of the datasets below to generate:\n1.Dataset A(100 items)\n2.Dataset B(100,000 items)\n3.Dataset C(500,000 items)\n4.Exit" << endl;
cout << "Enter your choice: ";
// Prompt user to enter their choice
cin >> choice;
cout << endl;
switch (choice)
{
case 1:
//Dataset A
generateEmail("Data Set A", 100);
break;
case 2:
//Dataset B
generateEmail("Data Set B", 100000);
break;
case 3:
//Dataset C
generateEmail("Data Set C", 500000);
break;
case 4:
exit = true;
break;
default:
cout<<"Error! Invalid input...Please enter choice from 1 - 4"<<endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
break;
}
cout << endl;
} while ( !exit );
return 0;
}
// generates email data, also generates a .txt file for reference
void generateEmail(string filename, int num) {
ofstream file;
file.open(filename + ".txt");
// declare a string vector
vector<string> vect;
// email format: [A-Za-z0-9]{4}\.[A-Za-z0-9]{5}@[A-Za-z]{4}\.(com|my|org)
string email;
int count = 1;
auto start = chrono::system_clock::now();
// Generate specified number of email addresses
while(count <= num){
email = "";
email += charGenerator(4);
email += ".";
email += charGenerator(5);
email += "@";
email += alphaGenerator(4);
email += ".";
email += domainGenerator();
// if no duplicate string is found, add string to the vector
if (duplicateValidate(email,vect)){
if(count != 1) {
file << endl;
}
vect.push_back(email);
file << email;
count++;
}
else{
continue; // data not recorded
}
}
auto end = chrono::system_clock::now();
chrono::duration<double> duration = end - start;
for(int i = 0; i < vect.size();i++){
cout << vect[i] << endl;
}
cout << "\nDuration for generating " + filename + " " << duration.count() << "s" << endl;
// close file
file.close();
}
string charGenerator(int l) {
string ans;
for (int i = 0; i < l; i++) {
ans += all[rand()%62];
}
return ans;
}
string alphaGenerator(int l) {
string ans;
for (int i = 0; i < l; i++) {
ans += all[rand()%52];
}
return ans;
}
string domainGenerator() {
string domain[] = {"com", "my", "org"};
return domain[rand()%3];
}
bool duplicateValidate(string &str, vector<string> &vect){
// return false if duplicate string is found
if(find(vect.begin(), vect.end(), str) != vect.end())
return false;
else
return true;
}
<file_sep>/algo-design-2/planet.cpp
#include <iostream>
#include <string>
using namespace std;
struct Planet
{
string name; // planet full name: "Planet_X"
char planetCharacter; // planet character: "X"
int x; // x coordinate
int y; // y coordinate
int z; // z coordinate
int weight;
int profit;
double value = 0; // value calculated from profit/weight
double calculateValue()
{
value = 1.0*profit/weight;
return value;
}
};
// print the planet character ("X") when it is called
ostream &operator<< (ostream &os, const Planet &p) {
os << p.planetCharacter;
return os;
}<file_sep>/README.md
# Algorithm-Design
Algorithm Design and Analysis Assignment
## Assignment 1
In Assignment 1, we generated a few sets of emails and stored them into different data structures. We recorded the time taken for storing and searching the emails in each data structures. _algo-design-1_ consists of 5 different programs:
1. Email Generator
2. Hash Table with Chaining
3. Hash Table with Linear Probing
4. AVL Binary Search Tree
5. Priority Queue and Heap
## Assignment 2
In Assignment 2, we are required to analyze planet data according to this map:

algo-design-2 consists of 4 different programs:
1. Planet Data Generator
2. Planet Edges and Value with Merge-Sort
3. Dijakstra's Algorithm to find Shortest Paths
4. Kruskal's Algorithm to find the Minimum Spanning Tree
<file_sep>/algo-design-2/linkedlist.cpp
#ifndef LINKEDLIST_CPP
#define LINKEDLIST_CPP
#include <iostream>
#include <iomanip>
using namespace std;
template <typename T>
struct Node
{
T info; // info
double value; // value, the value to be sorted and displayed
Node<T> *next;
};
template <typename T>
class LinkedList
{
Node<T> *start;
public:
LinkedList()
{
start = NULL;
}
void insert(T &element, double &value)
{
Node<T> *newNode = new Node<T>;
newNode->info = element;
newNode->value = value;
newNode->next = start;
start = newNode;
}
void splitLinkedList(Node<T> *head, Node<T> **a, Node<T> **b) {
Node<T> *front;
Node<T> *back;
back = head;
front = head->next;
while (front != NULL) {
front = front->next;
if (front != NULL) {
back = back->next;
front = front->next;
}
}
*a = head;
*b = back->next;
back->next = NULL;
}
Node<T> * merge(Node<T> *a, Node<T> *b, int order) {
Node<T> *result = NULL;
if (a == NULL) {
return b;
}
else {
if (b == NULL) {
return a;
}
}
if (order == 0) {
if (a->value <= b->value) {
result = a;
result->next = merge(a->next, b, order);
}
else {
result = b;
result->next = merge(a, b->next, order);
}
}
else {
if (a->value <= b->value) {
result = b;
result->next = merge(a, b->next, order);
}
else {
result = a;
result->next = merge(a->next, b, order);
}
}
return result;
}
void startMergeSort(int order=0) {
// order: 0 => ascending
// order: 1 => descending
mergeSort(&start, order);
}
void mergeSort(Node<T> **start, int order) {
Node<T> *head = *start;
Node<T> *a; // first half
Node<T> *b; // second half
if((head == NULL) || (head->next == NULL)) {
return;
}
splitLinkedList(head, &a, &b);
mergeSort(&a, order);
mergeSort(&b, order);
*start = merge(a, b, order);
}
bool find(T target)
{
bool found = false;
Node<T> *ptr = start;
while(ptr != NULL && !found)
{
if(ptr->info == target)
{
found = true;
}
else
{
ptr = ptr->next;
}
}
return found;
}
bool isEmpty()
{
if(start == NULL)
return false;
else
return true;
}
// print single linked list when called
friend ostream &operator<< (ostream &os, LinkedList<T> &list)
{
Node<T> *ptr = list.start;
while(ptr != NULL)
{
os << ptr->info << ": " << setw(7) << ptr->value << " ";
ptr = ptr->next;
if (ptr != NULL) {
os << "-> ";
}
}
return os;
}
};
#endif<file_sep>/algo-design-1/avl_tree.cpp
#include <iostream>
#include <chrono>
#include <fstream>
#include "avl.cpp"
#include <vector>
#include <algorithm>
using namespace std;
bst insertEmailToTree(string &filename, bst tree);
void searchEmailAddresses(string &filename, bst tree);
int main() {
int choice;
bool quit = false;
do {
bst avl_tree;
string filename;
cout << "****************************************************************" << endl;
cout << " AVL Binary Search Tree " << endl;
cout << "****************************************************************" << endl;
cout << "Please select one of the datasets below to be insert into a BST:" << endl;
cout << "1.Dataset A(100 items)" << endl;
cout << "2.Dataset B(100,000 items)" << endl;
cout << "3.Dataset C(500,000 items)" << endl;
cout << "4.Quit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch(choice) {
case 1: filename = "Data Set A";
break;
case 2: filename = "Data Set B";
break;
case 3: filename = "Data Set C";
break;
default: quit = true;
break;
}
if(!quit) { // if not exiting
avl_tree = insertEmailToTree(filename, avl_tree);
int action;
bool exit = false;
string search;
do {
cout << endl << "****************************************************************" << endl;
cout << "Please select one of the actions below to be done to the new AVL Tree:" << endl;
cout << "1.Search 10 emails that can be found" << endl;
cout << "2.Search 10 emails that cannot be found" << endl;
cout << "3.Show AVL Tree" << endl;
cout << "4.Exit" << endl;
cout << "Enter your choice: ";
cin >> action;
cout << endl;
switch(action) {
case 1: search = filename + "(Found)";
searchEmailAddresses(search, avl_tree);
break;
case 2: search = filename + "(Cannot Found)";
searchEmailAddresses(search, avl_tree);
break;
case 3: avl_tree.show(avl_tree.root, 1);
break;
default: exit = true;
break;
}
cout << endl;
}while (!exit);
}
}while(!quit);
cout << "****************************************************************" << endl;
return 0;
}
bst insertEmailToTree(string &filename, bst tree) {
string email;
ifstream file("datasets/" + filename + ".txt");
//
vector<string> vec;
while(getline(file, email)) {
vec.push_back(email);
}
sort(vec.begin(), vec.end());
int size = vec.size();
auto start = chrono::system_clock::now();
tree.root = tree.insert(tree.root, vec.at(size/2));
tree.root = tree.insert(tree.root, vec.at(size/2-1));
for(int i = 0; i < size/2-1; i++) {
tree.root = tree.insert(tree.root, vec.at(i));
tree.root = tree.insert(tree.root, vec.at(size-1-i));
}
auto end = chrono::system_clock::now();
chrono::duration<double> duration = end - start;
cout << endl << "Duration for inserting " + filename + ": " << duration.count() << "s" << endl;
file.close();
return tree;
}
void searchEmailAddresses(string &filename, bst tree) {
string email;
ifstream file("Search Datasets/" + filename + ".txt");
auto start = chrono::system_clock::now();
while(getline(file, email)) {
if(tree.searchItem(tree.root, email)) {
cout << email << "\tcan be found!" << endl;
}
else {
cout << email << "\tcannot be found" << endl;
}
}
auto end = chrono::system_clock::now();
chrono::duration<double> duration = end - start;
cout << endl << "Duration for searching emails in " + filename + ": " << duration.count() << "s" << endl;
}
<file_sep>/algo-design-1/priorityqueue&heap.cpp
#include <iostream>
#include <vector>
#include <fstream>
#include <chrono>
using namespace std;
template <typename T>
class PriorityQueue {
vector<T> arr;
//return the index of parent
int parentIndex(int index){
return (index-1)/2;
}
// return the index of left child
int leftChildIndex(int index){
return (2*index) + 1;
}
// return the index of right child
int rightChildIndex(int index){
return (2*index) + 2;
}
public:
void enqueue(T element){
arr.push_back(element);
heap_Enqueue(arr.size()-1);
}
T dequeue(){
T dequeued_element = arr[0];
arr[0] = arr[arr.size()-1];
arr.pop_back();
heap_Dequeue(0);
return dequeued_element;
}
void heap_Enqueue(int index){
int parent_index = parentIndex(index);
if (index > 0 && arr[parent_index] < arr[index]){
swap(arr[index],arr[parent_index]);
heap_Enqueue(parent_index);
}
}
void heap_Dequeue(int index){
int leftChild_index = leftChildIndex(index);
int rightChild_index = rightChildIndex(index);
int maxIndex;
//if left and right nodes are not empty
if (rightChild_index < arr.size()){
if(arr[leftChild_index] > arr[rightChild_index]){
maxIndex = leftChild_index;
}
else{
maxIndex = rightChild_index;
}
if(arr[index] > arr[maxIndex]){
maxIndex = index;
}
}
//if left node not empty
else if(leftChild_index < arr.size()){
if (arr[leftChild_index] > arr[index]){
maxIndex = leftChild_index;
}
else{
maxIndex = index;
}
}
else{
maxIndex = index;
}
if (maxIndex != index) {
swap (arr[index], arr[maxIndex]);
heap_Dequeue(maxIndex);
}
}
void show() {
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
cout << endl;
}
};
bool getEmail(string fileName, vector<string> &vect)
{
// open the file
ifstream inFile(fileName.c_str());
// Check if object is valid
if(!inFile)
{
cout << "Unable to open the File : " << fileName << endl;
return false;
}
string email="";
// Read the next line from file until it reaches the end
while (getline(inFile, email))
{
// email contains string of length > 0 then save it in vector
if(email.size() > 0)
vect.push_back(email);
}
//close the file
inFile.close();
return true;
}
void priorityQueue(vector<string> &vect,bool show){
int n = vect.size();
int partOfData = vect.size()*0.10;
PriorityQueue<string> pq;
// Print the vector contents
if(show == true){
cout << "Below are the email addresses in this dataset:" << endl;
for (int i = 0; i < n; i++){
cout<<vect[i]<<endl;
}
}
//take the start time to insert all data into the priority queue
auto start_Enqueue = chrono::system_clock::now();
if(show == true){
cout << "\nEnqueue\t\t\t: PriorityQueue\n";
for (int i = 0; i < n; i++) {
cout << vect[i] << "\t: ";
pq.enqueue (vect[i]);
pq.show();
cout << endl;
}
}
else{
for (int i = 0; i < n; i++)
pq.enqueue (vect[i]);
}
//take the end time to insert all data into the priority queue
auto end_Enqueue = chrono::system_clock::now();
//take the start time to dequeue 10% of the data
auto start_Dequeue = chrono::system_clock::now();
if(show == true){
cout << "\nDequeue\t\t\t: PriorityQueue\n";
for (int i = 0; i < partOfData; i++) {
cout << pq.dequeue() << "\t: ";
pq.show();
cout << endl;
}
}
else{
for (int i = 0; i < partOfData; i++)
pq.dequeue();
}
//take the end time to dequeue 10% of the data
auto end_Dequeue = chrono::system_clock::now();
//Calculate the duration
chrono::duration<double> duration_Enqueue = end_Enqueue - start_Enqueue;
chrono::duration<double> duration_Dequeue = end_Dequeue - start_Dequeue;
cout << "Duration to insert all data into the priority queue: " << duration_Enqueue.count() << "s" << endl;
cout << "Duration to dequeue 10% of the data: " << duration_Dequeue.count() << "s\n" << endl;
}
int main()
{
vector<string> vectA;
vector<string> vectB;
vector<string> vectC;
int choice = 0;
int choice_display = 0;
bool show = false;
bool exit = false;
bool result_1 = getEmail("Datasets/Data Set A.txt", vectA);
bool result_2 = getEmail("Datasets/Data Set B.txt", vectB);
bool result_3 = getEmail("Datasets/Data Set C.txt", vectC);
do{
cout << "***************************************" << endl;
cout << "Priority Queue and Heap Implementation" << endl;
cout << "***************************************" << endl;
cout << "Please select one of the datasets below:\n1.Data Set A(100 items)\n2.Data Set B(100,000 items)\n3.Data Set C(500,000 items)\n4.Exit" << endl;
cout << "Enter your choice: ";
// Prompt user to enter their choice
cin >> choice;
cout << endl;
switch (choice)
{
case 1:
if(result_1){
//Dataset A
do{
cout << "Do you want to show the output?\n1.Yes\n2.No\nEnter your choice: ";
cin >> choice_display;
if(choice_display == 1){
show = true;
priorityQueue(vectA,show);
}
else if (choice_display == 2){
show = false;
priorityQueue(vectA,show);
}
else{
cout << "Error! Invalid input...Please enter choice 1 or 2\n\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}while(choice_display < 1 || choice_display > 2);
break;
}
case 2:
if(result_2){
//Dataset B
show = false;
priorityQueue(vectB,show);
break;
}
case 3:
if(result_3){
//Dataset C
show = false;
priorityQueue(vectC,show);
break;
}
case 4:
exit = true;
break;
default:
cout<<"Error! Invalid input...Please enter choice from 1 - 4"<<endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
break;
}
cout << endl;
} while ( !exit );
return 0;
}
<file_sep>/algo-design-1/avl.cpp
#include <iostream>
#include <string>
#include "node.cpp"
using namespace std;
class bst {
public:
struct node *root;
node * insert(node *n, string &s) {
if (n == NULL) {
n = new node();
n->d = s;
n->left = NULL;
n->right = NULL;
}
else {
if (s.compare(n->d) < 0) {
n->left = insert(n->left, s);
n = balance(n);
}
else {
n->right = insert(n->right, s);
n = balance(n);
}
}
return n;
}
node * getSuccessor(node *n) {
if (n->right == NULL) {
return n;
}
else {
return getSuccessor(n->right);
}
}
bool searchItem(node *n, string &s) const {
if (n == NULL) {
return false; // not found
}
else {
if (s.compare(n->d) == 0) {
return true;
}
else {
if (s.compare(n->d) < 0){
return searchItem(n->left, s);
}
else {
return searchItem(n->right, s);
}
}
}
}
int getNodeHeight(node *n) {
if (n == NULL) {
return 0;
}
else {
int left_h = getNodeHeight(n->left);
int right_h = getNodeHeight(n->right);
return max(left_h, right_h) + 1;
}
}
int getBalanceFactor(node *n) {
int left_h = getNodeHeight(n->left);
int right_h = getNodeHeight(n->right);
return right_h - left_h;
}
node * balance(node *n) {
int bF = getBalanceFactor(n);
if (bF < -1) {
if (getBalanceFactor(n->left) < 0) {
n = rightRotate(n);
}
else {
n = leftRightRotate(n);
}
}
else {
if (bF > 1) {
if (getBalanceFactor(n->right) < 0) {
n = rightLeftRotate(n);
}
else {
n = leftRotate(n);
}
}
}
return n;
}
node * leftRotate(node *n) {
node *temp = n->right;
n->right = temp->left;
temp->left = n;
return temp;
}
node * rightRotate(node *n) {
node *temp = n->left;
n->left = temp->right;
temp->right = n;
return temp;
}
node * leftRightRotate(node *n) {
node *temp = n->left;
n->left = leftRotate(temp);
return rightRotate(n);
}
node * rightLeftRotate(node *n) {
node *temp = n->right;
n->right = rightRotate(temp);
return leftRotate(n);
}
void show(node *n, int lvl)
{
int i;
if (n != NULL)
{
if (n == root)
cout << "Root: " << n->d << endl;
else
{
cout << n->d << endl;
}
cout << lvl << "L: ";
show(n->left, lvl + 1);
cout << "\n" << lvl << "R: ";
show(n->right, lvl + 1);
}
}
bst() {
root = NULL;
}
};
<file_sep>/algo-design-2/program2_dijkstra_algorithm.cpp
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cmath>
#include <climits>
#include <math.h>
#include <climits>
using namespace std;
const int NUM_VERTEX = 10; // declare the number of vertex
const int GRAPH_COL = 13;
void getDistance(double matrix[][NUM_VERTEX]); // read planet distances from the text file
void readPlanetEdges(double matrix[][NUM_VERTEX],char graphBefore[][GRAPH_COL]); // read planet edges from the text file
void addEdge(double matrix[][NUM_VERTEX],int a, int b, double value); // (for adjacency matrix) adds a new edge in the map
void printAdjacencyMatrix(double matrix[][NUM_VERTEX]); // display the adjacency matrix
void printShortestDistance(double distance[]); // print the constructed distance array
void minDistance(double distance[],bool sptSet[]); // find the vertex with minimum distance value
void dijkstra(double matrix[][NUM_VERTEX],char graphAfter[][GRAPH_COL],int source); //function that implements Dijkstra's algorithm by using adjacency matrix representation
void initmap(char graph[][GRAPH_COL]);
void displayGraph(char graph[][GRAPH_COL]);
void connect(char graph[][GRAPH_COL], int a, int b);
int main() {
char graphBefore[7][13];
char graphAfter[7][13];
double matrix[10][10]; // adjacency matrix of planets
cout << "**********************************Before applying Dijkstra Algorithm**********************************" << endl;
initmap(graphBefore);
initmap(graphAfter);
readPlanetEdges(matrix,graphBefore);
getDistance(matrix);
cout << "The graph of the planet location:";
displayGraph(graphBefore);
printAdjacencyMatrix(matrix);
cout << "**********************************After applying Dijkstra Algorithm**********************************" << endl;
dijkstra(matrix,graphAfter,0);
cout << "The graph representing the shortest paths: " << endl;
displayGraph(graphAfter);
return 0;
}
// read planet distances from the text file
void getDistance(double matrix[][NUM_VERTEX]) {
string details;
ifstream file("generated-data/planet-distances.txt");
if(file){
for (int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++){
// read in the value of distance into the matrices
file >> matrix[i][j];
}
}
file.close();
}
else{
cout << "Unable to open the file." << endl;
}
}
//Initialize the graph map
void initmap(char graph[][GRAPH_COL]){
for (int i=0; i<7; i++)
{
for (int j=0; j<13; j++)
{
graph[i][j] = ' ';
}
}
graph[0][6] = 'A';
graph[4][0] = 'B';
graph[4][12] = 'C';
graph[2][0] = 'D';
graph[6][6] = 'E';
graph[2][12] = 'F';
graph[4][3] = 'G';
graph[2][9] = 'H';
graph[4][9] = 'I';
graph[2][3] = 'J';
}
//Read planet edges from the text file
void readPlanetEdges(double matrix[][NUM_VERTEX],char graphBefore[][GRAPH_COL]) {
int numOfEdges;
int p1, p2;
ifstream file("generated-data/planet-edges.txt");
file >> numOfEdges;
if(file){
for (int i = 0; i < numOfEdges; i++) {
file >> p1 >> p2;
// initialize the map
addEdge(matrix, p1, p2, 1);
// initial graph before finding the shortest path
connect(graphBefore,p1,p2);
}
file.close();
}
else{
cout << "Unable to open the file." << endl;
}
}
// (for adjacency matrix) adds a new edge in the map
void addEdge(double matrix[][NUM_VERTEX],int a, int b, double value) {
matrix[a][b] = value;
matrix[b][a] = value;
}
// print adjacency matrix
void printAdjacencyMatrix(double matrix[][NUM_VERTEX]) {
char characters[] = "ABCDEFGHIJ";
cout << "Adjacency Matrix(distances as weights of the edges):" << endl;
cout << " ";
for (int i = 0; i < 10; i++) {
cout << " " << setw(9) << characters[i];
}
cout << endl;
for (int j = 0; j < 10; j++) {
cout << characters[j] << " ";
for (int i = 0; i < 10; i++) {
cout << setw(9) << matrix[j][i] << " ";
}
cout << endl;
}
cout << endl;
}
//Connect the edges of the graph
void connect(char graph[][GRAPH_COL], int a, int b){
switch (a) {
case 0: // A
if (b == 3) // connect to D
{
graph[0][0] = '+';
graph[0][1] = '-';
graph[0][2] = '-';
graph[0][3] = '+';
graph[0][4] = '-';
graph[0][5] = '-';
graph[1][0] = '|';
}
if (b == 5) // connect to F
{
graph[0][12] = '+';
graph[0][11] = '-';
graph[0][10] = '-';
graph[0][9] = '+';
graph[0][8] = '-';
graph[0][7] = '-';
graph[1][12] = '|';
}
if (b == 9) // connect to J
{
graph[0][3] = '+';
graph[0][4] = '-';
graph[0][5] = '-';
graph[1][3] = '|';
}
if (b == 7) // connect to H
{
graph[0][9] = '+';
graph[0][8] = '-';
graph[0][7] = '-';
graph[1][9] = '|';
}
break;
case 1: // B
if (b == 3) // connect to D
{
graph[3][0] = '|';
}
if (b == 4) // connect to E
{
graph[6][0] = '+';
graph[6][1] = '-';
graph[6][2] = '-';
graph[6][3] = '+';
graph[6][4] = '-';
graph[6][5] = '-';
graph[5][0] = '|';
}
if (b == 6) // connect to G
{
graph[4][1] = '-';
graph[4][2] = '-';
}
break;
case 2: // C
if (b == 4) // connect to E
{
graph[6][12] = '+';
graph[6][11] = '-';
graph[6][10] = '-';
graph[6][9] = '+';
graph[6][8] = '-';
graph[6][7] = '-';
graph[5][12] = '|';
}
if (b == 5) // connect to F
{
graph[3][12] = '|';
}
if (b == 8) // connect to I
{
graph[4][10] = '-';
graph[4][11] = '-';
}
break;
case 3: // D
if (b == 1) // connect to B
{
graph[3][0] = '|';
}
if (b == 9) // connect to J
{
graph[2][1] = '-';
graph[2][2] = '-';
}
break;
case 4: //E
if (b == 1) // connect to B
{
graph[6][0] = '+';
graph[6][1] = '-';
graph[6][2] = '-';
graph[6][3] = '+';
graph[6][4] = '-';
graph[6][5] = '-';
graph[5][0] = '|';
}
if (b == 2) // connect to C
{
graph[6][12] = '+';
graph[6][11] = '-';
graph[6][10] = '-';
graph[6][9] = '+';
graph[6][8] = '-';
graph[6][7] = '-';
graph[5][12] = '|';
}
if (b == 6) // connect to G
{
graph[6][3] = '+';
graph[6][4] = '-';
graph[6][5] = '-';
graph[5][3] = '|';
}
if (b == 8) // connect to I
{
graph[6][9] = '+';
graph[6][8] = '-';
graph[6][7] = '-';
graph[5][9] = '|';
}
break;
case 5: // F
if (b == 2) // connect to C
{
graph[3][12] = '|';
}
if (b == 7) // connect to H
{
graph[2][10] = '-';
graph[2][11] = '-';
}
break;
case 6: // G
if (b == 1) // connect to B
{
graph[4][1] = '-';
graph[4][2] = '-';
}
if (b == 4) // connect to E
{
graph[6][3] = '+';
graph[6][4] = '-';
graph[6][5] = '-';
graph[5][3] = '|';
}
if (b == 8) // connect to I
{
graph[4][4] = '-';
graph[4][5] = '-';
graph[4][6] = '-';
graph[4][7] = '-';
graph[4][8] = '-';
}
if (b == 9) // connect to J
{
graph[3][3] = '|';
}
break;
case 7: // H
if (b == 5) // connect to F
{
graph[2][10] = '-';
graph[2][11] = '-';
}
if (b == 8) // connect to I
{
graph[3][9] = '|';
}
if (b == 9) // connect to J
{
graph[2][4] = '-';
graph[2][5] = '-';
graph[2][6] = '-';
graph[2][7] = '-';
graph[2][8] = '-';
}
break;
case 8: //I
if (b == 2) // connect to C
{
graph[4][10] = '-';
graph[4][11] = '-';
}
if (b == 4) // connect to E
{
graph[6][9] = '+';
graph[6][8] = '-';
graph[6][7] = '-';
graph[5][9] = '|';
}
if (b == 6) // connect to G
{
graph[4][4] = '-';
graph[4][5] = '-';
graph[4][6] = '-';
graph[4][7] = '-';
graph[4][8] = '-';
}
if (b == 7) // connect to H
{
graph[3][9] = '|';
}
break;
case 9: // J
if (b == 3) // connect to D
{
graph[2][1] = '-';
graph[2][2] = '-';
}
if (b == 6) // connect to G
{
graph[3][3] = '|';
}
if (b == 7) // connect to H
{
graph[2][4] = '-';
graph[2][5] = '-';
graph[2][6] = '-';
graph[2][7] = '-';
graph[2][8] = '-';
}
break;
}
}
// find the vertex with minimum distance value
int minimumDistance(double distance[],bool sptSet[]){
int minDistance = INT_MAX,minIndex;
for(int i = 0;i<NUM_VERTEX;i++){
if(sptSet[i]==false){
if(distance[i]<=minDistance)
{
minDistance=distance[i];
minIndex=i;
}
}
}
return minIndex;
}
// print the constructed distance array
void printShortestDistance(double distance[]){
char characters[] = "ABCDEFGHIJ";
cout << "\n\nThe shortest distance to each planet:\n";
cout<<"Planets\t\tDistance from source"<<endl;
for(int i=0;i<NUM_VERTEX;i++){
//char c=65+i;
cout<<"Planet_" <<characters[i]<<"\t"<<distance[i]<<endl;
}
cout << endl;
}
//function that implements Dijkstra's algorithm by using adjacency matrix representation
void dijkstra(double matrix[][NUM_VERTEX],char graphAfter[][GRAPH_COL],int source){
char characters[] = "ABCDEFGHIJ";
int path[NUM_VERTEX];
double distance[NUM_VERTEX];
bool sptSet[NUM_VERTEX];
for (int i = 0; i < NUM_VERTEX; i++){
// Initialize the variables
distance[i] = INT_MAX;
sptSet[i] = false;
path[i] = source;
}
//initialize the source vertex distance to zero
distance[source] = 0;
for (int i = 0; i < NUM_VERTEX; i++) {
int u = minimumDistance(distance, sptSet);
// Mark the picked vertex as visited
sptSet[u] = true;
for (int v = 0; v < NUM_VERTEX; v++){
// update the minimum distance
if (!sptSet[v] && matrix[u][v] && distance[u] != INT_MAX
&& distance[u] + matrix[u][v] < distance[v]){
distance[v] = distance[u] + matrix[u][v];
path[v] = u;
}
}
}
cout << "The shortest paths from Planet A to the other planets:";
for(int i = 0;i < NUM_VERTEX;i++){
if(i!=source) {
int j = 0;
cout<<"\nPath = "<<characters[i];
j = i;
do {
connect(graphAfter,path[j],j);
j=path[j];
cout<<"<-"<<characters[j];
}while(j!=source);
}
}
// print the constructed distance array
printShortestDistance(distance);
}
//Display the graph
void displayGraph(char graph[][GRAPH_COL]){
cout << endl;
for (int i=0; i<7; i++)
{
cout << " ";
for (int j=0; j<13; j++)
cout << graph[i][j];
cout << endl;
}
cout << endl;
}
<file_sep>/algo-design-1/hashtablelp.cpp
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <chrono>
#include "LinkedList.cpp"
template <typename T>
class HashTableLP
{
vector<LinkedList<T>> hashtable;
int hashFunction (string email)
{
int i = 0;
for(int j=0; email[j] ;j++)
i = i + int(email[j]);
return i % hashtable.size();
}
public:
HashTableLP (int size)
{
hashtable.resize (size*1.5);
}
int size()
{
return hashtable.size();
}
void insertEmail (T newEmail)
{
int index = hashFunction(newEmail);
while(hashtable[index].isEmpty())
{
index = index + 1;
}
hashtable[index].insert(newEmail);
}
void searchEmail (T newEmail)
{
int index = hashFunction(newEmail);
while(hashtable[index].find(newEmail) == false && hashtable[index].isEmpty())
{
index = index + 1;
}
if (hashtable[index].find(newEmail) == true)
cout << newEmail << " can be found in index " << index <<endl;
else
cout << newEmail << " cannot be found" <<endl;
}
friend ostream& operator<< (ostream& os, HashTableLP<T>& ht)
{
for (int i = 0; i < ht.size(); i++)
os << i << " = " << ht.hashtable[i] << endl;
return os;
}
};
int main()
{
vector<string> email;
vector<string> foundEmail;
string temp;
string temp2;
string insertEmail;
string searchEmail;
int insertChoice;
int searchChoice;
fstream fileName;
fstream foundFile;
cout << "Welcome to Hash Table (Linear Probing) Program" << endl << endl;
cout << "Please choose a dataset to insert: " << endl;
cout << "1. Data Set A - 100 items" << endl;
cout << "2. Data Set B - 100,000 items" << endl;
cout << "3. Data Set C - 500,000 items" << endl;
cout << "Please enter 1, 2 or 3 only: ";
cin >> insertChoice;
cout << endl;
while (insertChoice < 1 || insertChoice > 3)
{
cout << "Invalid number !!" << endl;
cout << "Please enter 1, 2 or 3 only: ";
cin >> insertChoice;
cout << endl;
}
cout << "Please choose a dataset to search: " << endl;
cout << "1. Data Set I (Can be found)" << endl;
cout << "2. Data Set II (Cannot be found)" << endl;
cout << "Please enter 1 or 2 only: ";
cin >> searchChoice;
cout << endl;
while (searchChoice < 1 || searchChoice > 2)
{
cout << "Invalid number !!" << endl;
cout << "Please enter 1 or 2only: ";
cin >> searchChoice;
cout << endl;
}
if(insertChoice == 1)
{
insertEmail = "datasets/Data Set A.txt";
if(searchChoice == 1)
searchEmail = "Search Datasets/Data Set A(Found).txt";
else
searchEmail = "Search Datasets/Data Set A(Cannot Found).txt";
}
else if (insertChoice == 2)
{
insertEmail = "datasets/Data Set B.txt";
if(searchChoice == 1)
searchEmail = "Search Datasets/Data Set B(Found).txt";
else
searchEmail = "Search Datasets/Data Set B(Cannot Found).txt";
}
else
{
insertEmail = "datasets/Data Set C.txt";
if(searchChoice == 1)
searchEmail = "Search Datasets/Data Set C(Found).txt";
else
searchEmail = "Search Datasets/Data Set C(Cannot Found).txt";
}
fileName.open(insertEmail, ios :: in);
if(fileName)
{
while(getline(fileName, temp))
{
email.push_back(temp);
}
HashTableLP <string> hashtable (email.size());
auto start = chrono::system_clock::now();
for(int i =0; i < email.size();i++)
{
hashtable.insertEmail(email[i]);
}
auto end = chrono::system_clock::now();
chrono::duration<double> insertDuration = end - start;
cout << endl;
if(insertChoice == 1)
{
cout << hashtable << endl;
}
cout << "Insert Duration: " << insertDuration.count() << "s\n\n";
foundFile.open(searchEmail, ios::in);
if(foundFile)
{
while(getline(foundFile, temp2))
{
foundEmail.push_back(temp2);
}
auto start = chrono::system_clock::now();
for(int i =0; i < foundEmail.size();i++)
{
hashtable.searchEmail(foundEmail[i]);
}
auto end = chrono::system_clock::now();
chrono::duration<double> searchDuration = end - start;
cout << "\nSearch Duration: " << searchDuration.count() << "s\n";
foundFile.close();
}
else
{
cout << "The file cant be read" << endl;
}
fileName.close();
}
else
{
cout << "The file cant be read" << endl;
}
return 0;
}
|
6b5009b6d84f746680d930d70a7f15129aea8fa3
|
[
"Markdown",
"C++"
] | 13 |
Markdown
|
BingQuanChua/algorithm-design
|
3a37fbfb0550f2a3eb6d1c91b984915d0f74c4d3
|
05b9528bb074953630c471a7990f65df0ce2f9a1
|
refs/heads/master
|
<repo_name>Tathagatd96/Santander-Challenge<file_sep>/santander_value_prediction_challenge.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 2 16:47:26 2018
@author: <NAME>
"""
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
santander_data=pd.read_csv("train.csv")
test_df=pd.read_csv('test.csv')
print(santander_data.keys()) #4992 features except target
#print(santander_data.head())
x_data=santander_data.drop(["target",'ID'],axis=1)
y_data=santander_data["target"]
#print(len(x_data.keys()))
#print(x_data.isnull().sum().sort_values(ascending=False))
from sklearn.decomposition import PCA
pca = PCA(n_components=1000)
x_data = pd.DataFrame(pca.fit_transform(x_data))
test_df=pd.DataFrame(pca.fit_transform(test_df))
#print(x_data.head(5))
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(x_data, y_data, train_size=0.70, random_state=1)
import sklearn.feature_selection
select = sklearn.feature_selection.SelectKBest(k=100)
selected_features = select.fit(X_train, y_train)
indices_selected = selected_features.get_support(indices=True)
colnames_selected = [x_data.columns[i] for i in indices_selected]
X_train_selected = X_train[colnames_selected]
X_test_selected = X_test[colnames_selected]
test_df_selected=test_df[colnames_selected]
from xgboost.sklearn import XGBClassifier
from sklearn.ensemble import RandomForestRegressor,GradientBoostingRegressor
regr = RandomForestRegressor(max_depth=5, random_state=0)
rfr=regr.fit(X_train_selected, y_train)
y_pred=rfr.predict(X_test_selected)
def rmsle(y, y0):
assert len(y) == len(y0)
return np.sqrt(np.mean(np.power(np.log1p(y)-np.log1p(y0), 2)))
err = rmsle(y_pred,y_test)
print('RMSLE: {:.3f}'.format(err))
y_pred=rfr.predict(test_df_selected)
df=pd.read_csv("sample_submission.csv")
submission = pd.DataFrame({
"ID": df["ID"],
"target": y_pred
})
submission.to_csv('santander1.csv', index=False)
|
c6ec7648308d0c68b4b89b0e01691082ff8e0875
|
[
"Python"
] | 1 |
Python
|
Tathagatd96/Santander-Challenge
|
2c10144847bc90207246f5f3076d243803b95c73
|
7cdb7f4db30063c1eb19b66b10c899b8901f065c
|
refs/heads/develop
|
<repo_name>GuillaumeHaben/PI-InfoAutonomie<file_sep>/README.md
# Info-Autonomie
## Requirements
* Java SE 1.8
## Usage
To run this application, type `./activator run` in your terminal.
|
16663d6045cd89c64505aad492ef8369be6d5960
|
[
"Markdown"
] | 1 |
Markdown
|
GuillaumeHaben/PI-InfoAutonomie
|
489c400bc34dcc83e0d2cd3219a847001ffc1c71
|
1e37665e5336f064be2b077e6bf026eab48df72c
|
refs/heads/master
|
<file_sep>jslicense-bsd-2-clause
======================
The Two-Clause ("Simplified") BSD License in [jslicense][jslicense] format
[jslicense]: http://jslicense.org
|
795f97f54bb85b6d2136089c48080c0e4c97552b
|
[
"Markdown"
] | 1 |
Markdown
|
jslicense/jslicense-bsd-2-clause
|
4bb81b36c86c0e7e0e026abd000fe305add420f2
|
4e1d3afb7a27b38f8ad68a3dc508a250ce9bb79a
|
refs/heads/master
|
<file_sep>require 'rails_helper'
RSpec.describe Api::V1::NotebooksController, type: :controller do
let(:notebook) { FactoryBot.create(:notebook, name: 'Tester1')}
describe "GET #index" do
before do
get :index, :format => :json
end
it "returns http success" do
expect(response).to have_http_status(:success)
end
end
describe "POST notebook#create" do
it "should create notebook " do
expect {
post :create, params: {notebook: {name: 'test'}, :format=> JSON}
}.to change(Notebook, :count).by(1)
end
end
describe "PUT 'update/:id'" do
it "allows an notebook to be updated" do
newnotebook = FactoryBot.create(:notebook, name: 'Tester2')
put :update, params: {id: newnotebook.id, :notebook => newnotebook.attributes = { :name => "new name" }}, :format => JSON
response.should be_successful
end
end
describe "DELETE notebook#destroy" do
it "should destroy notebook and return 200" do
notebook1 = FactoryBot.create(:notebook, name: 'Tester2')
expect {
delete :destroy, params: {id: notebook1.id}, :format => JSON
}.to change(Notebook, :count).by(-1)
expect(response.status).to eq 200
end
end
describe "GET notebook#external_books" do
before do
get :external_books, :format => :json
end
it "should fetch data from api" do
expect(response).to have_http_status(:success)
end
end
#notebook = Notebook.create! valid_attributes
# expect {
# delete :destroy, params: {id: notebook.to_param}, session: valid_session
# }.to change(Notebook, :count).by(-1)
# end
# describe "GET #show" do
# it "returns a success response" do
# notebook = Notebook.create! valid_attributes
# expect(response.content_type).to eq('application/json')
# expect(response).to be_successful
# end
# end
# describe "POST #create" do
# context "with valid params" do
# it "creates a new Notebook" do
# expect {
# post :create, params: {notebook: valid_attributes}, session: valid_session
# }.to change(Notebook, :count).by(1)
# end
# it "renders a JSON response with the new notebook" do
# post :create, params: {notebook: valid_attributes}, session: valid_session
# expect(response).to have_http_status(:created)
# expect(response.content_type).to eq('application/json')
# expect(response.location).to eq(notebook_url(Notebook.last))
# end
# end
# context "with invalid params" do
# it "renders a JSON response with errors for the new notebook" do
# post :create, params: {notebook: invalid_attributes}, session: valid_session
# expect(response).to have_http_status(:unprocessable_entity)
# expect(response.content_type).to eq('application/json')
# end
# end
#end
#describe "PUT #update" do
# context "with valid params" do
# let(:new_attributes) {
# skip("Add a hash of attributes valid for your model")
# }
# it "updates the requested notebook" do
# notebook = Notebook.create! valid_attributes
# put :update, params: {id: notebook.to_param, notebook: new_attributes}, session: valid_session
# notebook.reload
# skip("Add assertions for updated state")
# end
# it "renders a JSON response with the notebook" do
# notebook = Notebook.create! valid_attributes
# put :update, params: {id: notebook.to_param, notebook: valid_attributes}, session: valid_session
# expect(response).to have_http_status(:ok)
# expect(response.content_type).to eq('application/json')
# end
# end
# context "with invalid params" do
# it "renders a JSON response with errors for the notebook" do
# notebook = Notebook.create! valid_attributes
# put :update, params: {id: notebook.to_param, notebook: invalid_attributes}, session: valid_session
# expect(response).to have_http_status(:unprocessable_entity)
# expect(response.content_type).to eq('application/json')
# end
# end
#end
#describe "DELETE #destroy" do
# it "destroys the requested notebook" do
# notebook = Notebook.create! valid_attributes
# expect {
# delete :destroy, params: {id: notebook.to_param}, session: valid_session
# }.to change(Notebook, :count).by(-1)
# end
#end
end
<file_sep>module Response
def json_response(object, status = :success, status_code = 200, message = "")
render json: {status: status, status_code: status_code, message: message, data: object}
end
end
<file_sep>module ExceptionHandler
# provides the more graceful `included` method
extend ActiveSupport::Concern
included do
ActionController::Parameters.action_on_unpermitted_parameters = :raise
rescue_from ActionController::UnpermittedParameters do |e|
json_response({}, :unprocessable_entity, 422, "Unpermitted parameters received" )
end
rescue_from ActionController::ParameterMissing do |e|
json_response({} , :unprocessable_entity, 422, "Required parameter missing")
end
rescue_from ArgumentError do |e|
json_response({} , :unprocessable_entity, 422, "Invalid parameters")
end
rescue_from ActiveRecord::RecordNotFound do |e|
json_response({} , :not_found, 404, 'Record Not Found')
end
rescue_from ActiveRecord::RecordInvalid do |e|
json_response({} , :unprocessable_entity, 422, e.message)
end
end
end
<file_sep>FactoryBot.define do
factory :notebook do
end
end
<file_sep>Rails.application.routes.draw do
get 'dashboards/index'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root to: 'dashboards#index'
namespace 'api' do
namespace 'v1' do
resources :notebooks, :path => 'books'
end
end
get '/api/v1/external-books' => 'api/v1/notebooks#external_books'
post '/api/v1/books/:id/delete', to: 'api/v1/notebooks#destroy'
post '/api/v1/books/:id/update', to: 'api/v1/notebooks#update'
end
<file_sep>class Api::V1::NotebooksController < ApplicationController
before_action :set_notebook, only: [:show, :update, :destroy]
before_action :get_notebook, only: [:external_books]
before_action :filter_notebook, only: [:external_books]
# GET /notebooks
def index
@notebooks = Notebook.all
json_response(@notebooks)
end
def external_books
json_response(@notebooks)
end
# GET /notebooks/1
def show
json_response(@notebook)
end
# POST /notebooks
def create
@notebook = Notebook.new(notebook_params)
if @notebook.save!
json_response("book" => @notebook)
else
json_response({}, :unprocessable_entity, 422, 'Notebook has not created')
end
end
# PATCH/PUT /notebooks/1
def update
if @notebook.update(notebook_params)
json_response(@notebook)
else
json_response({},:unprocessable_entity, 422, 'Notebook has not updated')
end
end
# DELETE /notebooks/1
def destroy
@notebook.destroy
json_response(@notebook, :success, 204, "The Book #{@notebook.name} was deleted successfully")
end
private
# Use callbacks to share common setup or constraints between actions.
def set_notebook
@notebook = Notebook.find(params[:id])
end
def get_notebook
@notebooks = HTTParty.get("https://www.anapioficeandfire.com/api/books?name=#{params[:name]}").parsed_response
end
# Only allow a trusted parameter "white list" through.
def notebook_params
params.require(:notebook).permit(:name, :isbn, :country, :number_of_pages, :publisher, :release_date, authors: [])
end
def filter_notebook
@notebooks = @notebooks.map { |hs| hs.except("povCharacters", "mediaType", "characters") }
end
end
<file_sep>##LIBRARY
This is a Rails 5 app.
## Documentation
This README describes the purpose of this repository and how to set up a development environment. Other sources of documentation are as follows:
## Prerequisites
This project requires:
* Ruby 2.5.3, preferably managed using [rbenv]
* Rails 5.2.3
* PostgreSQL must be installed and accepting connections
## Getting started
Please follow the steps to setup:
1.) Install ruby version 2.5.1
2.) Install rails version 5.2.0
3.) Install postgresql
4.) On the project root directory:
a.) Run `bundle install`
b.) rename database.yml.example to database.yml
c.) Run `rake db:create`
d.) run `rake db:migrate`
5.) run `rails s`
### bin/setup
Run the `bin/setup` script. This script will:
* Check you have the required Ruby version
* Install gems using Bundler
* Create local copies of `.env` and `database.yml`
* Create, migrate, and seed the database
## API endpoints
1. Fetch External Books
Request-> GET /api/v1/external-books
2. To Create a Book In Development Database
Request-> POST /api/v1/books
params -> {
"notebook": {
"name": "Testname",
"isbn": "Testisbn",
"authors": ["TestAuthor1", "TestAuthor2"],
"country": "India",
"number_of_pages": 20,
"publisher": "Testpublisher"
}
}
3. READ from Database
Request-> GET /api/v1/books
4. READ a particular Record
Request-> GET /api/v1/books/:id
5. Update a Record In Database
Request-> PATCH /api/v1/books/:id
POST /api/v1/books/:id/update
params -> {
"notebook": {
"name": "Testname",
"isbn": "Testisbn",
"authors": ["TestAuthor1", "TestAuthor2"],
"country": "India",
"number_of_pages": 20,
"publisher": "Testpublisher"
}
}
6. Delete a Record
Request-> DELETE /api/v1/books/:id
POST /api/v1/books/:id/delete
<file_sep>development: &development
adapter: postgresql
encoding: unicode
host: 'localhost'
database: 'library_dev'
username:
password:
pool: 5
test: &test
<<: *development
database: 'library_test'
username:
password:
pool: 5
|
78333004ad9688db65f9c1ff68801a3dc84c6040
|
[
"Markdown",
"Ruby",
"YAML"
] | 8 |
Markdown
|
BhaveshSaluja/library
|
64da440c3507cae52f7b13325d4efcbe5cc008cd
|
b684d53075776ce01c538576ad83a765ce375a0f
|
refs/heads/master
|
<repo_name>lonecloudStudy/classwork<file_sep>/README.md
# classwork程序
# 运行步骤
1. 新建一个名字为`classwork`数据库
2. 导入`sql`文件夹下的classwork.sql文件
3. 克隆该项目
4. 导入后放在tomcat运行即可
<file_sep>/src/cn/classwork/servlet/GetUserServlet.java
package cn.classwork.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import cn.classwork.base.BaseServlet;
import cn.classwork.util.JsonMsgUtils;
/**
* 获取用户信息
* @Title: GetUserServlet.java
* @Package cn.classwork.servlet
* @version V1.0
*/
//前台请求地址为getUser
@WebServlet("/getUser")
public class GetUserServlet extends BaseServlet {//继承的是BaseServlet(按住ctrl/alt会出现渐变效果)
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object user = req.getSession().getAttribute("user");//从session中获取用户
JsonMsgUtils.jsonData(user, resp);//然后将用户数据进行封装
}
}
<file_sep>/src/cn/classwork/dto/JsonMessage.java
package cn.classwork.dto;
/**
* json数据封装
* @Title: JsonMessage.java
* @Package cn.classwork.dto
* @date 2017年7月19日 上午12:07:05
* @version V1.0
*/
public class JsonMessage {
public final static String SUCCESS="success";
public final static String ERROR="error";
public String code;
public String message;
public JsonMessage(String code, String message) {
super();
this.code = code;
this.message = message;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
<file_sep>/WebContent/js/register.js
var SUCCESS = "success";
var ERROR = "error";
$(function() {
$("#register").click(function() {
// 校验数据正确性
if (checkField("#username")) {
alert("用户名不能为空");
return;
}
if (checkField("#password")) {
alert("密码不能为空")
return
}
if ($("#rePassword").val() != $("#password").val()) {
alert("输入的两次密码不一致")
return
}
if (checkField("#email")) {
alert("请输入正确的email")
return
}
$.ajax({
url : "register",
type : "POST",
dataType : "json",
data : $("#registerForm").serialize(),
success : function(data) {
if (SUCCESS == data.code) {
alert("用户注册成功");
window.location.href = "index.html";
} else {
alert("该用户已经被注册");
}
},
error : function() {
alert("请求失败")
}
});
});
function checkUserName() {
$.ajax({
url : "checkUser",
type : "POST",
dataType : "json",
data : {
type : "username",
value : $("#username").val()
},
success : function(data) {
if (SUCCESS == data.code) {
alert("该用户可用");
} else {
alert("该用户不可用");
}
},
error : function() {
alert("请求失败")
}
});
}
function checkField(field) {
var val = $(field).val();
return val == null || val == undefined || val == "";
}
});<file_sep>/config/jdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/classwork?characterEncoding=utf8
jdbc.username=root
jdbc.password=<PASSWORD>
jdbc.class=com.mysql.jdbc.Driver<file_sep>/WebContent/js/login.js
/**
* Created by lonecloud on 2017/7/16.
*/
var SUCCESS = "success";
var ERROR = "error";
$(function() {
$("#login").click(function() {
//校验数据
if(checkField("#username")){
alert("用户名不能为空")
return
}
if(checkField("#password")){
alert("密码不能为空")
return
}
$.ajax({
url : "doLogin",
dataType : "json",
type : "POST",
data : {
username : $("#username").val(),
password : $("#<PASSWORD>").val()
},
success : function(data) {
if (SUCCESS == data.code) {
window.location.href = "index.html";
} else {
alert(data.message);
}
},
error : function() {
alert("请求失败")
}
});
})
function checkField(field) {
var val = $(field).val();
return val == null || val == undefined || val == "";
}
});<file_sep>/src/cn/classwork/servlet/UpdateUserServlet.java
package cn.classwork.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.classwork.base.BaseServlet;
import cn.classwork.entity.User;
import cn.classwork.util.JsonMsgUtils;
/**
* 更新用户的信息
* @Title: UpdateUserServlet.java
* @Package cn.classwork.servlet
* @date 2017年7月18日 下午6:47:55
* @version V1.0
*/
@WebServlet("/updateUserInfo")
public class UpdateUserServlet extends BaseServlet{
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
userService.updateUser(coverUpdateUser(request));
JsonMsgUtils.successMsg("成功更新", response);
} catch (Exception e) {
JsonMsgUtils.errorMsg("系统错误", response);
e.printStackTrace();
}
}
/**
* 整合user
*
* @Description:
* @param request
* @return
*/
private User coverUpdateUser(HttpServletRequest request) {
User user = new User();
user.setId(Integer.parseInt(request.getParameter("id")));
user.setTel(request.getParameter("tel"));
user.setNickname(request.getParameter("nickname"));
user.setSex(request.getParameter("sex"));
user.setQq(request.getParameter("qq"));
user.setAddress(request.getParameter("address"));
return user;
}
}
<file_sep>/WebContent/js/index.js
var lis = document.getElementById("tab").getElementsByTagName("li");// 获取li
var uls = document.getElementById("content").getElementsByTagName("ul");// 获取ul
var bottomLi = document.getElementById("bottomUl").getElementsByTagName("li");// 获取菜单所有li
var bottomUl = document.getElementById("bottomGame").getElementsByTagName("ul");// 获取内容ul
for (var i = 0; i < lis.length; i++) {// 循环给li添加事件
lis[i].onmouseover = function() {// 给li添加鼠标覆盖事件
var index = 0;
for (var j = 0; j < lis.length; j++) {
if (this.isEqualNode(lis[j])) {// 获取这个li是哪一个li
index = j;
}
lis[j].className = "";// 清除li 的样式
uls[j].className = "hidden";// 清除ul 的样式
}
this.className = "active";// 添加li样式
uls[index].className = "show"; // 添加ul样式
}
}
/**
* 所有游戏点击事件
*/
for (var i = 0; i < bottomLi.length; i++) {
var index = 0;
bottomLi[i].onclick = function() {
for (var j = 0; j < bottomUl.length; j++) {
if (this.isEqualNode(bottomLi[j])) {
index = j;
}
bottomLi[j].className = "";
bottomUl[j].className = "hidden";
}
this.className = "bottomMenuClick";
bottomUl[index].className = "";
}
}
/**
* 图片的js
*/
function changeImg() {
// 图片变化
index++;
if (index == 5) {
index = 1;
}
document.getElementById("img_banner").className = "login" + " img" + index;//
// li的样式发生变化
var lis = document.getElementById("indexUl").getElementsByTagName("li");
for (var i = 0; i < lis.length; i++) {
lis[i].className = "gray";
}
lis[index - 1].className = "lightblue";
}
/**
* 鼠标在div的框框的时间
*/
var intervalId = setInterval(changeImg, 2000);
function stop_play() {
//清除定时器
clearInterval(intervalId);
intervalId = null;
}
/**
* 鼠标不在div时候的时间
* @returns
*/
function play() {
if (intervalId == null) {
//设置了一个定时器
intervalId = setInterval(changeImg, 2000);//参数1调用函数,2为时间
}
}
function showImg(i) {
// 图片变化
index = i;
document.getElementById("img_banner").className = "login" + " img" + index;
// li的样式发生变化
var lis = document.getElementById("indexUl").getElementsByTagName("li");
for (var i = 0; i < lis.length; i++) {
lis[i].className = "gray";
}
lis[index - 1].className = "lightblue";
}
/**
* 登录按钮事件
*/
$("#loginBtn").click(function() {
$.ajax({
url : "doLogin",
dataType : "json",
type : "POST",
data : {
username : $("#username").val(),
password : $("#<PASSWORD>").val()
},
success : function(data) {
if (SUCCESS == data.code) {
window.location.href = "index.html";
} else {
alert(data.message);
}
},
error : function() {
alert("请求失败")
}
});
});
//首页默认判断登录信息
$(function() {
$.ajax({
url : "checkToken",
dataType : "json",
type : "GET",
data : {},
success : function(data) {
// 判断已经登录
if (ERROR != data.code) {
$("#username_href").html(data.username);
$("#showContent").removeClass("hidden");
$("#login_content").addClass("hidden");
} else {
$("#showContent").addClass("hidden");
$("#login_content").removeClass("hidden");
}
}
});
});
<file_sep>/WebContent/js/common.js
/**
* Created by lonecloud on 2017/7/17.
*/
var SUCCESS = "success";
var ERROR = "error";
//隐藏页面的注册和登录和注册按钮,以及注销按钮
//定义一个准备函数
$(function() {
//ajax请求
$.ajax({
url : "checkToken",//请求的后端地址
dataType : "json",//返回的数据类型为json
type : "GET",//请求类型GET
data : {},//请求参数
success : function(data) {//请求成功后回调的函数
// 判断已经登录
if (ERROR != data.code) {//判断返回的json 中cod值是success还是error
//成功之后隐藏登录注册按钮
$("[href='register.html']").hide();
$("[href='login.html']").hide();
} else {
//注销功能按钮隐藏
$("[href='logout']").hide();
}
}
});
});<file_sep>/src/cn/classwork/servlet/RegisterServlet.java
package cn.classwork.servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.connector.Request;
import cn.classwork.base.BaseServlet;
import cn.classwork.entity.User;
import cn.classwork.util.JsonMsgUtils;
/**
* 注册界面servlet
* @Title: RegisterServlet.java
* @Package cn.classwork.servlet
* @author lonecloud
* @date 2017年7月23日 上午11:09:36
* @version V1.0
*/
@WebServlet("/register")
public class RegisterServlet extends BaseServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");//获取参数
try {
if(username!=null&&userService.checkType("username", username)){//判断用户名是否被使用
User user = coverUser(request);//封装用户
try {
userService.saveUser(user);//保存用户给数据库
JsonMsgUtils.successMsg("注册成功", response);
} catch (Exception e) {
JsonMsgUtils.errorMsg("系统错误", response);
e.printStackTrace();
}
}else{
JsonMsgUtils.errorMsg("用户名不能为空", response);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 整合user
*
* @Description:
* @param request
* @return
*/
private User coverUser(HttpServletRequest request) {
User user = new User();
user.setEmail(request.getParameter("email"));
user.setUsername(request.getParameter("username"));
user.setPassword(request.getParameter("<PASSWORD>"));
user.setIdcard(request.getParameter("idcard"));
user.setFullname(request.getParameter("fullname"));
user.setRegisterIp(request.getRemoteAddr());
user.setRegistertime(new Date());
user.setLogintime(new Date());
return user;
}
}
<file_sep>/sql/classwork.sql
/*
Navicat MySQL Data Transfer
Source Server : mysql
Source Server Version : 50633
Source Host : localhost
Source Database : classwork
Target Server Version : 50633
File Encoding : utf-8
Date: 07/19/2017 00:00:02 AM
*/
SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for `tbl_user`
-- ----------------------------
DROP TABLE IF EXISTS `tbl_user`;
CREATE TABLE `tbl_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(40) NOT NULL,
`password` varchar(40) NOT NULL,
`email` varchar(40) DEFAULT NULL,
`fullname` varchar(40) DEFAULT NULL,
`idcard` varchar(40) DEFAULT NULL,
`registertime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`logintime` timestamp NULL DEFAULT '0000-00-00 00:00:00',
`registerIp` varchar(40) DEFAULT NULL,
`tel` varchar(20) DEFAULT NULL,
`nickname` varchar(40) DEFAULT NULL,
`sex` varchar(2) DEFAULT NULL,
`qq` varchar(10) DEFAULT NULL,
`address` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;
SET FOREIGN_KEY_CHECKS = 1;
<file_sep>/src/cn/classwork/util/ServletUtils.java
package cn.classwork.util;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* servlet操作类
* @Title: ServletUtils.java
* @Package cn.classwork.util
* @version V1.0
*/
public class ServletUtils {
private static final String PREFIX = "/WEB-INF/pages";
/**
* 请求转发
*
* @param request
* @param response
* @param url
* @throws ServletException
* @throws IOException
*/
public static void forwardUrl(HttpServletRequest request, HttpServletResponse response, String url)
throws ServletException, IOException {
System.out.println(url);
String urlx = PREFIX + url;
request.getRequestDispatcher(urlx).forward(request, response);
}
}
<file_sep>/src/cn/classwork/servlet/ChangePwdServlet.java
package cn.classwork.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.classwork.base.BaseServlet;
import cn.classwork.entity.User;
import cn.classwork.util.JsonMsgUtils;
/**
* 修改密码
* @Title: ChangePwdServlet.java
* @Package cn.classwork.servlet
* @author lonecloud
* @date 2017年7月18日 下午9:27:09
* @version V1.0
*/
@WebServlet("/changePwd")
public class ChangePwdServlet extends BaseServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String oldPwd=req.getParameter("oldPwd");
String repasswd=req.getParameter("repasswd");
String confirm=req.getParameter("confirm");
Object obj = req.getSession().getAttribute("user");
if (obj!=null) {
User user=(User)obj;
if (!user.getPassword().equals(oldPwd)) {
JsonMsgUtils.errorMsg("原密码错误", resp);
}else{
if (oldPwd!=null&&repasswd!=null&&repasswd.equals(confirm)) {
userService.updatePwd(user.getId(),repasswd);
JsonMsgUtils.successMsg("密码修改成功", resp);
}
}
}
}
}
<file_sep>/src/cn/classwork/util/StringUtils.java
package cn.classwork.util;
/**
* String 工具类
* @Title: StringUtils.java
* @Package cn.classwork.util
* @version V1.0
*/
public class StringUtils {
/**
* 判断字符串是不是空或者空字符串
* @Description:
* @param str
* @return
*/
public static boolean isNullOrBlank(String str){
return str==null||str.trim().equals("");
}
public static boolean isNotNullAndBlank(String str){
return !isNullOrBlank(str);
}
/**
* 判断是不是所有字符串为空
* @Description:
* @param strings
* @return
*/
public static boolean isAllNotNull(String... strings){
for (String string : strings) {
if(isNullOrBlank(string)){
return false;
}
}
return true;
}
}
<file_sep>/src/cn/classwork/entity/User.java
package cn.classwork.entity;
import java.io.Serializable;
import java.util.Date;
/**
* 用户类
* @Title: User.java
* @Package cn.classwork.entity
* @version V1.0
*/
public class User implements Serializable{
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", nickname=" + nickname + ", password=" + <PASSWORD>
+ ", email=" + email + ", fullname=" + fullname + ", idcard=" + idcard + ", registertime="
+ registertime + ", logintime=" + logintime + ", registerIp=" + registerIp + ", sex=" + sex
+", address=" + address + ", qq=" + qq + ", tel=" + tel + "]";
}
/**
*
*/
private static final long serialVersionUID = -2890698071035784694L;
private int id;//id
private String username;//用户名字
private String nickname;//用户名字
private String password;//<PASSWORD>
private String email;//电子邮件
private String fullname;
private String idcard;
private Date registertime;
private Date logintime;
private String registerIp;
private String sex;//性别
private String address;//地址
private String qq;//QQ
private String tel;//电话
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getIdcard() {
return idcard;
}
public void setIdcard(String idcard) {
this.idcard = idcard;
}
public Date getRegistertime() {
return registertime;
}
public void setRegistertime(Date registertime) {
this.registertime = registertime;
}
public Date getLogintime() {
return logintime;
}
public void setLogintime(Date logintime) {
this.logintime = logintime;
}
public String getRegisterIp() {
return registerIp;
}
public void setRegisterIp(String registerIp) {
this.registerIp = registerIp;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getPassword() {
return <PASSWORD>;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
}
<file_sep>/src/cn/classwork/util/JsonMsgUtils.java
package cn.classwork.util;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import cn.classwork.dto.JsonMessage;
/**
* json操作工具类
* @Title: JsonMsgUtils.java
* @Package cn.classwork.util
* @version V1.0
*/
public class JsonMsgUtils {
/**
* 返回成功消息
* @Description:
* @param msg
* @param response
* @return
* @throws IOException
*/
public static void successMsg(String msg,HttpServletResponse response) throws IOException{
response.setContentType("text/json");
response.getWriter().print(JSON.toJSONString(new JsonMessage(JsonMessage.SUCCESS,msg)));
}
/**
* 返回失败的消息
*
* @Description:
* @param msg
* @param response
* @return
* @throws IOException
*/
public static void errorMsg(String msg,HttpServletResponse response) throws IOException {
response.setContentType("text/json");
response.getWriter().print(JSON.toJSONString(new JsonMessage(JsonMessage.ERROR,msg)));
}
public static void jsonData(Object object,HttpServletResponse response) throws IOException{
response.setContentType("text/json");
response.getWriter().print(JSON.toJSONString(object,SerializerFeature.WriteDateUseDateFormat));
}
}
|
0deaeb67f62c74bb95d9c2a2c23ccd32d4327904
|
[
"INI",
"Java",
"Markdown",
"SQL",
"JavaScript"
] | 16 |
INI
|
lonecloudStudy/classwork
|
2859bc32815607d17003ca15e9797a1642759e90
|
240290cde43ffc5f3cf0c886732eafaaf8ca827d
|
refs/heads/master
|
<repo_name>test1MC/lingo01<file_sep>/Target/Content/Togglers.htm
<?xml version="1.0" encoding="utf-8"?>
<html xmlns:MadCap="http://www.madcapsoftware.com/Schemas/MadCap.xsd" MadCap:lastBlockDepth="2" MadCap:lastHeight="920" MadCap:lastWidth="1389" xml:space="preserve">
<head> <link href="Resources/Stylesheets/NewStylesheet.css" rel="stylesheet" type="text/css" /></head>
<body>
<h1>
<MadCap:concept term="javacontrols" />
<MadCap:keyword term="javacontrols" />Togglers</h1>
<p>
<MadCap:toggler targets="normal">Toggler!</MadCap:toggler>
</p>
<p MadCap:targetName="normal">Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</p>
<h2>MadCap|Toggler style uses a style class - .test - red/Courier New</h2>
<p>
<MadCap:toggler targets="dif1" class="test">Toggler!</MadCap:toggler>
</p>
<p MadCap:targetName="dif1">Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</p>
<p>
<MadCap:toggler targets="dif2" class="right">Toggler Right!</MadCap:toggler>
</p>
<p MadCap:targetName="dif2">Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</p>
<p MadCap:conditions="Default.bugged,Default.None">
<MadCap:toggler targets="dif3" class="none">Toggler None!</MadCap:toggler>
</p>
<p MadCap:targetName="dif3" MadCap:conditions="Default.bugged,Default.None">Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</p>
<p>
<MadCap:toggler targets="dif4" class="small_left">Toggler Small Left!</MadCap:toggler>
</p>
<p MadCap:targetName="dif4">Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</p>
<p>
<MadCap:toggler targets="dif5" class="small_right">Toggler Small Right!</MadCap:toggler>
</p>
<p MadCap:targetName="dif5">Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</p>
<p>
<MadCap:toggler targets="dif6" class="large_left">Toggler large Left!</MadCap:toggler>
</p>
<p MadCap:targetName="dif6">Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</p>
<p>
<MadCap:toggler targets="dif7" class="large_right">Toggler large Right!</MadCap:toggler>
</p>
<p MadCap:targetName="dif7">Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</p>
<h2>MadCap|Toggler style uses a style class - .test25- orange/Courier New with mc-image-spacing = 25px</h2>
<p>
<MadCap:toggler targets="dif8" class="test25">Toggler!</MadCap:toggler>
</p>
<p MadCap:targetName="dif8">Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</p>
<p> </p>
</body>
</html><file_sep>/Target/Content/MoreTopic2.htm
<?xml version="1.0" encoding="utf-8"?>
<html xmlns:MadCap="http://www.madcapsoftware.com/Schemas/MadCap.xsd" MadCap:lastBlockDepth="4" MadCap:lastHeight="883" MadCap:lastWidth="1205" MadCap:onlyLocalStylesheets="True" xml:space="preserve">
<head>
<link href="Resources/Stylesheets/more.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Topic Title</h1>
<h2>The following are using icons that are <span style="color: #b22222;">smaller than default (8px width)</span>- and <span style="color: #b22222;">mc-image-spacing is set to 2px</span></h2>
<p>
<MadCap:toggler targets="small5px" class="small_5pxspace">Toggler! <MadCap:glossaryTerm glossTerm="Glossary.Term1">GlossaryTerm2</MadCap:glossaryTerm></MadCap:toggler>
</p>
<p MadCap:targetName="small5px">Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</p>
<MadCap:dropDown class="small_5pxspace">
<MadCap:dropDownHead>
<MadCap:dropDownHotspot>Dropdown <MadCap:glossaryTerm glossTerm="Glossary.Term1">GlossaryTerm2</MadCap:glossaryTerm></MadCap:dropDownHotspot>
</MadCap:dropDownHead>
<MadCap:dropDownBody>
<p>Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</p>
</MadCap:dropDownBody>
</MadCap:dropDown>
<p>
<MadCap:expanding class="small_5pxspace">
<MadCap:expandingHead>Expanding Text. <MadCap:glossaryTerm glossTerm="Glossary.Term1">GlossaryTerm2</MadCap:glossaryTerm></MadCap:expandingHead>
<MadCap:expandingBody> Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</MadCap:expandingBody>
</MadCap:expanding>
</p>
<p>
<MadCap:expanding class="small_5pxspaceleft">
<MadCap:expandingHead>Expanding Text. <MadCap:glossaryTerm glossTerm="Glossary.Term1">GlossaryTerm2</MadCap:glossaryTerm></MadCap:expandingHead>
<MadCap:expandingBody> Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</MadCap:expandingBody>
</MadCap:expanding>
</p>
<p> </p>
<h2>The following are using icons that are <span style="color: #b22222;">smaller than default (8px width)</span>- and using default mc-image-spacing</h2>
<p>
<MadCap:toggler targets="small" class="small_default">
<MadCap:glossaryTerm glossTerm="Glossary.Term1">GlossaryTerm2</MadCap:glossaryTerm> Toggler!</MadCap:toggler>
</p>
<p MadCap:targetName="small">Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</p>
<MadCap:dropDown class="small_default">
<MadCap:dropDownHead>
<MadCap:dropDownHotspot>
<a href="Topic.htm#This_Is_A_Bookmark">This_Is_A_Bookmark</a> Dropdown</MadCap:dropDownHotspot>
</MadCap:dropDownHead>
<MadCap:dropDownBody>
<p>Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</p>
</MadCap:dropDownBody>
</MadCap:dropDown>
<p>
<MadCap:expanding class="small_default">
<MadCap:expandingHead>
<a href="Topic.htm#This_Is_A_Bookmark">This_Is_A_Bookmark</a> Expanding Text.</MadCap:expandingHead>
<MadCap:expandingBody> Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</MadCap:expandingBody>
</MadCap:expanding>
</p>
<p>
<MadCap:expanding class="small_defaultleft">
<MadCap:expandingHead> <MadCap:glossaryTerm glossTerm="Glossary.Term1">GlossaryTerm2</MadCap:glossaryTerm> Expanding Text.</MadCap:expandingHead>
<MadCap:expandingBody> Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</MadCap:expandingBody>
</MadCap:expanding>
</p>
<p> </p>
<h2>The following are using icons that are <span style="color: #b22222;">larger than default</span> - and <span style="color: #b22222;">mc-image-spacing is set to 25px</span></h2>
<p>
<MadCap:toggler targets="Name" class="test">Toggler! <a href="Topic.htm#This_Is_A_Bookmark">This_Is_A_Bookmark</a></MadCap:toggler>
</p>
<p MadCap:targetName="Name">Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</p>
<MadCap:dropDown class="test">
<MadCap:dropDownHead>
<MadCap:dropDownHotspot>Dropdown <a href="Topic.htm#This_Is_A_Bookmark">This_Is_A_Bookmark</a></MadCap:dropDownHotspot>
</MadCap:dropDownHead>
<MadCap:dropDownBody>
<p>Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</p>
</MadCap:dropDownBody>
</MadCap:dropDown>
<p>
<MadCap:expanding class="test">
<MadCap:expandingHead>Expanding Text. <a href="Topic.htm#This_Is_A_Bookmark">This_Is_A_Bookmark</a></MadCap:expandingHead>
<MadCap:expandingBody> Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</MadCap:expandingBody>
</MadCap:expanding>
</p>
<p>
<MadCap:expanding class="testleft">
<MadCap:expandingHead>Expanding Text. <a href="Topic.htm#This_Is_A_Bookmark">This_Is_A_Bookmark</a></MadCap:expandingHead>
<MadCap:expandingBody> Start. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. Delete this text and replace it with your own content. End.</MadCap:expandingBody>
</MadCap:expanding>
</p>
</body>
</html><file_sep>/Target/Content/GlossaryTopics/Green.htm
<?xml version="1.0" encoding="utf-8"?>
<html xmlns:MadCap="http://www.madcapsoftware.com/Schemas/MadCap.xsd" MadCap:lastBlockDepth="2" MadCap:lastHeight="212" MadCap:lastWidth="514" xml:space="preserve">
<head>
</head>
<body>
<h1>Green</h1>
<p>Green is a color on the spectrum of visible light, located between blue and yellow. It is evoked by light with a predominant wavelength of roughly 495–570 nm. In the subtractive color system, used in painting and color printing, it is created by a combination of yellow and blue, or yellow and cyan; in the RGB color model, used on television and computer screens, it is one of the additive primary colors, along with red and blue, which are mixed in different combinations to create all other colors.</p>
</body>
</html><file_sep>/Target/Content/Manual Glossary Terms.htm
<?xml version="1.0" encoding="utf-8"?>
<html xmlns:MadCap="http://www.madcapsoftware.com/Schemas/MadCap.xsd" MadCap:lastBlockDepth="4" MadCap:lastHeight="1212" MadCap:lastWidth="1492" xml:space="preserve">
<head>
<link href="Resources/Stylesheets/NewStylesheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Manual - Glossary Terms</h1>
<h2>Text Definitions</h2>
<blockquote>
<h3>Popup</h3>
<p>Default Popup - <MadCap:glossaryTerm glossTerm="Glossary.Term8">Banana</MadCap:glossaryTerm> is also a fruit.</p>
<p>Left Popup - <MadCap:glossaryTerm class="popup_left" glossTerm="Glossary.Term8">Banana</MadCap:glossaryTerm> is also a fruit.</p>
<h3>Hyperlink</h3>
<p>Default Hyperlink - <MadCap:glossaryTerm glossTerm="Glossary.Term3">Yellow</MadCap:glossaryTerm> is a color.</p>
<p>Left Hyperlink - <MadCap:glossaryTerm class="hyperlink_left" glossTerm="Glossary.Term3">Yellow</MadCap:glossaryTerm> is a color.</p>
<h3>Expanding text </h3>
<p>Default Expanding- An <MadCap:glossaryTerm glossTerm="Glossary.Term6">Apple</MadCap:glossaryTerm> is a fruit.</p>
<p>Left Expanding - An <MadCap:glossaryTerm class="expanding_left" glossTerm="Glossary.Term6">Apple</MadCap:glossaryTerm> is a fruit.</p>
</blockquote>
<h2>Topic Definitions</h2>
<blockquote>
<h3>Popup</h3>
<p>Default Popup - <MadCap:glossaryTerm glossTerm="Glossary.Term7">Green</MadCap:glossaryTerm> is a color.</p>
<h3>Hyperlink</h3>
<p>Default Hyperlink - <MadCap:glossaryTerm glossTerm="Glossary.Term9">Apples</MadCap:glossaryTerm> is the plural for Apple.</p>
<h3>Expanding text </h3>
<p>Default Expanding- An <MadCap:glossaryTerm glossTerm="Glossary.Term5">Orange</MadCap:glossaryTerm> is a fruit.</p>
</blockquote>
<div style="border-left-style: solid;border-left-width: 3px;border-left-color: #008080;border-right-style: solid;border-right-width: 3px;border-right-color: #008080;border-top-style: solid;border-top-width: 3px;border-top-color: #008080;border-bottom-style: solid;border-bottom-width: 3px;border-bottom-color: #008080;">
<h2>Text Definitions - glossary term should be <span style="color: #00ced1;">blue</span> and <span style="font-family: Stencil;">stencil</span> font</h2>
<blockquote>
<h3>Popup</h3>
<p>Default Popup - <MadCap:glossaryTerm glossTerm="Glossary.Term8" class="blue">Banana</MadCap:glossaryTerm> is also a fruit.</p>
<p>Left Popup - <MadCap:glossaryTerm class="blue popup_left" glossTerm="Glossary.Term8">Banana</MadCap:glossaryTerm> is also a fruit.</p>
<h3>Hyperlink</h3>
<p>Default Hyperlink - <MadCap:glossaryTerm glossTerm="Glossary.Term3" class="blue">Yellow</MadCap:glossaryTerm> is a color.</p>
<p>Left Hyperlink - <MadCap:glossaryTerm class="blue hyperlink_left" glossTerm="Glossary.Term3">Yellow</MadCap:glossaryTerm> is a color.</p>
<h3>Expanding text </h3>
<p>Default Expanding- An <MadCap:glossaryTerm glossTerm="Glossary.Term6" class="blue">Apple</MadCap:glossaryTerm> is a fruit.</p>
<p>Left Expanding - An <MadCap:glossaryTerm class="blue expanding_left" glossTerm="Glossary.Term6">Apple</MadCap:glossaryTerm> is a fruit.</p>
</blockquote>
<h2>Topic Definitions - glossary term should be <span style="color: #00ced1;">blue</span> and <span style="font-family: Stencil;">stencil</span> font</h2>
<blockquote>
<h3>Popup</h3>
<p>Default Popup - <MadCap:glossaryTerm glossTerm="Glossary.Term7" class="blue">Green</MadCap:glossaryTerm> is a color.</p>
<h3>Hyperlink</h3>
<p>Default Hyperlink - <MadCap:glossaryTerm glossTerm="Glossary.Term9" class="blue">Apples</MadCap:glossaryTerm> is the plural for Apple.</p>
<h3>Expanding text </h3>
<p>Default Expanding- An <MadCap:glossaryTerm glossTerm="Glossary.Term5" class="blue">Orange</MadCap:glossaryTerm> is a fruit.</p>
</blockquote>
</div>
</body>
</html>
|
ed4cf9f0e2ef288f27baadb8ab6401c3f6ef36c8
|
[
"HTML"
] | 4 |
HTML
|
test1MC/lingo01
|
6edab2f7fda67805a1bbcec547e749ff9735cc12
|
dd24672a1df451dc913beef3b28d4878b792d682
|
refs/heads/master
|
<file_sep>import { Task } from './../../../interfaces/Task';
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-task',
templateUrl: './task.component.html',
styleUrls: ['./task.component.css']
})
export class TaskComponent implements OnInit {
//recibe dos variables desde el padre
@Input() task: Task;
@Input() index: number;
//envia dos eventos al padre
@Output() remove: EventEmitter<number>;
@Output() complete:EventEmitter<number>;
constructor() {
this.remove = new EventEmitter<number>();
this.complete = new EventEmitter<number>();
}
ngOnInit() {
}
//funcion que verfica si la tarea esta checheada usa el index que recibio del padre
taskCheckedEvent(){
this.complete.emit(this.index);
}
//fuincion que elimina una tarea usando el index que recibe del padre
removeEvent(){
this.remove.emit(this.index);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Task } from '../../interfaces/Task';
@Component({
selector: 'app-task-list',
templateUrl: './task-list.component.html',
styleUrls: ['./task-list.component.css']
})
export class TaskListComponent implements OnInit {
//arreglo con las tareas completadas y no completadas
public taskListNoCompleted:any = [];
public taskListCompleted:any = [];
public showInputTask: boolean;
public errorInput:boolean;
public showCompleted:boolean;
constructor() {
this.taskListCompleted = [];
this.taskListNoCompleted = [];
this.showInputTask = false;
this.errorInput = false;
this.showCompleted = true;
}
ngOnInit() {
}
//funcion que va a cambiar el valor de la variable showInputTask a true
showInputTextTask(){
this.showInputTask = true;
}
addTask(description){
if (description) {
const task: Task ={
'date': new Date(),
'description': description,
'completed': false
}
//añadiendo una tarea al arreglo de no completadas
this.taskListNoCompleted.push(task);
this.errorInput = false;
this.showInputTask = false;
} else {
this.errorInput = true;
}
}
//funcion que permite eliminar un elemento desde la posicion indicada
removeTask($event){
this.taskListNoCompleted.splice($event,1);
}
completeTask($event){
const task = this.taskListNoCompleted[$event];
//va a cambiar la tarea a completada
task.completed = true;
//va a agregar la nueva fecha de la tarea
task.date = new Date();
//elimna la tarea del arreglo de las NO completadas
this.taskListNoCompleted.splice($event,1);
this.taskListCompleted.push(task);
}
//funcion que al momento de hacer click va a cambiar el valor de showCompleted al inverso
showTaskCompleted(){
this.showCompleted = !this.showCompleted;
}
}
|
c6f7329b907d07d4fd4b3d7e64540beb8d4e96f5
|
[
"TypeScript"
] | 2 |
TypeScript
|
cbustamante777duoc/angular-tareas
|
2130353cb3a4fe9ea8f9267fde07f0933c6cd6bb
|
00a806a886b612f74c0e4769a6852fa06c891411
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>ICAMME-2019</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" type="text/css" href="../assets/css/bootstrap.min.css" >
<!-- Icon -->
<link rel="stylesheet" type="text/css" href="../assets/fonts/line-icons.css">
<!-- Slicknav -->
<link rel="stylesheet" type="text/css" href="../assets/css/slicknav.css">
<!-- Nivo Lightbox -->
<link rel="stylesheet" type="text/css" href="../assets/css/nivo-lightbox.css" >
<!-- Animate -->
<link rel="stylesheet" type="text/css" href="../assets/css/animate.css">
<!-- Main Style -->
<link rel="stylesheet" type="text/css" href="../assets/css/main.css">
<!-- Responsive Style -->
<link rel="stylesheet" type="text/css" href="../assets/css/responsive.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
</head>
<body class="page-template-default page page-id-1193 fusion-image-hovers fusion-body ltr fusion-sticky-header no-tablet-sticky-header no-mobile-sticky-header no-mobile-slidingbar no-mobile-totop mobile-logo-pos-left layout-wide-mode fusion-top-header menu-text-align-center mobile-menu-design-modern fusion-show-pagination-text fusion-header-layout-v2 avada-responsive avada-footer-fx-none fusion-search-form-classic fusion-avatar-square">
<!-- Header Area wrapper Starts -->
<header id="header-wrap">
<!-- Navbar Start -->
<nav class="navbar navbar-expand-lg fixed-top scrolling-navbar bg-dark" style="font-size: 10px">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
<span class="icon-menu"></span>
<span class="icon-menu"></span>
<span class="icon-menu"></span>
</button>
<a href="../index.html" class="navbar-brand"><img style="height: 50px; width: 150px; margin-left: 0%;" src="../assets/img/logo/logo.png" alt=""></a>
<!--<a href="index.html" class="navbar-brand"><img src="logo.png" alt=""></a>-->
</div>
<div class="collapse navbar-collapse" id="main-navbar">
<ul class="navbar-nav mr-auto w-100 justify-content-end">
<li class="nav-item ">
<a class="nav-link" href="../index.html">
Home
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="mission.html">
About
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="about.html">
About KIIT & KISS
</a>
</li>
<li class="nav-item ">
<a class="nav-link" href="paper.html">
Paper
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="tracks.html">
Topics
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="author.html">
Author Guidelines
</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="#">
Sponsorship
</a>
</li>
<!--<li class="nav-item">
<a class="nav-link" href="#schedules">
Schedules
</a>
</li>-->
<li class="nav-item">
<a class="nav-link" href="register.html">
Registration
</a>
</li>
<!--<li class="nav-item">
<a class="nav-link" href="#gallery">
Gallery
</a>
</li>-->
<li class="nav-item">
<a class="nav-link" href="downloads.html">
Downloads
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="contact.html">
Contact
</a>
</li>
</ul>
</div>
</div>
<!-- Mobile Menu Start -->
<ul class="mobile-menu">
<li>
<a class="page-scrool" href="../index.html">Home</a>
</li>
<li>
<a class="page-scrool" href="mission.html">About</a>
</li>
<li>
<a class="page-scrool" href="about.html">About KIIT & KISS</a>
</li>
<li>
<a class="page-scroll" href="paper.html">Paper</a>
</li>
<li>
<a class="page-scroll" href="tracks.html">Topics</a>
</li>
<li>
<a class="page-scroll" href="author.html">Author Guidelines</a>
</li>
<li>
<a class="page-scroll" href="#">Sponsorship</a>
</li>
<!--<li>
<a class="page-scroll" href="#schedules">Schedules</a>
</li>-->
<li>
<a class="page-scroll" href="register.html">Registration</a>
</li>
<!--<li>
<a class="page-scroll" href="#gallery">Gallery</a>
</li>-->
<li>
<a class="page-scroll" href="downloads.html">Downloads</a>
</li>
<li>
<a class="page-scroll" href="contact.html">Contact</a>
</li>
</ul>
<!-- Mobile Menu End -->
</nav>
<!-- Navbar End -->
</header>
<!--
<div id="sliders-container">
</div>
<main id="main" role="main" class="clearfix " style="">
<div class="fusion-row" style="">
<section id="content" style="width: 100%;">
<div id="post-1231" class="post-1231 page type-page status-publish hentry">
<span class="entry-title rich-snippet-hidden">Sponsorship</span><span class="vcard rich-snippet-hidden"><span class="fn"><a href="http://event.kiit.ac.in/icamme2019/author/admin/" title="Posts by admin" rel="author">admin</a></span></span><span class="updated rich-snippet-hidden">2018-08-21T13:04:37+00:00</span>
<div class="post-content">
<div class="fusion-fullwidth fullwidth-box nonhundred-percent-fullwidth non-hundred-percent-height-scrolling" style='background-color: rgba(255,255,255,0);background-position: center center;background-repeat: no-repeat;padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px;'><div class="fusion-builder-row fusion-row "><div class="fusion-layout-column fusion_builder_column fusion_builder_column_1_1 fusion-one-full fusion-column-first fusion-column-last 1_1" style='margin-top:0px;margin-bottom:20px;'>
<div class="fusion-column-wrapper" style="padding: 0px 0px 0px 0px;background-position:left top;background-repeat:no-repeat;-webkit-background-size:cover;-moz-background-size:cover;-o-background-size:cover;background-size:cover;" data-bg-url="">
--><!--<div class="fusion-text"><p>Government/Private organizations, NGOs, Public and Private Research institutions/industries and individuals can sponsor this international conference (ICAMME 2019) at the following rates:</p>
<ul>
<li><strong>Platinum Sponsor</strong>: 2,00,000 INR</li>
<li><strong>Golden Sponsor</strong>: 1.50,000 INR</li>
<li><strong>Silver Sponsor</strong>: 1,00,000 INR</li>
</ul>
<p>Note that, the rates can be negotiated.</p>
</div><div class="fusion-clearfix"></div>-->
<section style="padding: 70px;">
<b style="color: black;">SPONSORSHIP PROPOSAL</b>
<br><br>
<b style="color: black;"> International Conference on Advances in Material and Manufacturing Engineering (ICAMME - 2019)</b>
<p>ICAMME 2019 is a three days event to be held on March 15th – 17th, 2018 and hosted by Department of Mechanical Engineering, KIIT University Bhubaneshwar,Orissa. The event will include oral presentations of research papers grouped into parallel tracks. Keynote talks from experts and panel discussions are also included in the program schedule of the conference. </p>
<p>ICAMME 2019 is likely to be attended by Scientists and Academicians, Engineers, Industry representatives and Students from all over the globe. </p>
<p>We invite you to team with us in promotion of scientific and engineering research by sponsoring the conference. Various opportunities for association are available as per sponsorship details given below.</p>
<<<<<<< HEAD
<br>
<div style="background-color: lightblue; font-weight: bold; height: 35px; width: 700px;"><h3 style="color: black;" >PLATINUM SPONSORSHIP             2,50,000 INR </h3></div>
<ul class="about_ul" style="margin-left:20px;"></ul>
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on conference website front page with link (in association with ICAMME-2019).</li></ul>
<li><i class="glyphicon glyphicon-ok"></i>Logo recognition on conference sponsorship page. </li></ul>
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on ICAMME-2019 conference souvenir.</li></ul>
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on ICAMME-2019 participant's certificates . </li></ul>
<li><i class="glyphicon glyphicon-ok"></i> Recognition on all press releases. </li></ul>
<li><i class="glyphicon glyphicon-ok"></i> Acknowledgement during the inaugral ceremony.</li></ul>
<li><i class="glyphicon glyphicon-ok"></i> Space (10X 20 sq. feet) for exhibition.</li></ul>
<li><i class="glyphicon glyphicon-ok"></i> Company's brochure and demo cd to be included in conference kit.</li></ul>
=======
<div style="background-color: lightblue; font-weight: bold; height: 25px; width: 700px;"><h3 style="color: black;" >PLATINUM SPONSORSHIP                         <span >5,00,000 INR </span></h3></div>
<ul class="about_ul" style="margin-left:20px;">
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on conference website front page with link (in association with ICAMME-2019).</li>
<li><i class="glyphicon glyphicon-ok"></i>Logo recognition on conference sponsorship page. </li>
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on ICAMME-2019 conference souvenir.</li>
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on ICAMME-2019 participant's certificates . </li>
<li><i class="glyphicon glyphicon-ok"></i> Recognition on all press releases. </li>
<li><i class="glyphicon glyphicon-ok"></i> Acknowledgement during the inaugral ceremony.</li>
<li><i class="glyphicon glyphicon-ok"></i> Space (10X 20 sq. feet) for exhibition.</li>
<li><i class="glyphicon glyphicon-ok"></i> Company's brochure and demo cd to be included in conference kit.</li>
>>>>>>> 2c8ec5f62e6575a7afc5c4de4f8156059739b406
<li><i class="glyphicon glyphicon-ok"></i> Right to nominte two members in Advisory committee.</li>
</ul>
<li><i class="glyphicon glyphicon-ok"></i> Right to nominte two members in Organising committee.</li>
</ul>
<li><i class="glyphicon glyphicon-ok"></i> Right to nominte one speaker for invited talks.</li>
</ul>
<li><i class="glyphicon glyphicon-ok"></i> Right to nominte one session chair.</li>
</ul>
<li><i class="glyphicon glyphicon-ok"></i> Free registration for four delegates.</li>
</ul>
<<<<<<< HEAD
<br>
<div style="background-color: lightblue; font-weight: bold; height: 35px; width: 700px;"><h3 style="color: black;" >GOLDEN SPONSORSHIP             <span >1,50,000 INR</span></h3></div>
<ul class="about_ul" style="margin-left:20px;"></ul>
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on conference website front page with link (in association with ICAMME-2019).</li></ul>
<li><i class="glyphicon glyphicon-ok"></i>Logo recognition on conference sponsorship page. </li></ul>
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on ICAMME-2019 conference souvenir.</li></ul>
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on ICAMME-2019 participant's certificates . </li></ul>
<li><i class="glyphicon glyphicon-ok"></i> Acknowledgement during the inaugral ceremony.</li></ul>
<li><i class="glyphicon glyphicon-ok"></i> Space (10X 20 sq. feet) for exhibition.</li></ul>
<li><i class="glyphicon glyphicon-ok"></i> Right to nominte one member in Organising committee.</li></ul>
</ul>
<li><i class="glyphicon glyphicon-ok"></i> Right to nominte one session chair.</li></ul>
=======
<div style="background-color: lightblue; font-weight: bold; height: 25px; width: 700px;"><h3 style="color: black;" >GOLDEN SPONSORSHIP                         <span >3,00,000 INR</span></h3></div>
<ul class="about_ul" style="margin-left:20px;">
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on conference website front page with link (in association with ICAMME-2019).</li>
<li><i class="glyphicon glyphicon-ok"></i>Logo recognition on conference sponsorship page. </li>
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on ICAMME-2019 conference souvenir.</li>
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on ICAMME-2019 participant's certificates . </li>
<li><i class="glyphicon glyphicon-ok"></i> Acknowledgement during the inaugral ceremony.</li>
<li><i class="glyphicon glyphicon-ok"></i> Space (10X 20 sq. feet) for exhibition.</li>
<li><i class="glyphicon glyphicon-ok"></i> Right to nominte one member in Organising committee.</li>
</ul>
<li><i class="glyphicon glyphicon-ok"></i> Right to nominte one session chair.</li>
>>>>>>> 2c8ec5f62e6575a7afc5c4de4f8156059739b406
</ul>
<li><i class="glyphicon glyphicon-ok"></i> Free registration for two delegates.</li>
</ul>
<<<<<<< HEAD
<br>
<div style="background-color: lightblue; font-weight: bold; height: 35px; width: 700px;"><h3 style="color: black;" >SILVER SPONSORSHIP             <span >1,00,000 INR</span></h3></div>
<ul class="about_ul" style="margin-left:20px;"></ul>
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on conference website front page with link (in association with ICAMME-2019).</li></ul>
<li><i class="glyphicon glyphicon-ok"></i>Logo recognition on conference sponsorship page. </li></ul>
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on ICAMME-2019 conference souvenir.</li></ul>
<li><i class="glyphicon glyphicon-ok"></i> Space (10X 20 sq. feet) for exhibition.</li></ul>
=======
<div style="background-color: lightblue; font-weight: bold; height: 25px; width: 700px;"><h3 style="color: black;" >SILVER SPONSORSHIP                         <span >1,00,000 INR</span></h3></div>
<ul class="about_ul" style="margin-left:20px;">
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on conference website front page with link (in association with ICAMME-2019).</li>
<li><i class="glyphicon glyphicon-ok"></i>Logo recognition on conference sponsorship page. </li>
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on ICAMME-2019 conference souvenir.</li>
<li><i class="glyphicon glyphicon-ok"></i> Space (10X 20 sq. feet) for exhibition.</li>
>>>>>>> 2c8ec5f62e6575a7afc5c4de4f8156059739b406
<li><i class="glyphicon glyphicon-ok"></i> Free registration for two delegates.</li>
</ul>
<br>
<div style="background-color: lightblue; font-weight: bold; height: 35px; width: 700px;"><h3 style="color: black;" >BRONZE SPONSORSHIP             <span >50,000 INR</span></h3></div>
<ul class="about_ul" style="margin-left:20px;"></ul>
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on conference website front page with link (in association with ICAMME-2019).</li></ul>
<li><i class="glyphicon glyphicon-ok"></i>Logo recognition on conference sponsorship page. </li></ul>
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on ICAMME-2019 conference souvenir.</li></ul>
<<<<<<< HEAD
<li><i class="glyphicon glyphicon-ok"></i> Free registration for one delegate.</li>
</ul>
<br>
=======
<div style="background-color: lightblue; font-weight: bold; height: 25px; width: 700px;"><h3 style="color: black;" >BRONZE SPONSORSHIP                         <span >50,000 INR</span></h3></div>
<ul class="about_ul" style="margin-left:20px;">
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on conference website front page with link (in association with ICAMME-2019).</li>
<li><i class="glyphicon glyphicon-ok"></i>Logo recognition on conference sponsorship page. </li>
<li><i class="glyphicon glyphicon-ok"></i> Logo recognition on ICAMME-2019 conference souvenir.</li>
<li><i class="glyphicon glyphicon-ok"></i> Free registration for one delegate.</li>
</ul>
>>>>>>> 2c8ec5f62e6575a7afc5c4de4f8156059739b406
<!--<div style="background-color: lightblue; font-weight: bold; height: 25px; width: 400px;"><h3 style="color: black;" >DINNER SPONSORSHIP                         <span ></span></h3></div>
<ul class="about_ul" style="margin-left:20px;">
<li><i class="glyphicon glyphicon-ok"></i> Company Logo and link on Conference Website </li>
<li><i class="glyphicon glyphicon-ok"></i> Colour Advertisement of sponsor/product in the Conference Souvenir </li>
<li><i class="glyphicon glyphicon-ok"></i> Special talk/Presentation of 15 minutes before the dinner </li>
<li><i class="glyphicon glyphicon-ok"></i> Company’s Name and Logo printed on the Conference Signage</li>
<li><i class="glyphicon glyphicon-ok"></i> Display of Company Banner within the Dinner Area</li>
<li><i class="glyphicon glyphicon-ok"></i> One complementary registration </li>
</ul>
<div style="background-color: lightblue; font-weight: bold; height: 25px; width: 400px;"><h3 style="color: black;" >ALLIED SPONSORSHIP                         <span ></span></h3></div>
<ul class="about_ul" style="margin-left:20px;">
<li><i class="glyphicon glyphicon-ok"></i> Conference Kit Sponsorship : 150,000 INR
(Benefits: Sponsor’s Logo along with Organizer’s Logo will be places on the bag)
</li>
<li><i class="glyphicon glyphicon-ok"></i> Banner and Poster Sponsorship : 50,000 INR
(Benefits: Conference Banner and Poster contain the sponsor’s logo. There will be placed at the Conference Venue and Publicised across colleges and Universities.)
</li>
<li><i class="glyphicon glyphicon-ok"></i> Pen drive, T-shirts and Blazers Sponsorship</li>
</ul>
<div style="background-color: lightblue; font-weight: bold; height: 25px; width: 400px;"><h3 style="color: black;" >EXHIBITION STALLS                         <span ></span></h3></div>
<ul class="about_ul" style="margin-left:20px;">
<li><i class="glyphicon glyphicon-ok"></i> Exhibition Stall (2mx2m) : 60,000 INR</li>
<li><i class="glyphicon glyphicon-ok"></i> Conference Bag Inserts : 10,000 INR </li>
<li>The inserts to be provided by the company </li>
</ul>
<table class="table table-bordered table-hover">
<tbody><tr>
<th>Advertisement Size and Location </th>
<th>Rate (INR)</th>
</tr>
<tr>
<td>Back Cover Page (Colour)</td>
<td>50,000</td>
</tr>
<tr>
<td>Inner Cover Page (Front & Back) </td>
<td>40,000</td>
</tr>
<tr>
<td>Full Page (Colour)</td>
<td>30,000</td>
</tr>
<tr>
<td>Full Page (B&W) </td>
<td>20,000</td>
</tr>
<tr>
<td>Half Page (Colour)</td>
<td>15,000</td>
</tr>
<tr>
<td>Half Page (B&W) </td>
<td>12,000/td>
</tr>
</tbody>
</table>
<p><b>Note:</b> For Coloured advertisement, artwork in CD with printout of the same should be provided by the advertiser only.</p>
<h1>General Terms & Conditions</h1>
<ol class="about_ul">
<li>Since sponsorship opportunities are limited, these shall be allocated on a first come first serve basis.</li>
<li>The sponsors shall set up their stalls (specified size) and bring display material as desired by them for the display stalls.</li>
<li>All payments for sponsorship/stall bookings are to be made in advance.</li>
<!-- <li>All transactions are subject to Noida jurisdiction.</li>-->
<!-- <li>All stall requirements shall be made known seven days prior to the event. All additions shall be charged appropriately.</li>
<li>Company's Logo & complete Name of the Company with style will be required for acknowledging through Backdrops, Banners, brochures, stationary, Invitation cards & other promotional material.</li>
</ol>
<b style="color: black;">Mode of Payment</b>
<p>All payments are to be made through DD/Cheque drawn in favour of "KIIT University Orissa" payable at Bhubaneshwar.</p>
<br>-->
<b> Stall package</b>
<br><br>
<h3>For more details download the brochure </h3>
<a href="../assets/Downloads/brochure.pdf"><button> BROCHURE</button></a>
<br><br>
<p style="color: black;">
<b> For further details Contact:</b> <br>
Organizing Secretary (ICAMME – 2019)<br>
Department of Mechanical Engineering <br>
Kalinga Institute of Industrial Technology<br>
Campus - 8 <br>
KIIT University, Orissa.<br>
Phone number: +91-9776220902 , +91-8763547437<br>
Email: <EMAIL>
</p>
</section>
<!--
</div></div></div>
</div>
</div>
</section>
</div>
</main>-->
<div class="fusion-footer">
<!-- Footer Section Start -->
<footer class="footer-area section-padding">
<div class="container">
<div class="row">
<div class="col-md-6 col-lg-3 col-sm-6 col-xs-12 wow fadeInUp" data-wow-delay="0.2s">
<!-- <h3><img src="assets/img/logo.png" alt=""></h3>-->
<h3><img src="../assets/img/logo/logo.png" alt=""></h3>
<p>
ICAMME - 2019 , begins from 15 March 2019.
</p>
</div>
<div class="col-md-6 col-lg-3 col-sm-6 col-xs-12 wow fadeInUp" data-wow-delay="0.4s">
<h3>QUICK LINKS</h3>
<ul>
<li><a href="mission.html">About Conference</a></li>
<li><a href="speakers.html">Our Speakers</a></li>
<li><a href="../index.html#schedules">Event Schedule</a></li>
<li><a href="../index.html#gallery">Event Photo Gallery</a></li>
</ul>
</div>
<div class="col-md-6 col-lg-3 col-sm-6 col-xs-12 wow fadeInUp" data-wow-delay="0.6s">
<h3>RECENT POSTS</h3>
<ul class="image-list">
<li>
<h6 class="post-title"> <a href="blog-single.html">Coming Soon</a> </h6>
<!--Recent POSTS
<figure class="overlay">
<img class="img-fluid" src="assets/img/art/a1.jpg" alt="">
</figure>
<div class="post-content">
<h6 class="post-title"> <a href="blog-single.html">Lorem ipsm dolor sumit.</a> </h6>
<div class="meta"><span class="date">October 12, 2018</span></div>
</div>
</li>
<li>
<figure class="overlay">
<img class="img-fluid" src="assets/img/art/a2.jpg" alt="">
</figure>
<div class="post-content">
<h6 class="post-title"><a href="blog-single.html">Lorem ipsm dolor sumit.</a></h6>
<div class="meta"><span class="date">October 12, 2018</span></div>
</div>-->
</li>
</ul>
</div>
<div class="col-md-6 col-lg-3 col-sm-6 col-xs-12 wow fadeInUp" data-wow-delay="0.8s">
<h3>SUBSCRIBE US</h3>
<div class="widget">
<div class="newsletter-wrapper">
<form method="post" id="subscribe-form" name="subscribe-form" class="validate">
<div class="form-group is-empty">
<input type="email" value="" name="Email" class="form-control" id="EMAIL" placeholder="Your email" required="">
<button type="submit" name="subscribe" id="subscribes" class="btn btn-common sub-btn"><i class="lni-pointer"></i></button>
<div class="clearfix"></div>
</div>
</form>
</div>
</div>
<!-- /.widget -->
<div class="widget">
<h5 class="widget-title">FOLLOW US ON</h5>
<ul class="footer-social">
<li><a class="facebook" href="#"><i class="lni-facebook-filled"></i></a></li>
<li><a class="twitter" href="#"><i class="lni-twitter-filled"></i></a></li>
<li><a class="linkedin" href="#"><i class="lni-linkedin-filled"></i></a></li>
<li><a class="google-plus" href="#"><i class="lni-google-plus"></i></a></li>
</ul>
</div>
</div>
</div>
</div>
</footer>
<!-- Footer Section End -->
<div id="copyright">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="site-info">
<p>© Designed and Developed by <a href="http://kiit.ac.in/" rel="nofollow">KIIT University</a></p>
</div>
</div>
</div>
</div>
</div>
<!-- Go to Top Link -->
<a href="#" class="back-to-top">
<i class="lni-chevron-up"></i>
</a>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="../assets/js/jquery-min.js"></script>
<script src="../assets/js/popper.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script src="../assets/js/jquery.countdown.min.js"></script>
<script src="../assets/js/jquery.nav.js"></script>
<script src="../assets/js/jquery.easing.min.js"></script>
<script src="../assets/js/wow.js"></script>
<script src="../assets/js/jquery.slicknav.js"></script>
<script src="../assets/js/nivo-lightbox.js"></script>
<script src="../assets/js/main.js"></script>
<script src="../assets/js/form-validator.min.js"></script>
<script src="../assets/js/contact-form-script.min.js"></script>
<script src="../assets/js/map.js"></script>
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key=<KEY>"></script>
<a class="fusion-one-page-text-link fusion-page-load-link"></a>
</body>
</html>
<file_sep># ICAMME-2019
Mechanical conference 2019
|
4ada5870f20ac314d660e96ca51b4967ccdcb127
|
[
"Markdown",
"HTML"
] | 2 |
Markdown
|
saumyagoyal1708/ICAMME-2019
|
298d85f8f4594cf5ea32aa0bf9110a486c654476
|
a92142aa9356f6f3c487a511500900dadae0c567
|
refs/heads/main
|
<repo_name>Jubel13/Wiki-API<file_sep>/README.md
# Project Description
## Wiki-API
Simple RESTful API from Udemy course: <a href="https://www.udemy.com/course/the-complete-web-development-bootcamp/">The Complete 2021 Web Development Bootcamp</a> by <NAME>.
Clone or download this project to run it on you local machine, then run 'npm install' on the terminal.
To run this project, you need <a href='https://www.mongodb.com/'>mongoDB</a> server on your local system.
Use <a href='https://www.postman.com/'>postman</a> app to do post, put, patch, get, and delete request.
This project is just some simple REST API simulation.
This API doesn't have interface, all actions was done using postman app
|
2a44eae40e039505cec7075baa4811a7703295c8
|
[
"Markdown"
] | 1 |
Markdown
|
Jubel13/Wiki-API
|
8b59ffa63088c681da17145dc1ee1365fdae74e7
|
6e195c84d45e625246797f909b5fc8d023360f23
|
refs/heads/master
|
<repo_name>kennycrosby/test-frontend<file_sep>/readme.md
# Siberia Front End Assessment
### **What's In Here**
In the `/audio` directory, you will find 3 files:
1. **test.wav** a spoken-word audio file
2. **test.json** a text transcript of test.wav in JSON format, as output by the Google Speech to Text API
3. **test.csv** same as above, but in CSV format
### **The Brief**
- Using the files above, please create a simple web experience that will render the words found in one of the transcript files in time with the audio playback.
- How the words and audio are rendered and any interaction or animation is entirely up to you. We have intentionally omitted any specific design documents from this exercise, so feel free to take your own creative liberties in service of a beautiful and elegant user experience.
- For the sake of this exercise, you are free to use any languages, frameworks or tools that you think will help you get the job done. Do not feel that you must pull from the standard Siberia toolbox (because such a thing doesn't really exist anyway).
- Please work in a feature branch of this repo.
- When you are finished, please submit your feature branch as a pull request against `master` and assign it for review.
- Feel free to add additional notes or instructions to this readme file.
- This should be a simple and fun way to give us a quick taste of what you can do. It shouldn't need to take up too much of your time, so please don't go too crazy with it.
### **What are we looking for?**
Your output should be polished and complete in a way that you would be comfortable handing over to a client as a (pre-QA) final deliverable.
The point of this exercise is simply to see how you would work through a task. This helps us assess if, when and where you might be a good fit for the team. That can take a wide variety of forms, so please don't try to second guess what you think we might be looking for... we want to see how _you_ would approach a problem – not how you think we would approach it.
|
ea7f04f64fd3bb3aa8f4e4748b702044c83f6b2d
|
[
"Markdown"
] | 1 |
Markdown
|
kennycrosby/test-frontend
|
63c81fb41b3b320a11cc5a1c88fe5bf324dd43ce
|
9eb61c2adcf96d4c38c45c39e702c20800dd2130
|
refs/heads/master
|
<repo_name>cerero/ZombieShoot<file_sep>/Assets/Script/PanelSwitch.cs
using UnityEngine;
using System.Collections;
public class PanelSwitch : MonoBehaviour {
// Use this for initialization
private GameObject panel1 ;
private GameObject panel2 ;
void Start() {
panel1 = GameObject.Find("MainMenu");
panel2 = GameObject.Find("GameSetting");
NGUITools.SetActive(panel2,false);
}
void OnClick() {
NGUITools.SetActive(panel2,true);
NGUITools.SetActive(panel1,false);
}
// Update is called once per frame
void Update () {
}
}
|
941498c605fa14c127ef2501e131c11f8d788e68
|
[
"C#"
] | 1 |
C#
|
cerero/ZombieShoot
|
75e6f8623402b48713cc2f86541a74896e26799a
|
641170ca5ff6206850b44f66b1182ff482168c9c
|
refs/heads/master
|
<repo_name>aarizag/FunctionalProgramming<file_sep>/Monads/partA2.py
from pymonad import Nothing, Maybe, Just
class Expr:
"""
Dummy superclass to support creation of 2 seperate constructors: Div and Val
Meant to Replicate:
data Expr = Val n | Div Expr Expr
"""
pass
class Div(Expr):
def __init__(self, a: Expr, b: Expr):
self.a = a
self.b = b
class Val(Expr):
def __init__(self, n: int):
self.n = n
def eval_basic(exp: Expr):
"""
eval :: Expr -> Int
eval (Val n) = n
eval (Div a b) = eval a / eval b
"""
if isinstance(exp, Val):
return exp.n
elif isinstance(exp, Div):
return eval_basic(exp.a) // eval_basic(exp.b)
def safe_div(a: int, b: int) -> Maybe:
"""
-- Division guarded against division by 0
safe_div :: Int -> Int -> Maybe Int
safe_div _ 0 = Nothing
sage_div a b = Just (a/b)
"""
return Nothing if b == 0 else Just(a // b)
def eval_do(exp: Expr) -> Maybe:
"""
eval :: Expr -> Maybe Int
eval (Val n) = return n
eval (Div x y) = do n <- eval x
m <- eval y
safe_div n m
"""
if isinstance(exp, Val):
return Just(exp.n)
elif isinstance(exp, Div):
n = eval_do(exp.a).getValue()
m = eval_do(exp.b).getValue()
return safe_div(n, m) if n and m else None
def eval_non_do(exp: Expr) -> Maybe:
"""
eval :: Expr -> Maybe Int
eval (Val n) = return n
eval (Div a b) = eval a >>= (\n -> eval b >>= (\m -> safe_div n m ))
"""
if isinstance(exp, Val):
return Just(exp.n)
elif isinstance(exp, Div):
return eval_non_do(exp.a) >> (lambda x: eval_non_do(exp.b) >> (lambda y: safe_div(x, y)))
# Works similarly to the below, but abstracts the actual values from the 'Just' values
# return (lambda x, y: safe_div(x,y))(eval_non_do(exp.a).getValue(), eval_non_do(exp.b).getValue())
# Test safe_div
x = safe_div(10, 2)
print(x)
print(x.getValue())
# Different expression tests
t1 = Div(Val(6), Val(2)) # 6 / 2 = 3
t2 = Div(Val(6), Val(0)) # 6 / 0 = Nothing
t3 = Div(Val(96), Div(Div(Val(72), Val(3)), Div(Val(9), Val(3)))) # 96 / [(72/3) / (9/3)] = 12
fs = [eval_do, eval_non_do]
ts = [t1, t2, t3]
# run tests in both functions
for f in fs:
print(f"\n{f.__name__}")
for t in ts:
print(f"{f(t)}")
<file_sep>/IntroToHaskell/class_notes.hs
import Debug.Trace
smallPrimeDivisors n = [d | d <- takeWhile (\x -> x^2 <= n) primes, n `mod` d == 0]
--primes = 2 : [n | n <- oddsFrom3, null (smallPrimeDivisors n)]
primes = 2 : [p | p <- oddsFrom3,
let divisors = smallPrimeDivisors p,
trace
(show p ++ (if null divisors
then "is prime"
else "is divisible by" ++ show divisors) )
null divisors
]
oddsFrom3 = [3, 5 .. ]
<file_sep>/Functional_in_Python/Luhn.py
from typing import List
from pyrsistent import v, pvector
"""
Luhn Algorithm to determine if an account number is considered valid.
Source: https://en.wikipedia.org/wiki/Luhn_algorithm
"""
def luhn_wiki(purported):
"""
>>> luhn_wiki(79927398713)
True
>>> luhn_wiki(79927398714)
False
"""
LUHN_ODD_LOOKUP = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9) # sum_of_digits (index * 2)
if not isinstance(purported, str):
purported = str(purported)
try:
evens = sum(int(p) for p in purported[-1::-2])
odds = sum(LUHN_ODD_LOOKUP[int(p)] for p in purported[-2::-2])
return (evens + odds) % 10 == 0
except ValueError: # Raised if an int conversion fails
return False
"""
Standard implementation of the Luhn Algorithm
"""
def luhn_standard(account_num: int, check_digit: int = 0) -> bool:
# Seperate number into a list.
# Convert the number to a string, then iterate through string converting back to int at each item
def sep_digits(num: int) -> List[int]:
# Doing math operations is slower at larger number of digits and negligibly faster at small numbers
# return [] if num == 0 else sep_digits(num // 10) + [num % 10]
return [int(x) for x in str(num)]
# Double every other number in a list starting at the end of the list and sum the new total
def double_and_sum() -> int:
digit_list = sep_digits(account_num)
for i in range(len(digit_list)-2, -1, -2):
# double every other number
digit_list[i] = sum(sep_digits(2*digit_list[i]))
return sum(digit_list)
# Return if the last digit matches the check digit (0 by default)
return double_and_sum() % 10 == check_digit
"""
Implementation of the Luhn Algorithm using Pyrsistent data structures rather than standard structures
"""
def luhn_pyrsistent(account_num, check_digit: int = 0) -> bool:
# Seperate number into a list.
# Convert the number to a string, then iterate through string converting back to int at each item
def sep_digits(n: int):
return pvector(int(x) for x in str(n))
# Double every other number in a list starting at the end of the list and sum the new total
def double_and_sum() -> int:
digit_list = sep_digits(account_num)
# sum every number not being doubled
even_sum = sum(digit_list[-1::-2])
# double every other number
# if the number being doubled is greater than 5, seperate the digits after doubling and sum those.
odd_sum = sum(2*x if x < 5 else sum(sep_digits(2*x))for x in digit_list[-2::-2])
return even_sum + odd_sum
# Return if the last digit matches the check digit (0 by default)
return double_and_sum() % 10 == check_digit
"""
# Coconut Implementation of Luhn Algorithm
from operator import mod
def luhn_algorithm(acc_num) = mod(evens+odds, 10) == 0 where:
digits = digit_to_list(acc_num)
evens = digits[-1::-2] |> sum
odds = digits[-2::-2] |> fmap$(x -> sum(digit_to_list(x*2))) |> list |> sum
def digit_to_list(n) = str(n) |> map$(int) |> list
t1 = 79927398713 # True
t2 = 79927398714 # False
luhn_algorithm(t1) |> print
luhn_algorithm(t2) |> print
"""
def test_all():
t1 = 79927398713 # True
t2 = 79927398714 # False
t3 = 1234567890123456 # False
t4 = 1234567890123452 # True
tests = [t1, t2, t3, t4]
for f in [luhn_wiki, luhn_standard, luhn_pyrsistent]:
print(f"\n{f.__name__}")
for t in tests:
print(f"Test on {t}: {f(t)}")
test_all()
<file_sep>/Intro/choose.py
# choose.py
import random
from typing import Sequence, TypeVar
Choosable = TypeVar("Chooseable")
def choose(items: Sequence[Choosable]) -> Choosable:
return random.choice(items)
names = ["Guido", "Jukka", "Ivan"]
reveal_type(names)
name = choose(names)
reveal_type(name)<file_sep>/Decorators/various_fibinacci.hs
{-
Author: <NAME>
Date: 2/18/19
No Rights Reserved tbh
-}
import qualified Data.Map as M
{-
Simple Top Down recursive Fibonacci algorithm
-}
fib_top_down_rec n
| n <= 2 = 1
| otherwise = (fib_top_down_rec (n-1)) + (fib_top_down_rec (n-2))
{-
Simple Bottom up 'iterative' Fibonacci
-}
fib_bottom_up_iter n = fib 1 1 0
where fib c ka kb
| c < n = fib (c+1) (ka+kb) ka
| otherwise = ka
{-
Generic Data Type for creating heterogeneous lists
S defines a string, I defines an Integer, and F defines an Integer.
F is used to distinguish between numbers in the sequence that
need to be broken down further and numbers that already have been added together.
-}
data Generic v = S {str :: String} | I {int :: Integer} | F {fibval :: Integer} deriving (Show, Eq)
{-
A dispatcher that uses pattern matching to distinguish between the
types of Generics
-}
dispatcher :: Generic v -> Char
dispatcher (S _) = 's'
dispatcher (I _) = 'i'
dispatcher (F _) = 'f'
{-
Top Down Iterative Fibonacci Algorithm
Takes no Parameters, but internally calls 'fib' which takes a list of Generics to represent commands and a
list of integers to represent a stack
Description of Guards:
1st: Exit Condition - Determines if there are still inputs to be processed.
Else return first int in stack
2nd: If token is an Integer Generic, add it to stack and continue iterating through inputs
3rd: Token Value needs to be broken down further:
if it's 2 or 1, then append (Generic Int = 1) to inputs
else append "+" symbol, then (Generic F = token-1 and token-2) to inputs
4th: "+" causes the first 2 items in stack to be added together then appended to the input list
otherwise: Fail safe, return -1 if none of the conditions are met. (Should never happen)
Description of where variables:
token: The last item in the list of inputs. This determines the action to be taken
inp: The list of inputs after "popping" off the last item.
n: The integer value of a number to be broken down further in the fibonacci sequence
first: the first integer in the stack
second: the third item in the stack (jk it's the second)
rest: the stack minus the first and second items
-}
fib_top_down_iter num_fibs = fib [F num_fibs] []
where fib inputs stack
| inputs == [] = head stack
| dispatcher token == 'i' = fib inp (int token : stack)
| dispatcher token == 'f' =
if n <= 2 then fib (inp ++ [I 1]) stack
else fib (inp ++ [S "+", F (n-1), F (n-2)]) stack
| S "+" == token = fib (inp ++ [I (first+second)]) rest
| otherwise = -1
where token = last inputs
inp = init inputs
n = fibval token
(first:second:rest) = stack
{-
Top Down Iterative Fibonacci Algorithm with an optimization
"""
Same as fib_top_down_iter but with more efficient list processing.
Expands second recursive call down to the bottom.
"""
- Abbott
Description is equal to the above function, but with the following changes:
Guard 3: replaced the appending of n-1 and n-2 with a full iteration
from n -> 2 with a step of -2. Since the iteration is guaranteed to
end at 1 or 2, it will always prepend [1] to the stack.
Guard 4: Rather than appending the value of the first and second numbers
in the stack to the input list, it is added directly back to the stack
variable list_iter: small function to iterate from n -> 2, creating a
list of "+" symbols to add and numbers that need to be broken down
further.
variable n: removed
-}
fib_top_down_iter_with_opt_1 num_fibs = fib [F num_fibs] []
where fib inputs stack
| inputs == [] = head stack
| dispatcher token == 'i' = fib inp $ int token : stack
| dispatcher token == 'f' = fib (inp ++ (list_iter $ fibval token)) $ [1]++stack
| S "+" == token = fib inp $ (first + second) : rest
| otherwise = -1
where token = last inputs
inp = init inputs
(first:second:rest) = stack
list_iter n
| n <= 2 = []
| otherwise = [S "+", F (n-1)] ++ list_iter (n-2)
{-
Top Down Iterative Fibonacci Algorithm with another optimization
"""
Same as fib_top_down_iter but with more efficient list processing.
Expands the first recursive call and groups results.
Since this approach need keep track only of the n it is up to and
the coefficients of n-1 and n-2, it does so directly in a tuple.
The result is equivalent to buttom-up iter.
"""
- Abbott
Guard Descriptions:
1st: If the original number of Fibonacci numbers to evaluate is <= 2, return 1
2nd: if the list is empty or the value of the next number to break down is 2:
return ca + cb
3rd: otherwise iterate through the next inputs
Variable Description:
ca, cb: the numbers being summed together for the sequence
fib_a,b: the numbers being continuously broken down to n-1 and n-2
nx, next_n = the literal int values of fib_a and fib_b-1
next_inputs: the updated sequence recursively called with fib
Note:
I removed the stack and the strings "+", "*" from the initial and recursive calls to the function because,
unlike the previous functions, they are unused in determining actions to take and there
is no console output to show the trace.
If you want to include them, replace the initial call with
fib [S "+", S "*", I 1, F num_fibs, S "*", I 0, F (num_fibs-1)]
the string of variables with
(plus:times:ca:fib_a:_:cb:fib_b: empty) = inputs
and next_inputs with
next_inputs = (plus:times:ca:fib_a:_:cb:fib_b: empty) = inputs
-}
fib_top_down_iter_with_opt_2 num_fibs = fib [I 1, F num_fibs, I 0, F (num_fibs-1)]
where fib inputs
| num_fibs <= 2 = 1
| inputs == [] || (nx == 2) = int ca + (int cb)
| otherwise = fib next_inputs
where (ca:fib_a:cb:fib_b: __) = inputs -- __ is the empty tail of the list
nx = fibval fib_a
next_n = fibval fib_b - 1
next_inputs = (I (int ca + (int cb)):fib_b:ca:(F next_n): __)
{-
Top Down Iterative Fibonacci Algorithm with Cache
Takes no Parameters, but internally calls 'fib' which takes a list of Generics to represent commands, a
list of integers to represent a stack, and a Map pre-made with the 1st and 2nd
Fibonacci numbers.
Description of Guards:
1st: Exit Condition - Determines if there are still inputs to be processed.
Else return first int in stack
2nd: If token is an Integer Generic, add it to stack and continue iterating through inputs
3rd: Token Value needs to be broken down further:
Look up the value of the token in the cache (Data Map).
If it exists, append that value (as a Generic) to the input list.
Else append "cache", then "+" symbol, then (Generic F = token-1 and token-2) to inputs
4th: "+" causes the first 2 items in stack to be added together then appended to the input list
5th: "cache" determines that a new value in the Fibonacci sequence has been found and
needs to be added to the cache. Insert the first and second values in the stack
as a key value pair, respectively
otherwise: Fail safe, return -1 if none of the conditions are met. (Should never happen)
Description of where variables:
token: The last item in the list of inputs. This determines the action to be taken
inp: The list of inputs after "popping" off the last item.
n: The integer value of a number to be broken down further in the fibonacci sequence
first: the first integer in the stack
second: the third item in the stack (jk it's the second)
rest: the stack minus the first and second items
-}
fib_top_down_iter_with_cache num_fibs = fib [F num_fibs] [] (M.fromList [(1,1),(2,1)])
where fib inputs stack cache
| inputs == [] = head stack
| dispatcher token == 'i' = fib inp (int token : stack) cache
| dispatcher token == 'f' =
case M.lookup n cache of
Just x -> fib (inp++[I x]) stack cache
Nothing -> fib (inp ++ [S "cache", I n, S "+", F (n-1), F (n-2)]) stack cache
| S "+" == token = fib (inp ++ [I (first+second)]) rest cache
| S "cache" == token = fib inp (tail stack) (M.insert first second cache)
where token = last inputs
inp = init inputs
n = fibval token
(first:second:rest) = stack
<file_sep>/Amuse-Bouche/test.hs
str = "hello \
\world"<file_sep>/IntroToHaskell/goldbach_conjecture(remade).py
import time
class goldbach:
def __init__(self):
from math import sqrt
from itertools import takewhile
self.primes = [2, 3]
self.sqrt = sqrt
self.takewhile = takewhile
def next_prime(self, floor):
i = floor # if floor % 2 == 1 else floor - 1
while self.primes[-1] < floor:
for p in self.takewhile((lambda x: x*x <= i), self.primes):
if i % p == 0:
break
else:
self.primes += [i]
i += 2
def is_prime(self, num):
return num in self.primes
def is_perfect_square(self, num):
return round(self.sqrt(num))**2 == num
def conjecture_test(self, g: int) -> [int]:
for p in self.primes[:-1]:
k = (g - p) // 2
if self.is_perfect_square(k):
return None
return g
def generate_odds(self):
n = 3
while True:
yield n
n += 2
def iterate_test(self):
exceptions: [int] = [] # list of exceptions to the conjecture
odd_nums = self.generate_odds()
while len(exceptions) < 2:
o = next(odd_nums)
self.next_prime(o)
exceptions += [o] if not self.is_prime(o) and self.conjecture_test(o) else []
return exceptions
def test_primes_speed(self, n):
nums = self.generate_odds()
start = time.time()
while len(self.primes) < n:
self.next_prime(next(nums))
end = time.time()
print(f"last prime = {self.primes[-1]}, found in {end-start}")
# (1000) last prime = 7919, found in 0.015625953674316406
# (10000) last prime = 104729, found in 0.3230447769165039
# (50000) last prime = 611953, found in 2.370232343673706
# print(self.primes)
goldbach().test_primes_speed(50000)
total = 0
for i in range(10):
start = time.time()
exceptions = goldbach().iterate_test()
total += time.time() - start
print("Average time taken after 10 runs:", (total/10))
print("Exceptions found:", exceptions)<file_sep>/IntroToHaskell2/while.py
def my_while(state, cont, act, fin):
return my_while(act(state), cont, act, fin) if cont(state) else fin(state)
<file_sep>/FunOfReinvention/FOR.py
_contracts = {}
class Contract:
@classmethod
def __init_subclass__(cls):
_contracts[cls.__name__] = cls
# Own the 'dot'
def __set__(self, instance, value):
self.check(value)
instance.__dict__[self.name] = value
def __set_name__(self, _cls, name):
self.name = name
@classmethod
def check(cls, value):
pass
class Typed(Contract):
type = None
@classmethod
def check(cls, value):
try:
assert isinstance(value, cls.type)
except AssertionError:
print(f'Got {value}; expected {cls.type}')
super().check(value)
class Integer(Typed):
type = int
class String(Typed):
type = str
class Float(Typed):
type = float
class Positive(Contract):
@classmethod
def check(cls, value):
# print(f'checking <{value}> for positive')
try:
assert value > 0
except AssertionError:
print(f'Got {value}; expected > 0.')
super().check(value)
class Nonempty(Contract):
@classmethod
def check(cls,value):
try:
assert '__len__' in dir(value) and len(value) > 0
except AssertionError:
val = value if value != '' else "''"
print(f'Got {val}; expected {val} to have a __len__ attribute and that len({val}) > 0.')
super().check(value)
class PositiveInteger(Integer, Positive):
pass
class NonemptyString(String, Nonempty):
pass
from functools import wraps
from inspect import signature
from collections import ChainMap
def checked(func):
sig = signature(func)
ann = ChainMap(
func.__annotations__,
func.__globals__.get('__annotations__', {})
)
@wraps(func)
def wrapper(*args, **kwargs):
bound = sig.bind(*args, **kwargs)
for (name, val) in bound.arguments.items():
if name in ann:
ann[name].check(val)
return func(*args, **kwargs)
return wrapper
print(f'\n>>> PositiveInteger.check(-2.0) #=>')
PositiveInteger.check(-2)
print(f'\n>>> PositiveInteger.check(2.3) #=>')
PositiveInteger.check(2.3)
@checked
def gcd(a: PositiveInteger, b: PositiveInteger):
"""
Compute greatest common divisor
"""
while b:
(a, b) = (b, a % b)
return a
print(f'\n>>> gcd(21, 35) #=> {gcd(21, 35)}')
# Recall how we used this in Heathrow-to-London
class BaseMeta(type):
@classmethod
def __prepare__(mcs, *args):
return ChainMap({ }, _contracts)
def __new__(mcs, name, bases, methods):
methods = methods.maps[0]
return super().__new__(mcs, name, bases, methods)
class Base(metaclass=BaseMeta):
@classmethod
def __init_subclass__(cls):
# Apply checked decorator
for (name, val) in cls.__dict__.items():
if callable(val):
# apply @checked as a decorator to methods.
setattr(cls, name, checked(val))
# Instantiate the contracts
for (name, val) in cls.__annotations__.items():
contracts = val() # Integer()
contracts.__set_name__(cls, name)
setattr(cls, name, contracts)
def __init__(self, *args):
ann = self.__annotations__
try:
assert len(args) == len(ann), f'Expected {len(ann)} arguments '
except AssertionError:
print(f'The {len(args)} arguments {args} don\'t pair up with the \n {len(ann)} annotations {ann}')
# 3.6 - Depends on ordered dictionary
for (name, val) in zip(ann, args):
setattr(self, name, val)
def __repr__(self):
# A list comprehension whose elements are generated by a lambda expression.
# For each key in self.__annotations__ the lambda expression is executed with argument getattr(self, key)
# Note that the value of getattr(self, key) is bound to the parameter attr of the lambda expression.
strs = [ ( lambda attr: repr(attr) + ': ' + repr(type(attr)) ) (getattr(self, key))
for key in self.__annotations__]
args = ', '.join(strs)
return f'{type(self).__name__}({args})'
dx: PositiveInteger
class Player(Base):
name: NonemptyString
x: Integer
y: Integer
z: Integer
def left(self, dx):
self.x -= dx
def right(self, dx):
self.x += dx
print(Player.__annotations__.items())
print(f'\n\n>>> Player(\'Guido\', 0, 0)')
p = Player('Guido', 0, 0)
print(f'\n>>> p = Player(\'Guido\', 0, 0) #=> {p}\n')
print(f'>>> p.x = \'23\' #=> ')
p.x = '23'
print(f'>>> p.name = \'\' #=> ')
p.name = ''
print(f'>>> p.name = 123 #=> ')
p.name = 123
print(f'\n>>> p #=> {p}\n')
print('_contracts:')
for (contract, cls) in _contracts.items():
print(f'{contract}: {cls})')
print(f"\ntype.__prepare__('Player', 'Base') #=> {type.__prepare__('Player', 'Base')}")
d = BaseMeta.__prepare__('Player', 'Base')
print('\nd = BaseMeta.__prepare__(\'Player\', \'Base\')')
print(f'>>> d #=> \n {d}')
d['x'] = 23
print('>>> d[\'x\'] = 23')
d['y'] = 45
print('>>> d[\'y\'] = 45')
print(f'>>> d #=>\n {d}')<file_sep>/Functional_in_Python/Problem_3.hs
toDigit_ :: Char -> Int
toDigit_ = read . (:[])
doubleAndSum :: [Int] -> Int
doubleAndSum = snd . foldr (\i (atEvnPos, acc) -> (not atEvnPos, nextVal atEvnPos i + acc)) (False, 0)
where
nextVal:: Bool -> Int -> Int
nextVal True i = (uncurry_ (+) . (`divMod` 10) . (*2)) i
nextVal False i = i
uncurry_ :: (t2 -> t1 -> t) -> (t2, t1) -> t
uncurry_ f = \(x, y) -> f x y
myLuhn :: Int -> Bool
myLuhn = (0 ==) . (`mod` 10) . doubleAndSum . map toDigit_ . show
testCC_ :: [Bool]
testCC_ = map myLuhn [1234567890123456, 1234567890123452]
-- => [False, True]<file_sep>/Intro/parse.py
# parse.pyi
# This is the equivalent of a java interface or a C++ header
# There are classes and methods defined, but no actual code for using them.
from typing import Any, Mapping, Optional, Sequence, Tuple, Union
"""
Class: Result
@params_for_init :
fixed (Sequence of strings, e.g. list, tuple)
named (Mapping of strings to strings, e.g. dictionary)
spans (Mapping of int to a Tuple of 2 ints)
"""
class Result:
def __init__(
self,
fixed: Sequence[str],
named: Mapping[str, str],
spans: Mapping[int, Tuple[int, int]],
) -> None: ...
def __getitem__(self, item: Union[int, str]) -> str: ...
def __repr__(self) -> str: ...
"""
Function: parse
@:param
format (string)
string (string),
evaluate_result (boolean): this is a keyword parameter
case_sensitive (boolean): this is a keyword parameter
@:return
Will either return an object of type Result or None
"""
def parse(
format: str,
string: str,
evaluate_result: bool = ...,
case_sensitive: bool = ...,
) -> Optional[Result]: ...<file_sep>/Monads/RPN_calc.hs
import Data.List
---------------------- Original ----------------------
--og_solveRPN :: String -> Double
--og_solveRPN = head . foldl _foldingFunction [] . words
--
--og_foldingFunction :: [Double] -> String -> [Double]
--og_foldingFunction (x:y:ys) "*" = (x * y):ys
--og_foldingFunction (x:y:ys) "+" = (x + y):ys
--og_foldingFunction (x:y:ys) "-" = (y - x):ys
--og_foldingFunction xs numberString = read numberString:xs
-------------------- Redone with Monads ---------------------
--foldM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
--foldM f a [] = return a -- Recall that "return"
---- wraps its argument.
--foldM f a (x:xs) = f a x >>= \fax -> foldM f fax xs
---- The variable fax receives the result of executing
---- f a x and then unwrapping the result.
readMaybe :: (Read a) => String -> Maybe a
readMaybe st = case reads st of [(x,"")] -> Just x
_ -> Nothing
--foldingFunction :: [Double] -> String -> Maybe [Double]
--foldingFunction (x:y:ys) "*" = return ((x * y):ys)
--foldingFunction (x:y:ys) "+" = return ((x + y):ys)
--foldingFunction (x:y:ys) "-" = return ((y - x):ys)
--foldingFunction xs numberString = liftM (:xs) (readMaybe numberString)
--solveRPN :: String -> Maybe Double
--solveRPN st = do
-- [result] <- foldM foldingFunction [] (words st)
-- return result
<file_sep>/Operator_Precedence/Haskell/ParseState_V1Type.hs
module ParseState_V1Type (ParseState_V1) where
import DataDeclrs (Elmt)
import ParseStateClass (ParseState(..))
---------------------------------------------------------------------
-- Define ParseState_V1 to be an [Elmt] list with an index
-- indicating the start of the window.
---------------------------------------------------------------------
data ParseState_V1 = IndexAndList Int [Elmt] deriving Eq
-- Define how to perform the ParseState functions on ParseState_V1 objects
instance ParseState ParseState_V1 where
initialParseState tokens = IndexAndList 0 tokens
fromListPair (left, right) =
IndexAndList (length left) (reverse left ++ right)
toListPair (IndexAndList n list) = revfirst $ splitAt n list
where revfirst (revLeft, right) = (reverse revLeft, right)
<file_sep>/Amuse-Bouche/class_function_test.py
class Road(type):
def __str__(cls):
return cls.__name__
class Segment(metaclass=Road):
def __init__(self, dist: int):
self.dist = dist
def __str__(self):
return str(type(self))# f'{str(type(self))}/{self.dist}'
class A(Segment):
"""
Segments of the A road.
"""
class B(Segment):
""" Segments of the B road. """
class C(Segment):
""" Segments of the C road. """
<file_sep>/Monads/partC.py
from pymonad import Just, Nothing, Maybe
from typing import Callable, Any
from functools import partial, reduce
from operator import and_
def safe_sqrt(x: float) -> Maybe:
"""
Haskell:
safeSqrt :: Double -> Maybe Double
safeSqrt x
| x < 0 = Nothing
| otherwise = Just (sqrt x)
"""
return Nothing if x < 0 else Just(x ** .5)
# test_safe_sqrt* takes the 4th root of a number by applying 'safe_sqrt' twice
def test_safe_sqrt0(x: float) -> Maybe:
"""
Haskell:
testSafeSqrt0 :: Double -> Maybe Double
testSafeSqrt0 x = safeSqrt x >>= safeSqrt
"""
return safe_sqrt(x) >> safe_sqrt
def test_safe_sqrt1(x: float) -> Maybe:
"""
Haskell:
testSafeSqrt1 :: Double -> Maybe Double
testSafeSqrt1 x = do
y <- safeSqrt x
safeSqrt y
"""
y = safe_sqrt(x)
return safe_sqrt(y.getValue()) if y != Nothing else Nothing
def test_eqs(a, b):
"""
Haskell:
all :: Foldable t => (a -> Bool) -> t a -> Bool
testEq0 a b = all (lambda x -> testSafeSqrt0 x == testSafeSqrt1 x) [a .. b]
testEq1 a b = all id [testSafeSqrt0 x == testSafeSqrt1 x | x <- [a .. b]]
testEq2 a b = foldl (&&) True [testSafeSqrt0 x == testSafeSqrt1 x | x <- [a .. b]]
"""
eq1 = all((lambda x: test_safe_sqrt0(x) == test_safe_sqrt1(x))(i) for i in range(a, b))
eq2 = all(test_safe_sqrt0(x) == test_safe_sqrt1(x) for x in range(a, b))
eq3 = reduce(and_, [test_safe_sqrt0(x) == test_safe_sqrt1(x) for x in range(a, b)], True)
return eq1 and eq2 and eq3
class Infix(object):
def __init__(self, func):
self.func = func
def __ror__(self, other):
return Infix(partial(self.func, other))
def __rlshift__(self, other):
"""
Reassigns the left shift operator (<<) if the left operand does not support
the left shift operation with Infix
e.g.
self.__rlshift__(other) is called if other.__lshift__(self) returns NotImplemented.
"""
return Infix(partial(self.func, other))
def __rshift__(self, other):
"""
Reassigns the right shift operator (>>)
This applies the above partially applied function to the given parameter
"""
return self.func(other)
def __or__(self, other):
return self.func(other)
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
# Simple example use of Infix
@Infix
def add(x, y):
return x + y
def demo_add():
ex = 5 | add # 5 | add = a partially applied function: add(5, _)
print("5 | add =", ex)
print("ex(6) =", ex(6)) # add(5,6)
print("5 <<add>> 6 = ", 5 << add >> 6) # add(5, 6) = 11
# 5 << add >> 6 = add(5,6)
@Infix
def bind(f1: Callable[[Any], Maybe], f2: Callable[[Any], Maybe]) -> Callable[[Any], Maybe]:
"""
Effectively combines 2 'Maybe' functions into a new function that applies the
result of the first into the second
Haskell:
(<.>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)
f1 <.> f2 = lambda x -> f1 x >>= f2
Note:
Pymonad defines right shift (>>) as its bind operand (>>=):
(>>) = (>>=) :: Monad m => m b -> (b -> m c) -> m c
"""
return lambda x: f1(x) >> f2
def safe_root(n: int) -> Callable[[float], Maybe]:
"""
Haskell:
safeRoot :: Int -> (Double -> Maybe Double)
safeRoot n
| n == 0 = Just
| otherwise = safeSqrt <.> safeRoot (n-1)
"""
return Just if n <= 0 else safe_sqrt << bind >> safe_root(n - 1) # bind(safe_sqrt, safe_root(n-1))
# example trace: n = 1
# Infix[safe_sqrt << bind = bind(safe_sqrt, _) ] >> (safe_root(0))
# Infix( bind(safe_sqrt, _) ) >> (Just) = bind(safe_sqrt, Just)
# returns lambda x: safe_sqrt(x) >> Just
def test_safe_root(n: int) -> Maybe:
"""
Return 'Just 2' for any n >= 0
Haskell:
testSafeRoot :: Int -> Maybe Double
testSafeRoot n = (safeRoot n) (2^(2^n))
"""
return safe_root(n)(2**(2**n))
def test_safe_root_to9() -> bool:
"""
Haskell:
testSafeRootTo9 :: Bool
testSafeRootTo9 = all (== Just 2) [testSafeRoot n | n <- [0 .. 9]]
"""
return all(test_safe_root(n) == Just(2) for n in range(10))
demo_add()
print("\n\nTesting test_safe_sqrt0 and test_safe_sqrt1 (a=-2,b=4): ", test_eqs(-2, 4))
print("\n\nTest safe_root from 0->9 all equal Just(2): ", test_safe_root_to9())
<file_sep>/Operator_Precedence/gen_test.py
def is_even(i):
if i % 2 == 0:
print("ye")
yield
else:
print("no")
<file_sep>/IntroToHaskell/goldbach_conjecture.py
from itertools import takewhile
from math import sqrt
import time
"""
@:name: find_primes
@:desc: Return a list of primes that ends at the next prime past the "max" param
@:returns: list of primes (integers)
@:keyword:
max - an integer that denotes the value that must be smaller than the largest prime
@default: 2^13 (8192)
primes - list of primes that have been previously evaluated
@default: None
"""
def find_primes(max: int = 2**13, primes: [int] = None) -> [int]:
if not primes or primes == [2]:
primes = [2, 3] # default first 2 primes instead of just 2 to protect iteration later
if primes[-1] > max: # Lazy evaluation: if there exists a prime larger than the max, just return the list
return primes
_primes = primes.copy() # create a new list instead of modifying the original
i: int = _primes[-1] # start iterating at the max prime value
while _primes[-1] < max:
i += 2 # this would fail if primes = [2]
check = True
for p in _primes:
if i % p == 0:
check = False
break
if check:
_primes += [i]
return _primes
"""
@:name: is_prime
@:desc: check if a given number is prime by evaluating if it exists within a list of primes
Function exists for readability, but can be replaced by lambda function:
# is_prime = lambda x: x in primes
@:returns: boolean
@:param:
num - number being checked
primes - list of primes
"""
def is_prime(num: int, primes: [int]) -> bool:
return num in primes
"""
@:name: is_a_square
@:desc: checks if number is a perfect square
@:returns: boolean
@:param:
num - integer to be checked
"""
def is_a_square(num: int) -> bool:
return round(sqrt(num))**2 == num
"""
@:name: conjecture_test
@:desc: perform a test to check for exceptions to Goldbach's conjecture, namely
for all non-prime odd numbers g so that for each there is a prime p and integer k > 0 such that
g = p + 2 * k^2
@:returns: an empty list if the condition is met, the number 'g' in a list otherwise
@:param:
g - integer to be checked
primes - list of evaluated prime numbers
"""
def conjecture_test(g: int, primes: [int]) -> [int]:
# Taking advantage of the lazy evaluation of find_primes, primes will only ever have one element larger than g,
# so we can speed up the evaluation by simply grabbing the primes we need with indexing.
# If using a pre-loaded, large list of primes, use:
# takewhile((lambda x: x < g), primes)
# in the place of
# primes[-1]
for p in primes[:-1]:
if is_a_square((g-p)//2):
return []
return [g]
"""
@:name: goldman_conjecture
@:desc: check all non-prime odd numbers in the given range to check if they satisfy Goldbach's Conjecture
@:returns: None
@:keyword:
max_test - the maximum number to be tested against the conjecture
primes - a list of prime integers that have already been evaluated
"""
def goldbach_conjecture(max_test: int = 6000, primes: [int] = None) -> None:
odd_nums: [int] = [i for i in range(3, max_test, 2)] # Odd numbers 3 -> 10000
exceptions: [int] = [] # list of exceptions to the conjecture
for odd_num in odd_nums:
primes = find_primes(odd_num, primes)
if not is_prime(odd_num, primes): # only check non-prime odd numbers
exceptions += conjecture_test(odd_num, primes)
return exceptions
total = 0
for i in range(10):
start = time.time()
exceptions = goldbach_conjecture()
total += time.time() - start
print("Average time taken after 10 runs:", (total/10))
print("Exceptions found:", exceptions)<file_sep>/Intro/parse_name.py
# parse_name.py
import parse
"""
Function : parse_name
@param : text, a string
"""
def parse_name(text: str) -> str:
# Tuple of strings with likely formats for declaring a name
# effectively used as a regular expression
patterns = (
"my name is {name}",
"i'm {name}",
"i am {name}",
"call me {name}",
"{name}",
)
for pattern in patterns:
# If the text inputted by the user matches a pattern by comparing the
# text with the patterns
result = parse.parse(pattern, text)
# If the result is not None
# IOW, if the text matched one of the expressions
if result:
return result["name"]
return ""
answer = input("What is your name? ")
name = parse_name(answer)
print(f"Hi {name}, nice to meet you!")<file_sep>/IntroToHaskell/test.hs
-- Problem 1
-- Create a function, using partial application of functions, that sees if a single Int is divisible by 5.
-- It takes in an Int and returns a Bool.
isFactorOf :: Int -> Int -> Bool
isFactorOf num1 num2 = num1 `mod` num2 == 0
factorOf5 :: Int -> Bool
factorOf5 num = isFactorOf num 5<file_sep>/Functional_in_Python/Pyrsistent_ex.py
from pyrsistent import *
# Pvector
x = 1234124151125
vec = pvector(int(x) for x in str(x))
print(vec)
v1 = v(1, 2, 3,4,5,6,7,8)
v2 = v1.append(4)
v3 = v2.set(1, 5)
# print(v1, v2, v3, sep="\n")
# print(sum(v1[-2::-2]))
# PSet
<file_sep>/Functional_in_Python/Heathrow_To_London.hs
data Path = Path
{roads :: [Road],
dist :: Integer} deriving (Show, Eq)
data Road = Road
{ind :: Integer, -- Debugging purpose, adds index to each road added to map
size :: Integer} deriving (Show, Eq)
-- Roads can be considered to be ordered in sets of 3 as (top left : bottom left : vertical right connecting the two: [...])
data CrossRoad = CrossRoad {connections :: [Road]} deriving (Show)
test_input = [50,10,30, 5,90,20, 40,2,25, 10,8,0]
get_test_map :: [CrossRoad]
get_test_map = city_map (roads_from_input [1..] test_input) []
roads_from_input :: [Integer] -> [Integer] -> [Road]
roads_from_input __ [] = []
roads_from_input (i:ids) (inp:inputs) = (Road i inp : roads_from_input ids inputs)
city_map :: [Road] -> [CrossRoad] -> [CrossRoad]
city_map [] crossroads = crossroads
city_map (r1:r2:r3:roads) [] = city_map roads [start_A, start_B, a, b]
where start_A = CrossRoad [r1]
start_B = CrossRoad [r2]
a = CrossRoad [r1, r3]
b = CrossRoad [r2, r3]
city_map (r1:r2:r3:roads) crossroads = city_map roads (mod_prev_int ++ [a, b])
where mod_prev_int = modify_prev crossroads (r1,r2)
a= CrossRoad [r1, r3]
b = CrossRoad [r2, r3]
-- Modify the last 2 CrossRoads in the list to add roads
modify_prev :: [CrossRoad] -> (Road, Road) -> [CrossRoad]
modify_prev crosses (r1,r2) = preL ++ [mod_A, mod_B]
where mod_A = CrossRoad (connections pre_A ++ [r1])
mod_B = CrossRoad (connections pre_B ++ [r2])
(preL, pre_A, pre_B) = prev_intersect crosses
-- Return all previous CrossRoads minus the last 2, and the last 2 CrossRoads
prev_intersect :: [CrossRoad] -> ([CrossRoad], CrossRoad, CrossRoad)
prev_intersect crosses = (init $ init crosses, last $ init crosses, last crosses)
join_paths :: Path -> Path -> Path
join_paths p1 p2 = Path (roads p1 ++ (roads p2)) (dist p1 + (dist p2))
calc_path_distance :: Path -> Integer
calc_path_distance p = sum [size x | x <- roads p]
sort_paths :: [Path] -> [Path]
sort_paths (p:paths)= less ++ [p] ++ greater
where less = sort_paths $ filter (\x -> dist x < dist p) paths
greater = sort_paths $ filter (\x -> dist x >= dist p) paths
find_paths :: Intersection -> Intersection -> [Path]
find_paths start_cross end_cross =
where for_each_road =
{-
optimal_paths :: [Integer] -> [Path]
optimal_paths input =
let result = optimal_paths' $ trace ("\noptimal_paths (input):\n" ++ show input) input
in trace ("\noptimal_paths (output): " ++ show ++ "\n") result
optimal_paths' input = sort . (\(QuadPaths paths) -> paths) . combine_paths . qp_list $ input
-}<file_sep>/Operator_Precedence/Haskell/Tokenizer.hs
module Tokenizer (tokenize) where
import DataDeclrs (Elmt(..))
import Data.Map as M (fromList, lookup)
---------------------------------------------------------------------
-- These functions convert a string into a list of Elmts.
-- The main function is tokenize.
---------------------------------------------------------------------
addSpaces :: String -> String
addSpaces = foldr (\c str -> if c `elem` " 0123456789"
then c:str
else [' ', c, ' '] ++ str)
[]
-- What does makeToken assume about the input String?
-- The symbol for division is '/', but the operation performed is `div`.
-- How can you tell that from this table?
makeToken :: String -> Elmt
makeToken str =
case M.lookup str $
fromList [ ( "(", LPar), ( ")", RPar)
, ( "+", Op (+) '+' 1 'L'), ( "-", Op (-) '-' 1 'L')
, ( "*", Op (*) '*' 2 'L'), ( "/", Op div '/' 2 'L')
, ( "^", Op (^) '^' 3 'R')
] of
Just op -> op
Nothing -> Nbr (read str) -- How do we know we should perform: read str?
-- How do we know what type read returns?
tokenize :: String -> [Elmt]
tokenize string =
concat [[LPar], map makeToken . words . addSpaces $ string, [RPar]]
<file_sep>/Amuse-Bouche/my_heathrow.py
from typing import List, Tuple
from functools import reduce
class Road:
"""
Object representation of a Road with values to denote it's length and position on the map
"""
def __init__(self, distance: int, pos: str = ""):
self.distance = distance
self.position = pos
def g(self):
return f"Pos: {self.position} | Dist: {self.distance}"
class Path:
"""
Object representation of a series of roads and the distance to travel those roads
"""
def __init__(self, dist: int = 0, roads: List[Road] = None, start: str = None):
self.roads = [] if roads is None else roads
self.dist = dist
self.start = start
def __lt__(self, other):
"""
Define the "less than" function for Path:
A Path is considered less than another Path if the distance is less than the other
If they are the same, it is considered less if the number of roads in it is less than the other
:param other: the Path it is being compared to
:return: Boolean
"""
return (self.dist, len(self.roads)) < (other.dist, len(other.roads))
def __add__(self, other):
"""
Define addition for Paths
:param other: the Path it is being added
:return: A new Path with the combined distances and combined road lists as parameters
"""
return Path(self.dist + other.dist, self.roads + other.roads, start=self.start)
def all_paths(a: int, b: int, c: int) -> (Path, Path, Path, Path):
"""
:param a, b, c: Integers denoting the "distance" of the road
:return: Four Paths representing both possible routes to A (top) and B (bottom)
written as follows: (Path to A from A, Path to B from A, Path to A from B, Path to B from B)
"""
road_a = Road(a, "A")
road_b = Road(b, "B")
road_c = Road(c, "C")
return (Path(a, [road_a], start="A"),
Path(a + c, [road_a, road_c], start="A"),
Path(b + c, [road_b, road_c], start="B"),
Path(b, [road_b], start="B"))
def find_best(r_vals) -> (Path, Path):
"""
:param r_vals: A tuple containing 3 values for roads (A,B,C respectively)
:return: A tuple containing the (Optimum path to A, Optimum Path to B)
:var: (a_a, b_a, a_b, b_b) refer to the paths starting and ending locations,
e.g. a_a = start at a, end at a
"""
(a_a, b_a, a_b, b_b) = all_paths(*r_vals)
return a_a if a_a < a_b else a_b, \
b_a if b_a < b_b else b_b
def combine_paths(old_a: Path, old_b: Path, a: Path, b: Path) -> (Path, Path):
"""
:param old_a, old_b: The previous best paths to A and B, respectively
:param a, b: The local best paths to A and B in the current set of four possible paths
:return: A tuple containing the best local paths to A and B respectively combined with the best Path ending at the
best local paths' starting points
e.g. if the best local path to A starts at B, combine it with the old best path to B
"""
best_a = old_a + a if a.start == "A" else old_b + a
best_b = old_b + b if b.start == "B" else old_a + b
return best_a, best_b
def current_optimum(best: Tuple[Path, Path], r_vals: Tuple[int, int, int]) -> (Path, Path):
"""
:param best: A tuple containing the (previous best path to A, previous best path to B)
:param r_vals: A tuple containing 3 values for roads (A,B,C respectively)
:return: A tuple containing the best path from start to current to A and B, respectively
"""
return combine_paths(*best, *find_best(r_vals))
def optimal_path(inp: [int]) -> Path:
"""
:param inp: A list of numbers that is represents the distance of Roads in a series of intersections
Input is given in 3s, visualized as:
[(top road, bottom road, vertical right road connecting the other two) ...]
:return: The fastest path traversing the series of intersections
"""
inp += [0] * (len(inp) % 3) # If len(inp)%3 != 0, adds segments of length 0.
roads = zip(inp[::3], inp[1::3], inp[2::3]) # split the input into a series of tuples with 3 elements each
accumulator = (Path(start="A"), Path(start="B")) # empty paths to start the accumulator
(a, b) = reduce(current_optimum, roads, accumulator)
return a if a < b else b
def print_path(p: Path, test_num: int = 0) -> None:
"""
:param p: Path to be printed
:param test_num: The current test number
:return: None
"""
print(f"\n\nTest {test_num} results in a Path starting at {p.start} and ending at {p.roads[-1].position}\nRoads: ")
for r in p.roads:
print(r)
test_input = [50, 10, 30, 5, 90, 20, 40, 2, 25, 10, 8, 0]
test_input2 = [15, 5, 10, 10, 30, 10, 5, 20, 5, 35, 15, 20, 15, 10, 0]
op = optimal_path(test_input)
print_path(op, test_num=1)
Road.road_id = 0
print_path(optimal_path(test_input2), test_num=2)
<file_sep>/IntroToHaskell2/python-submission.py
# importing the libraries and packages used
from typing import List, Tuple, Sequence, Any, Callable, TypeVar, Union
from functools import reduce
import doctest
""" # # # # # # # # # Question 1 - My Zip With # # # # # # # # # """
# by Jeffry
# Question: If you use recursion, does the order of the clauses matter? Why or why not?
# -----------------> Unanswered. <----------------- #
T1 = TypeVar("T1")
T2 = TypeVar("T2")
T3 = TypeVar("T3")
# myZipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
# haskell code: myZipWith f (x:xs) (y:ys) = (f x y) : myZipWith f xs ys
def myZipWith (f: Callable[[T1,T2], T3], xs: Sequence[T1], ys: Sequence[T2]) -> Sequence[T3] :
"""
>>> myZipWith(lambda x, y: x + y, [1,2,3], [2,2,2])
[3, 4, 5]
"""
# what about map(f, xs, ys)
return [f(x, y) for x, y in zip(xs, ys)]
""" # # # # # # # # # Question 2 - My Foldl # # # # # # # # # """
# by Jeffry
# Question:
# Is this tail recursive. Why or why not?
# myFoldl is tail recursive since once it finishes traversing the list, it will
# immediately return the total
# Question:
# What is the relationship between the value produced by the base case and
# the initial function call? That is, assume you make a call like this:
# > myFoldl fn accInit list
# and assume that when the base case is reached it returns value
# What is the relationship (if any) between value and myFoldl fn accInit list?
# -----------------> Unanswered. <----------------- #
# myFoldl :: (a -> b -> b) -> b -> [a] -> b
# myFoldl f total (x:xs) = myFoldl f (f x total) xs
# recursion here is not tail recursive
def myFoldlN (f: Callable[[T1,T2], T2], total: T2, xs: Sequence[T1]) -> T2 :
"""
>>> myFoldlN(lambda x, y: x * y, 1, [1,2,3,4])
24
"""
if(xs):
return myFoldl(f, f(xs[0], total), xs[1:])
else:
return total
# tail recursive:
# update the total as we iterate through the xs list, return the total after we are done
def myFoldl (f: Callable[[T1,T2], T2], total: T2, xs: Sequence[T1]) -> T2 :
"""
>>> myFoldl(lambda x, y: x * y, 1, [1,2,3,4])
24
"""
for x in xs:
total = f(x, total)
return total
""" # # # # # # # # # Question 3 - My Foldr # # # # # # # # # """
# by Soo
# Question:
# Is this tail recursive. Why or why not?
# -----------------> Unanswered. <----------------- #
# Question:
# What is the relationship between the value produced by the base case
# and the initial accumulator value in the initial function call?
# -----------------> Unanswered. <----------------- #
def f(f: Callable[[Any, Any], Any], x, y):
return f(x, y)
def head(xs: Sequence) -> Any:
return xs[0] if len(xs) > 0 else []
def tail(xs: Sequence) -> Any:
return xs[1:] if len(xs) > 0 else []
def last(xs: Sequence) -> Any:
return xs[-1] if len(xs) > 0 else []
def rest(xs: Sequence) -> Any:
return xs[:-1] if len(xs) > 0 else []
def myFold1(func: Callable[[Any, Any], Any], acc, xs: Sequence) -> Any:
"""
:param func:
:param acc:
:param xs:
:return:
>>> myFold1((lambda x, y: x - y), 0, [1, 2, 3])
-6
"""
return acc if len(xs) <= 0 else \
f(func, acc, head(xs)) if len(xs) == 1 else \
myFold1(func, f(func, acc, head(xs)), tail(xs))
def myFoldr(func: Callable[[Any, Any], Any], acc, xs: Sequence) -> Any:
"""
:param func:
:param acc:
:param xs:
:return:
>>> myFoldr((lambda x, y: x - y), 0, [1, 2, 3])
0
"""
return acc if len(xs) <= 0 else \
f(func, last(xs), acc) if len(xs) == 1 else \
myFold1(func, f(func, last(xs), acc), rest(xs))
def myFoldr2(func: Callable[[Any, Any], Any], acc, xs: Sequence) -> Any:
"""
:param func:
:param acc:
:param xs:
:return:
>>> myFoldr2((lambda x, y: x - y), 0, [1, 2, 3])
0
"""
return myFold12(func, acc , xs.reverse())
def myFold12(func: Callable[[Any, Any], Any], acc, xs: Sequence) -> Any:
return acc if xs is None else \
f(func, head(xs), acc) if len(xs) == 1 else \
myFold12(func, f(func, head(xs), acc), tail(xs))
""" # # # # # # # # # Question 4 - My Cycle # # # # # # # # # """
# by Adryel
"""
Question: Such a situation would produce an infinite loop in Java. Why doesn’t this lead
to an infinite loop in Haskell? Does it lead to an infinite loop in Python?
It still produces an infinite list in Haskell, but since Haskell is lazy,
it only evaluates as far as it needs to. Thus, while the list is infinite,
Haskell will only look as far as it needs to to find the values it needs.
Python is not lazy witb recursive evaluation, so a list function would need
to terminate before the rest of the program to continue.
Question: What happens with the following? Explain why.
> cyc12 = myCycle [1,2]
-- Is this an infinite loop? What about Python? Why or why not?
This is an infinite loop in Haskell but the implementation would need
to be different in Python to allow the rest of the program to execute
but retain the intended cycle.
> take 5 cyc12
-- Does this result in an infinite loop? What about Python? Why or why not?
This does not result in an infinite loop in Haskell since the language
is lazy. It only evaluates what it needs to.
Question: Walk through the step-by-step evaluation of
> take 5 cyc12
You may assume that take is implemented as follows
take 0 _ = []
take _ [] = []
take n (x:xs) = x : take (n-1) xs
and that (++) is implemented as follows.
[] ++ ys = ys
(x:xs) ++ ys = x:(xs ++ ys)
For my purposes, I am defining myCycle as:
myCycle :: [a] -> [a]
myCycle x = x ++ myCycle x
>> cyc12 = myCycle [1,2]
>> take 5 cyc12
-> take 5 (cyc12 ++ myCycle cyc12)
-> take 5 ([1,2] ++ myCycle [1,2])
-> take 5 (1 : ([2] ++ myCycle [1,2]))
-> 1 : take 4 ([2] ++ myCycle [1,2])
-> 1 : take 4 (2 : ([] ++ myCycle [1,2]))
-> 1 : 2 : take 3 ([] ++ myCycle [1,2])
-> 1 : 2 : take 3 (myCycle [1,2])
-> 1 : 2 : take 3 ([1,2] ++ myCycle [1,2])
-> 1 : 2 : take 3 (1 : ([2] ++ myCycle [1,2]))
-> 1 : 2 : 1 : take 2 ([2] ++ myCycle [1,2])
-> 1 : 2 : 1 : take 2 (2 : ([] ++ myCycle [1,2]))
-> 1 : 2 : 1 : 2 : take 1 ([] ++ myCycle [1,2])
-> 1 : 2 : 1 : 2 : take 1 (myCycle [1,2])
-> 1 : 2 : 1 : 2 : take 1 ([1,2] ++ myCycle [1,2])
-> 1 : 2 : 1 : 2 : take 1 (1 : ([2] ++ myCycle [1,2]))
-> 1 : 2 : 1 : 2 : 1 : take 0 ([2] ++ myCycle [1,2])
-> 1 : 2 : 1 : 2 : 1 : []
** For a python equivalent of this operation, one would need to define a circular linked list for
** the operation to not end in an infinite loop
Question: Is there a Python equivalent [to using insertion sort to find the smallest element]?
If so, does it have the same time complexity?
There is an equivalent in python, but the complexity would O(n^2) since python would not evaluate it lazily. The
entire list would be sorted before pulling the first element.
"""
""" # # # # # # # # # Question 5 - Compose # # # # # # # # # """
# by Soo
# Question:
# Given g :: b -> c, f:: a -> b, and h = g `compose` f,
# what is the type of h? (Hint: the type of h is not the same as the type of compose.)
# h is type of (a -> c)
# --5
# compose :: (b -> c) -> (a -> b) -> (a -> c)
# compose g f = \x -> g ( f x )
# --test5 = compose negate (*3)
# --test5 5
# -- - 15
A = TypeVar('A')
B = TypeVar('B')
C = TypeVar('C')
def compose(g: Callable[[B],C], f: Callable[[A],B], x) -> C:
"""
:param g:
:param f:
:param x:
:return:
>>> compose((lambda x: -x),(lambda x: x*3),5)
-15
"""
return g(f(x))
""" # # # # # # # # # Question 6 - Function Pairs # # # # # # # # # """
# by Jesus
# In the following functions it was assumed that we were dealing with integers; although floats could
# also be used, it was assumed that we used integers only in order to simplify the type annotations
# All of these functions, when given a function, return a function which applies the given function
# on a list of elements, and returns a list of tuples. Each tuple follows the pattern where the first
# element is the element used to calculate the resultant when applied the given function, and the
# second element is that resultant.
# For example, if we assume that the function f() was given, then the tuple is as such: ( x , f(x) ),
# where x is an element from the given list. The resulting list, is a list of these structured tuples.
# The abbreviation 'fp' stands for function pairs
# ( Part a ) This is the function pairs implementation using the List Comprehension
def fp_list(func: Callable[[int], int]) -> Callable[[List[int]], List[Tuple[int, int]]]:
"""
>>> apply_using_list = fp_list(sqrd_plus_17)
>>> apply_using_list(range(9))
[(0, 17), (1, 18), (2, 21), (3, 26), (4, 33), (5, 42), (6, 53), (7, 66), (8, 81)]
"""
def func_on_list(a_list: List[int]) -> List[Tuple[int, int]]:
return [ (x, func(x)) for x in a_list ]
return func_on_list
# ( Part B ) This is the function pairs implementation using the map() function
def fp_map(func: Callable[[int], int]) -> Callable[[List[int]], List[Tuple[int, int]]]:
"""
>>> apply_using_map = fp_map(sqrd_plus_17)
>>> apply_using_map(range(10))
[(0, 17), (1, 18), (2, 21), (3, 26), (4, 33), (5, 42), (6, 53), (7, 66), (8, 81), (9, 98)]
"""
def func_on_list(a_list: List[int]) -> List[Tuple[int, int]]:
result: List[int] = list( map(func, a_list) )
return [ (a_list[i] , result[i]) for i in range(len(a_list)) ]
return func_on_list
# ( Part C )This is the function pairs implementation using both the zip() and map() functions
def fp_zip_and_map(func: Callable[[int], int]) -> Callable[[List[int]], List[Tuple[int, int]]]:
"""
>>> apply_using_zip_and_map = fp_zip_and_map(sqrd_plus_17)
>>> apply_using_zip_and_map(range(11))
[(0, 17), (1, 18), (2, 21), (3, 26), (4, 33), (5, 42), (6, 53), (7, 66), (8, 81), (9, 98), (10, 117)]
"""
def func_on_list(a_list: List[int]) -> List[Tuple[int, int]]:
result: List[int] = list( map(func, a_list) )
return [ x for x in zip(a_list, result) ]
return func_on_list
# ( Part D ) This is the function pairs implementation using the zip() function, but not the map() function
def fp_zip_no_map(func: Callable[[int], int]) -> Callable[[List[int]], List[Tuple[int, int]]]:
"""
>>> apply_using_only_zip = fp_zip_no_map(sqrd_plus_17)
>>> apply_using_only_zip(range(12))
[(0, 17), (1, 18), (2, 21), (3, 26), (4, 33), (5, 42), (6, 53), (7, 66), (8, 81), (9, 98), (10, 117), (11, 138)]
"""
def func_on_list(a_list: List[int]) -> List[Tuple[int, int]]:
result: List[int] = [ func(r) for r in a_list ]
return [ x for x in zip(a_list, result) ]
return func_on_list
# ( Part E & F ) This is the function pairs implementation using the
# reduce() function; the Python-equivalent foldl function from Haskell
def fp_reduce(func: Callable[[int], int]) -> Callable[[List[int]], List[Tuple[int, int]]]:
"""
>>> apply_using_reduce = fp_reduce(sqrd_plus_17)
>>> apply_using_reduce(range(13))
[(0, 17), (1, 18), (2, 21), (3, 26), (4, 33), (5, 42), (6, 53), (7, 66), (8, 81), (9, 98), (10, 117), (11, 138), (12, 161)]
"""
def func_on_list(a_list: List[int]) -> List[Tuple[int, int]]:
return reduce( ( lambda x,y: x + [ ( y , func(y) ) ] ) , a_list , [] )
return func_on_list
# This is a function that I will use for testing.
# It is the function that will be passed as a parameter to the above functions.
def sqrd_plus_17(n):
"""
>>> sqrd_plus_17(25)
642
"""
return (n ** 2) + 17
""" # # # # # # # # # Question 7 - While Loop # # # # # # # # # """
# by Jay
"""
Question: Is your while function tail recursive. Why or why not?
It is tail recursive, as the accumulator keeps updating at each recursive call of
while and it does not have to wait till the last while call to evaluate the result.
At the final call, the final result is calculated by the result extractor and
returned to the parent calls.
Question: Explain how nSquares works. What is the state? What do its components represent?
state is the accumulator on which the bodyFn performs the operation and returns the new
state. (index, list) is the form of state in this example. index keeps track of the iteration
count and list accumulates the results at each bodyFn operation.
For clarity, I will use following notations:
eval = (\(index, _) -> index <= n)
bodyFn = (\(index, list) -> (index + 1, index^2 : list))
extractRes = (reverse . snd)
> nSquares 15
while (1, []) eval bodyFn extractRes
while (bodyFn (1, [])) eval bodyFn extractRes
while (2, 1:[]) eval bodyFn extractRes
while (bodyFn (2, 1:[])) eval bodyFn extractRes
while (3, 2:1:[]) eval bodyFn extractRes
while (bodyFn (3, 2:1:[])) eval bodyFn extractRes
while (4, 3:2:1:[]) eval bodyFn extractRes
while (bodyFn (4, 3:2:1:[])) eval bodyFn extractRes
while (5, 4:3:2:1:[]) eval bodyFn extractRes
while (bodyFn (5, 4:3:2:1:[])) eval bodyFn extractRes
.
.
.
while (15, 14:13:12:11: ... :4:3:2:1:[]) eval bodyFn extractRes
while (bodyFn (15, 14:13:12:11: ... :4:3:2:1:[])) eval bodyFn extractRes
while (16, 15:14:13:12: ... :4:3:2:1:[]) eval bodyFn extractRes
extractRes (16, 15:14:13:12: ... :4:3:2:1:[])
reverse (15:14:13:12: ... :4:3:2:1:[])
reverse [15, 14, 13, ... , 3, 2, 1]
[1, 2, 3, ... , 13, 14, 15]
"""
State = TypeVar('State')
Result = TypeVar('Result')
# While loop implementation
def while_(state: State, evalFn: Callable[[State], bool] , bodyFn: Callable[[State], State], extractRes: Callable[[State], Result]) -> Result:
return while_(bodyFn(state), evalFn, bodyFn, extractRes) if evalFn(state) else extractRes(state)
# Test Example
def nSquares(n: Union[int, float]) -> [int]:
return while_(
(1, []),
lambda state: state[0] <= n,
lambda state: (state[0]+1, state[1]+[state[0]**2]),
lambda state: state[1]
)
print(nSquares(15.1))
""" # # # # # # # # # Question 8 - While Loop & Function Pairs # # # # # # # # # """
# by ?
# This is used to run the tests written in the doc strings
if __name__ == '__main__':
doctest.testmod(verbose=True)
# print(functionPairs_a((lambda x: x*x),range(1,5)))
# print(functionPairs_b((lambda x: x * x), range(1, 5)))
# print(functionPairs_c((lambda x: x * x), range(1, 5)))
# print(functionPairs_d((lambda x: x * x), range(1, 5)))
# test5 = compose((lambda x: -x),(lambda x: x*3), 5)
# print(test5)
# print(myFold1(operator.sub, 0, [1, 2, 3]))
# print(myFold1((lambda x, y : x - y), 0, [1,2,3]))
# print(myFoldr(operator.sub, 0, [1, 2, 3]))
# print(myFoldr2(operator.sub, 0, [1, 2, 3]))<file_sep>/IntroToHaskell/goldbach_conjecture.hs
{-
The assignment is to write a program to generates a sequence of numbers for which Goldbach’s other conjecture
does not hold. In other words, write programs that generate all non-prime odd numbers g so that for each there is no
prime p and integer k > 0 such that
g = p + 2 * k^2
-}
-- all Odd numbers starting from 3 -> 6000 for purposes for time trials
odd_nums :: [Integer]
odd_nums = [3,5 .. 6000]
-- all primes
primes :: [Integer]
primes = 2 : [p | p <- odd_nums, null (prev_primes p)]
where prev_primes n = [d | d <- takeWhile (\x -> x^2 <= n) primes, n `mod` d == 0]
-- Receives a list of integers and checks if any one in the list is a perfect square
isASquare :: [Integer] -> Bool
isASquare [] = False
isASquare (item:rest) = if (nearest_root item)^2 == item then True else isASquare rest
where nearest_root i = round $ sqrt $ fromInteger i
-- Checks if a number is Prime
isPrime :: Integer -> Bool
isPrime n = n `elem` (takeWhile (<=n) primes)
-- Compiles a list of numbers made by subtracting a number 'g' by every prime number smaller than it
g_test :: Integer -> [Integer]
g_test g = if isASquare [(g-p) `div` 2| p <- takeWhile (<g) primes] then [] else [g]
-- Iterates through a list of numbers and tests to see if they pass or fail Goldbach's Conjecture
-- Numbers that fail are added to a list and returned
g_iteration :: [Integer] -> [Integer]
g_iteration [] = []
g_iteration (g:remainder) = test ++ g_iteration remainder
where test = if isPrime g then [] else g_test g
-- Tests Goldbach's Conjecture against a pre-defined list of odd numbers
goldbach_conjecture :: [Integer]
goldbach_conjecture = g_iteration odd_nums<file_sep>/Intro/do_twice.py
# do_twice.py
from typing import Callable
"""
Function : do_twice
purpose : perform a callable function with a single argument twice
@:param
func (a callable function that takes a string as an argument and returns a string)
argument (string)
"""
def do_twice(func: Callable[[str], str], argument: str) -> None:
print(func(argument))
print(func(argument))
def create_greeting(name: str) -> str:
# return the string "Hello" + the name parameter
return f"Hello {name}"
do_twice(create_greeting, "Jekyll")
# >>> Hello Jekyll
# >>> Hello Jekyll
<file_sep>/Intro/temp.py
from typing import Tuple
Card = Tuple[int, int, int]
print(Card)<file_sep>/Amuse-Bouche/OperatorWrapper.py
from typing import Dict, Callable, TypeVar, List, Any
from functools import wraps
# Debug Tools
SILENT_TRACE = True
T1 = TypeVar('T1')
def trace(func: Callable[..., T1]) -> Callable[..., T1]:
"""
Print the function arguments and the type
Adapted from the @debug decorator of Hjelle, Primer on Python Decorators
(https://realpython.com/primer-on-python-decorators/#debugging-code)
"""
@wraps(func)
def wrapper_trace(*args: List[Any], **kwargs: List[Any]) -> T1:
if not SILENT_TRACE:
args_str = [str(a) for a in args]
funcType = {
'__lt__': ' < ',
'__gt__': ' > ',
'__or__': ' | ',
'__xor__': ' ^ ',
'__truediv__': ' / ',
'__and__': ' & ',
'__mod__': ' % ',
'__mul__': ' * ',
}.get(func.__name__, '')
fullArgsStr = funcType.join(args_str)
print(fullArgsStr)
value = func(*args, **kwargs)
return value
return wrapper_trace
# End Debug Tools
class Meta(type):
@trace
def __lt__(self, other):
return self._createStreak('<', other)
@trace
def __gt__(self, other):
return self._createStreak('>', other)
@trace
def __or__(self, other):
return self._createStreak('|', other)
@trace
def __xor__(self, other):
return self._createStreak('^', other)
@trace
def __truediv__(self, other):
return self._createStreak('/', other)
@trace
def __and__(self, other):
return self._createStreak('&', other)
@trace
def __mod__(self, other):
return self._createStreak('%', other)
@trace
def __mul__(self, other):
return self._createStreak('*', other)
def _createStreak(self, symbol, other):
if other is X:
return OperatorStreak([symbol])
elif isinstance(other, OperatorStreak):
return OperatorStreak([symbol]) + other
else:
return OperatorStreak([symbol], other)
class X(metaclass=Meta): # X is a placeholder name. I chose it since it is short
pass
class OperatorStreak():
def __init__(self, streak: List[str] = [], value=None):
self.streak = streak
self.value = value # Keeps track of second value of overall operator
@trace
def __lt__(self, other):
return self._performOperator('<', other)
@trace
def __gt__(self, other):
return self._performOperator('>', other)
@trace
def __or__(self, other):
return self._performOperator('|', other)
@trace
def __xor__(self, other):
return self._performOperator('^', other)
@trace
def __truediv__(self, other):
return self._performOperator('/', other)
@trace
def __and__(self, other):
return self._performOperator('&', other)
@trace
def __mod__(self, other):
return self._performOperator('%', other)
@trace
def __mul__(self, other):
return self._performOperator('*', other)
def _performOperator(self, symbol, other):
self.streak.append(symbol)
if isinstance(other, OperatorStreak):
return self + other
else:
return OperatorStreak(self.streak, other)
def __add__(self, other): # Other must be of type OperatorStreak
return OperatorStreak(self.streak + other.streak, other.value) # Value should never come from left side
def reset(self):
self.streak = []
self.value = None
def append(self, val):
self.streak.append(val)
class MyWrapper():
# This is a map of all operators to their functions
# To make this simple, I only selected these 3 operators
# This Wrapper can be made more complex by adding the rest of the one character operators
# or attempting to implement two character operators
operators = {
'<': '__lt__',
'>': '__gt__',
'|': '__or__',
'^': '__xor__',
'/': '__truediv__',
'&': '__and__',
'%': '__mod__',
'*': '__mul__',
}
def __init__(self, cls):
self.wrappedClass = cls
self.types = cls.types if hasattr(cls, 'types') else {} # Set for quick lookup if a valid operator was found
self.streak = OperatorStreak()
def __call__(self, value):
self.wrapped = self.wrappedClass(value)
return self
def __getattr__(self, attr):
if callable(attr):
return self.attr
else:
return self.wrapped.__getattribute__(attr)
@trace
def __lt__(self, other):
return self._performOperator('<', other)
@trace
def __gt__(self, other):
return self._performOperator('>', other)
@trace
def __or__(self, other):
return self._performOperator('|', other)
@trace
def __xor__(self, other):
return self._performOperator('^', other)
@trace
def __truediv__(self, other):
return self._performOperator('/', other)
@trace
def __and__(self, other):
return self._performOperator('&', other)
@trace
def __mod__(self, other):
return self._performOperator('%', other)
@trace
def __mul__(self, other):
return self._performOperator('*', other)
def _performOperator(self, symbol, other):
operator = self.operators[symbol]
# Keeps track of streak of operators
self.streak.append(symbol)
# Check if we have matched an operator
def testOperator():
myOperator = ''.join(self.streak.streak)
return myOperator in self.types
if other is X:
return self
# Combines streaks of operators (if weird order of operations)
elif isinstance(other, OperatorStreak):
self.streak = self.streak + other
# Value will be given from other
if self.streak.value:
if testOperator():
return self._runOperator()
else:
raise Exception ("Invalid Operator")
return self
else:
# Attempt to correctly execute some operator
# We already attempted to use our operator and failed
self.streak.value = other
if testOperator():
return self._runOperator()
elif(self.streak.streak):
raise Exception ("Invalid Operator")
else:
# Performs Operator Normally
return self.wrapped.__getattribute__(operator)(other) # Int does not have __dict__ atr?
def _runOperator(self):
operator = ''.join(self.streak.streak)
value = self.streak.value
# Resets Streak
self.streak.reset()
return self.types[operator](self.wrapped, value)<file_sep>/Operator_Precedence/Python/Tokenizer.py
from Operator_Precedence.Python.DataDeclrs import *
def add_spaces(s: str) -> str:
return " ".join(s.replace(" ", ""))
"""
-- What does makeToken assume about the input String?
-- The symbol for division is '/', but the operation performed is `div`.
-- How can you tell that from this table?
makeToken :: String -> Elmt
makeToken str =
case M.lookup str $
fromList [ ( "(", LPar), ( ")", RPar)
, ( "+", Op (+) '+' 1 'L'), ( "-", Op (-) '-' 1 'L')
, ( "*", Op (*) '*' 2 'L'), ( "/", Op div '/' 2 'L')
, ( "^", Op (^) '^' 3 'R')
] of
Just op -> op
Nothing -> Nbr (read str) -- How do we know we should perform: read str?
-- How do we know what type read returns?
"""
def make_token(s: str) -> Elmt:
pass
<file_sep>/Monads/partB2.py
from typing import Callable, TypeVar, List, Union, Tuple, Any
from pymonad import Monad, Just, Maybe, Nothing
from operator import mul, add, sub
T1 = TypeVar('T1')
T2 = TypeVar('T2')
def foldM(f: Callable[[T1, T2], Monad], acc: T1, xs: List[T2]) -> Monad:
"""
foldM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
foldM f a [] = return a
foldM f a (x:xs) = f a x >>= lambda fax -> foldM f fax xs
"""
return Just(acc) if not xs else f(acc, xs) >> (lambda fax: foldM(f, fax, xs))
"""
readMaybe :: (Read a) => String -> Maybe a
readMaybe st = case reads st of [(x,"")] -> Just x
_ -> Nothing
"""
def read_maybe(item: str) -> Maybe:
pass
# return Just() if _ else Nothing
"""
foldingFunction :: [Double] -> String -> Maybe [Double]
foldingFunction (x:y:ys) "*" = return ((x * y):ys)
foldingFunction (x:y:ys) "+" = return ((x + y):ys)
foldingFunction (x:y:ys) "-" = return ((y - x):ys)
foldingFunction xs numberString = liftM(:xs)(readMaybe
numberString)
"""
def folding_function(xs: List[float], op: str) -> Maybe:
operations = {"*": mul, "+": add, "-": sub}
if xs:
(x, y, *ys) = xs
return Just((operations[op](x, y))+ys)
<file_sep>/Operator_Precedence/Python/DataDeclrs.py
class ExprTree:
def __eq__(self, other):
return False
class Elmt:
def __eq__(self, other):
return False
class Optr:
def __init__(self, f, c):
self.f = f
self.c = c
def __eq__(self, other):
return self.c == other.c
class ExprLeaf(ExprTree):
def __init__(self, n):
self.n = n
def __str__(self):
return self.n
def __eq__(self, other):
return self.n == other.n
class ExprNode(ExprTree):
def __init__(self, tree1, optr, tree2):
self.e1 = tree1
self.op = optr
self.e2 = tree2
def __str__(self):
return f"({self.e1},{[self.op.c]},{self.e2})"
def __eq__(self, other):
return self.e1 == other.e1 and self.op == other.op and self.e2 == other.e2
class Error(ExprTree):
def __init__(self, elems: [Elmt]):
self.elems = elems
def __str__(self):
return "Error"
class Nbr(Elmt):
def __init__(self, num: int):
self.num = num
def __str__(self):
return self.num
def __eq__(self, other):
return self.num == other.num
class LPar(Elmt):
def __str__(self):
return "("
def __eq__(self, other):
return True
class RPar(Elmt):
def __str__(self):
return ")"
def __eq__(self, other):
return True
class Op(Elmt):
def __init__(self, func, c1, i, c2):
self.f = func
self.c1 = c1
self.i = i
self.c2 = c2
def __str__(self):
return [self.c1]
def __eq__(self, other):
return self.c1 == other.c1
class Expr(Elmt):
def __init__(self, expr_tree: ExprTree):
self.expr_tree = expr_tree
def __str__(self):
return self.expr_tree
def __eq__(self, other):
return self.expr_tree == other.expr_tree
def eval_expr(exp_tree: ExprTree) -> int:
instance = {
ExprLeaf: lambda e: e.n,
ExprNode: lambda e: e.op(eval_expr(e.e1), eval_expr(e.e2)),
Error: None
}
return instance[exp_tree.__class__](exp_tree)
def to_expr_tree(elem: Elmt) -> ExprTree:
instance = {
Nbr: lambda e: ExprLeaf(e.num),
Expr: lambda e: e.expr_trees
}
return instance[elem.__class__](elem)
def wrapped_expr_tree(e1: Expr, e2: Op, e3: Expr) -> Elmt:
return Expr(ExprNode(to_expr_tree(e1), Optr(e2.f, e2.c1), to_expr_tree(e3)))
<file_sep>/Intro/cosine.py
# cosine.py
import numpy as np
"""
Function : print_cosine
purpose : print the cosine of the array into the console
@:param
x (an n-dimensional array from numpy)
"""
def print_cosine(x: np.ndarray) -> None:
with np.printoptions(precision=3, suppress=True):
print(np.cos(x))
x = np.linspace(0, 2 * np.pi, 9)
print_cosine(x)<file_sep>/Operator_Precedence/Haskell/DataDeclrs.hs
module DataDeclrs
( Elmt(..) -- Export all the Elmt constructors.
, evalExpr
, ExprTree(Error, ExprNode)
, Optr(..)
, toExprTree
, wrappedExprTree
) where
---------------------------------------------------------------------
-- Data declarations.
---------------------------------------------------------------------
-- These are elements in the sequence to be (and being) parsed.
data Elmt = Nbr Int
| LPar
| RPar
| Op (Int -> Int -> Int) Char Int Char
| Expr ExprTree
-- These are constructors for the parse Tree. During
-- the parse they are wrapped in Expr elements
data ExprTree = ExprLeaf Int
| ExprNode ExprTree Optr ExprTree
| Error [Elmt]
-- Represents operators in the parse tree.
data Optr = Optr (Int -> Int -> Int) Char
evalExpr :: ExprTree -> Int
evalExpr (ExprLeaf n) = n
evalExpr (ExprNode e1 (Optr op _) e2) = (evalExpr e1) `op` (evalExpr e2)
evalExpr (Error elmts) = -1 -- Would prefer NaN, but it's not an Int.
toExprTree :: Elmt -> ExprTree
toExprTree (Nbr n) = ExprLeaf n
toExprTree (Expr exprTree) = exprTree
wrappedExprTree :: Elmt -> Elmt -> Elmt -> Elmt
wrappedExprTree e1 (Op fn char _ _) e2 =
Expr (ExprNode (toExprTree e1) (Optr fn char) (toExprTree e2))
instance Show Elmt where
show LPar = "("
show RPar = ")"
show (Nbr n) = show n
show (Op _ c _ _) = [c] -- Assume every operator is one character.
show (Expr exprTree) = show exprTree
instance Show ExprTree where
show (ExprLeaf n) = show n
show (ExprNode e1 (Optr _ c) e2)
= concat["(", show e1, [c], show e2, ")"]
show (Error elmts) =
"Error:" ++ tail (foldr (\s acc -> ", " ++ show s ++ acc) "" elmts)
instance Eq Elmt where
Nbr n1 == Nbr n2 = n1 == n2
LPar == LPar = True
RPar == RPar = True
Op _ c1 _ _ == Op _ c2 _ _ = c1 == c2
Expr exprTree1 == Expr exprTree2
= exprTree1 == exprTree2
_ == _ = False
instance Eq ExprTree where
ExprLeaf n1 == ExprLeaf n2 = n1 == n2
ExprNode e11 optr1 e12 == ExprNode e21 optr2 e22
= e11 == e21
&& optr1 == optr2
&& e12 == e22
_ == _ = False
instance Eq Optr where
(Optr _ c1) == (Optr _ c2) = c1 == c2
<file_sep>/IntroToHaskell2/final-haskell-submission.hs
-- # # # # # # # # # Question 1 - My Zip With # # # # # # # # # --
-- by Jeffry
myZipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
myZipWith _ [] _ = []
myZipWith _ _ [] = []
-- not tail recursive
myZipWith f (x:xs) (y:ys) = (f x y) : myZipWith f xs ys
-- tail recursive, set up '.
myZipWithTail' :: (a -> b -> c) -> [a] -> [b] -> [c] -> [c]
myZipWithTail' _ [] _ orev = reverse orev
myZipWithTail' _ _ [] orev = reverse orev
myZipWithTail' f (x:xs) (y:ys) output = myZipWithTail' f xs ys $ f x y : output
myZipWithTail :: (a -> b -> c) -> [a] -> [b] -> [c]
myZipWithTail f (x:xs) (y:ys) = myZipWithTail' f (x:xs) (y:ys) []
-- tests
--myZipWith (*) [1,2,3] [1,2,3]
--myZipWithTail (*) [1,2,3] [1,2,3]
-- # # # # # # # # # Question 2 - My Foldl # # # # # # # # # --
-- by Jeffry
-- takes in a f accumilator list
-- iterates the f and returns the final accumilator, its reduce function on other languages
-- foldl traverses the list from left to right
-- myFoldl is tail recursive since once it finishes traversing the list, it will immediately return the total
myFoldl :: (a -> b -> b) -> b -> [a] -> b
myFoldl _ total [] = total
myFoldl f total (x:xs) = myFoldl f (f x total) xs
-- test: myFoldl (+) 0 [1 .. 4], replace + with any operator
-- # # # # # # # # # Question 3 - My Foldr # # # # # # # # # --
-- by Soo
--3
--Recursive version
--Not tail recursive
myFoldr :: (a -> b -> b) -> b -> [a] -> b
myFoldr f accInit [] = accInit
myFoldr f acc (x:xs) = f x (myFoldr f acc xs)
--myFoldr (+) 0 [1 .. 4]
--10
--Reverse and foldl
myFlip [] = []
myFlip (x:xs) = (myFlip xs) ++ [x]
--myFoldr2 :: (a -> b -> b) -> b -> [a] -> b
myFoldr2 f accInit [] = accInit
myFoldr2 f acc xs = myFoldl2 f acc (myFlip xs)
myFoldl2 f accInit [] = accInit
myFoldl2 f acc (x:xs) = myFoldl2 f (f x acc) xs
--myFoldr2 (+) 0 [1 .. 4]
--10
-- # # # # # # # # # Question 4 - My Cycle # # # # # # # # # --
-- by Adryel
{-
Question: Such a situation would produce an infinite loop in Java. Why doesn’t this lead
to an infinite loop in Haskell? Does it lead to an infinite loop in Python?
It still produces an infinite list in Haskell, but since Haskell is lazy,
it only evaluates as far as it needs to. Thus, while the list is infinite,
Haskell will only look as far as it needs to to find the values it needs.
Python is not lazy witb recursive evaluation, so a list function would need
to terminate before the rest of the program to continue.
Question: What happens with the following? Explain why.
> cyc12 = myCycle [1,2]
-- Is this an infinite loop? What about Python? Why or why not?
This is an infinite loop in Haskell but the implementation would need
to be different in Python to allow the rest of the program to execute
but retain the intended cycle.
> take 5 cyc12
-- Does this result in an infinite loop? What about Python? Why or why not?
This does not result in an infinite loop in Haskell since the language
is lazy. It only evaluates what it needs to.
Question: Walk through the step-by-step evaluation of
> take 5 cyc12
You may assume that take is implemented as follows
take 0 _ = []
take _ [] = []
take n (x:xs) = x : take (n-1) xs
and that (++) is implemented as follows.
[] ++ ys = ys
(x:xs) ++ ys = x:(xs ++ ys)
For my purposes, I am defining myCycle as:
myCycle :: [a] -> [a]
myCycle x = x ++ myCycle x
>> cyc12 = myCycle [1,2]
>> take 5 cyc12
-> take 5 (cyc12 ++ myCycle cyc12)
-> take 5 ([1,2] ++ myCycle [1,2])
-> take 5 (1 : ([2] ++ myCycle [1,2]))
-> 1 : take 4 ([2] ++ myCycle [1,2])
-> 1 : take 4 (2 : ([] ++ myCycle [1,2]))
-> 1 : 2 : take 3 ([] ++ myCycle [1,2])
-> 1 : 2 : take 3 (myCycle [1,2])
-> 1 : 2 : take 3 ([1,2] ++ myCycle [1,2])
-> 1 : 2 : take 3 (1 : ([2] ++ myCycle [1,2]))
-> 1 : 2 : 1 : take 2 ([2] ++ myCycle [1,2])
-> 1 : 2 : 1 : take 2 (2 : ([] ++ myCycle [1,2]))
-> 1 : 2 : 1 : 2 : take 1 ([] ++ myCycle [1,2])
-> 1 : 2 : 1 : 2 : take 1 (myCycle [1,2])
-> 1 : 2 : 1 : 2 : take 1 ([1,2] ++ myCycle [1,2])
-> 1 : 2 : 1 : 2 : take 1 (1 : ([2] ++ myCycle [1,2]))
-> 1 : 2 : 1 : 2 : 1 : take 0 ([2] ++ myCycle [1,2])
-> 1 : 2 : 1 : 2 : 1 : []
** For a python equivalent of this operation, one would need to define a circular linked list for
** the operation to not end in an infinite loop
Question: Is there a Python equivalent [to using insertion sort to find the smallest element]?
If so, does it have the same time complexity?
There is an equivalent in python, but the complexity would O(n^2) since python would not evaluate it lazily. The
entire list would be sorted before pulling the first element.
-}
-- # # # # # # # # # Question 5 - Compose # # # # # # # # # --
-- by Soo
--5
-- h is type of (a -> c)
compose :: (b -> c) -> (a -> b) -> (a -> c)
compose g f = \x -> g ( f x )
--test5 = compose negate (*3)
--test5 5
-- - 15
-- # # # # # # # # # Question 6 - Function Pairs # # # # # # # # # --
-- by Jesus
{-
Question 6 - Function Pairs
-}
{-
For these functions, you can use either integers or floats
All of these functions, when given a function, return a function which applies the given function
on a list of elements, and returns a list of tuples. Each tuple follows the pattern where the first
element is the element used to calculate the resultant when applied the given function, and the
second element is that resultant.
For example, if we assume that the function f() was given, then the tuple is as such: ( x , f(x) ),
where x is an element from the given list. The resulting list, is a list of these structured tuples.
-}
-- ( Part a ) This is the function pairs implementation using the List Comprehension --
funcPairsList :: (Num a) => (a -> a) -> [a] -> [(a, a)]
funcPairsList func list = [(x, func x) | x <- list]
-- ( Part B ) This is the function pairs implementation using the map function --
funcPairsMap :: (Eq a) => (Num a) => (a -> a) -> [a] -> [(a, a)]
funcPairsMap func list = [(x,y) | x <- list, y <- map func list, y == func x ]
-- ( Part C )This is the function pairs implementation using both the zip and map functions --
funcPairsMapAndZip :: (Num a) => (a -> a) -> [a] -> [(a, a)]
funcPairsMapAndZip func list = zip list $ map func list
-- ( Part D ) This is the function pairs implementation using the zipWith func, but not the map func --
funcPairsZipWith :: (Num a) => (a -> a) -> [a] -> [(a, a)]
funcPairsZipWith func list = zipWith f list list
where f x _ = (x, func x)
-- ( Part E ) This is the function pairs implementation using the foldr function --
funcPairsFoldr :: (Num a) => (a -> a) -> [a] -> [(a, a)]
funcPairsFoldr func list = foldr ( \x acc -> (x, func x) : acc ) [] list
-- ( Part F ) This is the function pairs implementation using the foldl function --
funcPairsFoldl :: (Num a) => (a -> a) -> [a] -> [(a, a)]
funcPairsFoldl func list = foldl ( \acc x -> acc ++ [(x, func x)] ) [] list
-- This function will be used for testing
sqrdPlus17 :: Num a => a -> a
sqrdPlus17 n = (n^2) + 17
-- Using the following functions for testing, type into ghci the line that is commented --
applyUsingList = funcPairsList sqrdPlus17
-- applyUsingList [1..8]
applyUsingMap = funcPairsMap sqrdPlus17
-- applyUsingMap [1..9]
applyUsingMapAndZip = funcPairsMapAndZip sqrdPlus17
-- applyUsingMapAndZip [1..10]
applyUsingZipWith = funcPairsZipWith sqrdPlus17
-- applyUsingZipWith [1..11]
applyUsingFoldr = funcPairsFoldr sqrdPlus17
-- applyUsingFoldr [1..12]
applyUsingFoldl = funcPairsFoldl sqrdPlus17
-- applyUsingFoldl [1..13]
-- # # # # # # # # # Question 7 - While Loop # # # # # # # # # --
-- by Jay
{-
Question: Is your while function tail recursive. Why or why not?
It is tail recursive, as the accumulator keeps updating at each recursive call of
while and it does not have to wait till the last while call to evaluate the result.
At the final call, the final result is calculated by the result extractor and
returned to the parent calls.
Question: Explain how nSquares works. What is the state? What do its components represent?
state is the accumulator on which the bodyFn performs the operation and returns the new
state. (index, list) is the form of state in this example. index keeps track of the iteration
count and list accumulates the results at each bodyFn operation.
For clarity, I will use following notations:
eval = (\(index, _) -> index <= n)
bodyFn = (\(index, list) -> (index + 1, index^2 : list))
extractRes = (reverse . snd)
> nSquares 15
while (1, []) eval bodyFn extractRes
while (bodyFn (1, [])) eval bodyFn extractRes
while (2, 1:[]) eval bodyFn extractRes
while (bodyFn (2, 1:[])) eval bodyFn extractRes
while (3, 2:1:[]) eval bodyFn extractRes
while (bodyFn (3, 2:1:[])) eval bodyFn extractRes
while (4, 3:2:1:[]) eval bodyFn extractRes
while (bodyFn (4, 3:2:1:[])) eval bodyFn extractRes
while (5, 4:3:2:1:[]) eval bodyFn extractRes
while (bodyFn (5, 4:3:2:1:[])) eval bodyFn extractRes
.
.
.
while (15, 14:13:12:11: ... :4:3:2:1:[]) eval bodyFn extractRes
while (bodyFn (15, 14:13:12:11: ... :4:3:2:1:[])) eval bodyFn extractRes
while (16, 15:14:13:12: ... :4:3:2:1:[]) eval bodyFn extractRes
extractRes (16, 15:14:13:12: ... :4:3:2:1:[])
reverse (15:14:13:12: ... :4:3:2:1:[])
reverse [15, 14, 13, ... , 3, 2, 1]
[1, 2, 3, ... , 13, 14, 15]
-}
-- While loop implementation
while :: state -> (state -> Bool) -> (state -> state) -> (state -> result) -> result
while state eval bodyFn extractRes
| eval state = while (bodyFn state) eval bodyFn extractRes
| otherwise = extractRes state
-- Test Example
nSquares:: Int -> [Int]
nSquares n =
while (1, [])
(\(index, _) -> index <= n) -- n is the nSquares argument.
(\(index, list) -> (index + 1, index^2 : list))
(reverse . snd) -- Extract the second element of
-- the tuple and reverse it.
-- test : nSquares 15 -> OP : [1,4,9,16,25,36,49,64,81,100,121,144,169,196,225]
-- # # # # # # # # # Question 8 - While Loop & Function Pairs # # # # # # # # # --
-- by Soo & Jeffry
myMap3 :: (a -> b) -> [a] -> [b]
myMap3 f xs =
while (1, xs, [])
(\(i, _, _) -> i <= n)
(\(i, (x:xs), list) -> (i+1,xs, f x:list ))
(\(_, _, list) -> reverse list)
where n = length xs
-- test
-- main = do print $ myMap3 (+1) [1, 3 .. 15]
myWhileFoldl :: (b -> a -> b) -> b -> [a] -> b
myWhileFoldl f total xs =
while (1, xs, total)
(\(i, _, _) -> i <= n)
(\(i, (x:xs), total) -> (i+1,xs, f total x))
(\(_, _, total) -> total)
where n = length xs
-- main = do print $ myWhileFoldl (*) 1 [1, 2 .. 5]
--8 c
--Fibonacci number
nFibs n =
while (1, 1, 1, [1, 1])
(\(index, _, _, _ ) -> index <= (n - 2))
(\(index, first, second, list) -> (index + 1, second, first + second, first + second : list))
(\(_,_,_,list) -> reverse list )
--8 d
--Primes number
--8 d
--sieve of Eratosthenes
smallPrimeDivisors n primes = [d | d <- primes, n `mod` d == 0]
isPrime n primes = null (smallPrimeDivisors n primes)
nextPrime p primes
| isPrime p primes = p
| otherwise = nextPrime (p + 1) primes
nPrimes n =
while (1, 2, [])
(\(index, _, _) -> index <= n)
(\(index, p, list) -> (index + 1, (nextPrime p list), (nextPrime p list) : list))
(\(_, _, list) -> reverse list)
--next_state (nums, primes) = (filter (\x -> x `mod` (head nums) == 0) nums, head nums : primes )<file_sep>/Amuse-Bouche/heathrow_to_london.hs
module Main where
-- import Data.Function (on)
import Data.List (intersperse, sort)
-- trace is used to display the input and output of functions.
import Debug.Trace
-- By convention, modules should have a main function,
-- which is how the code in the module starts on its own.
-- Alternatively, one can call optimalPaths directly from the prompt.
main = do putStrLn . show . optimalPaths $ [50, 10, 30, 5, 90, 20, 40, 2, 25, 10, 8]
-- The A side, the B side, or a Crossover.
data Label = A | B | C deriving (Eq, Show)
-- A Step is a transition from one intersection to another.
-- It is on the A or B side, or it's a crossover. In all
-- cases it has an associated distance.
data Step = Step Label Int
-- Define how show runs on a Step. Makes Step an instance of the Show typeclass.
instance Show Step where
show (Step lbl dist) = show lbl ++ "/" ++ show dist
-- A Path is a sequence of Steps.
data Path = Path [Step]
-- The distance for a Path is the sum of the Step distances.
dist :: Path -> Int
dist (Path steps) = sum $ map (\(Step _ d) -> d) steps
-- The following is also correct.
-- dist (Path steps) = foldl (\sum (Step _ d) -> sum+d) 0 steps
-- measureOfMerit is a metric for how good a path is. The
-- shorter the distance the better. If two Paths have the
-- same distance, fewer steps is better.
measureOfMerit :: Path -> (Int, Int)
measureOfMerit p@(Path steps) = (dist p, length steps)
-- Two Paths are equal if their measures of merit are equal.
instance Eq Path where
(==) = (==) `on` measureOfMerit
-- This says that Paths can be compared.
-- Compare paths by comparing their measures of merit.
instance Ord Path where
compare = compare `on` measureOfMerit
-- Instead of importing it from Data.Function, this is how `on` works.
-- E.g., compare = compare `on` measureOfMerit means that when comparing
-- two elements apply measureOfMerit to each and then compare those results.
-- In this case f1 is compare; f2 is measureOfMerit
on :: (b -> b -> c) -> (a -> b) -> (a -> a -> c)
f1 `on` f2 = \x y -> f1 (f2 x) (f2 y)
-- The start of a path is the label of the first step.
start :: Path -> Label
start (Path (Step label _ : _)) = label
-- If the label of the last step is A or B, that's the
-- value for end. If the last step is C, the path ends
-- at the opposite of the previous step.
end :: Path -> Label
end (Path steps) =
case reverse steps of
Step C _ : rest -> case rest of Step A _ : _ -> B
Step B _ : _ -> A
Step lastLbl _ : _ -> lastLbl
-- Define show on Path.
-- Notice that each Path string starts on a new line.
instance Show Path where
show p@(Path steps) =
"\n" ++ show (start p) ++ "->" ++ show (end p)
++ ". Dist: " ++ show (dist p) ++ ". "
++ (concat . intersperse ", " . map show) steps
-- Can two paths be joined, i.e., does the first one end
-- where the second one starts? Use a new infix operator,
-- which can be defined on the fly.
(>?<) :: Path -> Path -> Bool
p1 >?< p2 = end p1 == start p2
-- Extend one path by another by appending their Steps.
-- Should not be used unless the Paths can be joined.
(+>) :: Path -> Path -> Path
-- A guard may be used to check the >?< constraint.
p1@(Path steps1) +> p2@(Path steps2)
| p1 >?< p2 = Path (steps1 ++ steps2)
| otherwise = error ("Attempt to join " ++ show (end p1)
++ " to " ++ show (start p2) ++ " in "
++ show p1 ++ " +> " ++ show p2 ++ "\n")
-- A QuadPaths object always has exactly 4 paths connecting from
-- one cross link to another. It has the four optimal paths for:
-- A-to-A, A-to-B, B-to-A, B-to-B.
data QuadPaths = QuadPaths [Path] deriving Show
-- Join two Quadpaths by joining the paths that fit and selecting
-- the best path for each start-end combination. This is another new infix operator.
-- E.g. A-to-B can be either A-to-A +> A-to-B or A-to-B +> B-to-B.
(++>) :: QuadPaths -> QuadPaths -> QuadPaths
(QuadPaths paths1) ++> (QuadPaths paths2) =
let result = trace ("\njoin (input):\n" ++ show (QuadPaths paths1) ++ show (QuadPaths paths2))
join (QuadPaths paths1) (QuadPaths paths2)
in trace ("\njoin (output):\n" ++ show result ++ "\n") result
join (QuadPaths paths1) (QuadPaths paths2) =
QuadPaths [ bestPath s e | s <- [A, B], e <- [A, B]] where
bestPath :: Label -> Label -> Path
bestPath s e = minimum [p1 +> p2 | p1 <- paths1, s == start p1,
p2 <- paths2, e == end p2,
p1 >?< p2]
-- An alternative formuation:
-- QuadPaths (map bestWithStartEnd [(A, A), (A, B), (B, A), (B, B)])
-- where bestWithStartEnd :: (Label, Label) -> Path
-- bestWithStartEnd (s, e) =
-- minimum [p1 +> p2 | p1 <- paths1, s == start p1,
-- p2 <- paths2, e == end p2,
-- p1 >?< p2]
-- Input to the overall problem is given as a list of Ints. The
-- list should be understood as sequences of three Steps.
-- Each 3-Step sequence is (a) the distance along the A road,
-- (b) the distance along the B road, and (c) the distance of the
-- crossover that connects the ends of the two roads.
-- The problem is to find all 4 shortest paths from Heathrow
-- to London. When sorted the head is the minimum.
-- The program first uses qpList to convert the initial int list into
-- a sequence of QuadPaths. Then it uses combinePaths to combine
-- the list of QuadPaths into a single QuadPath. Then it sorts the
-- paths in that QuadPath.
optimalPaths :: [Int] -> [Path]
optimalPaths input =
let result = optimalPaths' $ trace ("\noptimalPaths (input):\n" ++ show input) input
in trace ("\noptimalPaths (output):\n" ++ show result ++ "\n") result
optimalPaths' = sort . (\(QuadPaths paths) -> paths) . combinePaths . qpList
-- where
-- combinePaths glues a list of QuadPaths objects together.
-- Gluing two QuadPaths together produces a QuadPaths object
-- with four optimum paths (A-to-A, A-to-B, B-to-A, B-to-B)
-- over the distance of the two objects together. (See ++>.)
-- Any of the following versions of combinePaths works.
-- combinePaths :: [QuadPaths] -> QuadPaths
-- combinePaths = foldl1 (++>)
-- combinePaths :: [QuadPaths] -> QuadPaths
-- combinePaths = foldr1 (++>)
-- The following version is longer, but it lends itself to
-- parallel processing. It also illustrates that the sequence
-- in which the QuadPaths objects are glued together doesn't
-- matter.
--
-- Split the QuadPaths list into two lists; combine the
-- QuadPaths in each list; combine the two results.
combinePaths :: [QuadPaths] -> QuadPaths
combinePaths qps =
let result = combinePaths' $ trace ("\ncombinePaths (input):\n" ++ show qps) qps
in trace ("\ncombinePaths (output):\n" ++ show result ++ "\n") result
combinePaths' (qp : qps) = foldl (++>) qp qps
-- combinePaths' [qp] = qp
-- combinePaths' [qp1, qp2] = qp1 ++> qp2
-- combinePaths' qps = combinePaths leftQPs ++> combinePaths rightQPs
-- where (leftQPs, rightQPs) = splitAt (length qps `div` 2) qps
-- Read the inputs 3 at a time and make a QuadPaths of each group.
-- Each QuadPaths object is the 4 paths for a segment.
qpList :: [Int] -> [QuadPaths]
qpList list =
let result = qpList' $ trace ("\nqpList (input):\n" ++ show list) list
in trace ("\nqpList (output):\n" ++ show result ++ "\n") result
qpList' (aDist : bDist : cDist : rest) =
QuadPaths [ Path [Step A aDist], -- A to A
Path [Step A aDist, Step C cDist], -- A to B
Path [Step B bDist, Step C cDist], -- B to A
Path [Step B bDist] -- B to B
] : qpList' rest
qpList' [] = []
-- What to do if the number of input elements is not a multiple of 3.
-- These are arbitrary decisions.
qpList' [aDist, bDist] = qpList' [aDist, bDist, 0]
qpList' [xDist] = qpList' [xDist, xDist, 0]
{-
Test using the example in the book.
> optimalPaths [50, 10, 30, 5, 90, 20, 40, 2, 25, 10, 8]
[
B->B. Dist: 75. B/10, C/30, A/5, C/20, B/2, B/8,
B->A. Dist: 75. B/10, C/30, A/5, C/20, B/2, B/8, C/0,
A->B. Dist: 85. A/50, A/5, C/20, B/2, B/8,
A->A. Dist: 85. A/50, A/5, C/20, B/2, B/8, C/0]
Why does changing the second crossover from 15 to 14 in
the following examples cause the shortest path to take
the first crossover?
> optimalPaths [10, 50, 30, 50, 5, 15, 2, 40, 0, 10, 5]
[
A->B. Dist: 67. A/10, A/50, A/2, C/0, B/5,
A->A. Dist: 67. A/10, A/50, A/2, C/0, B/5, C/0,
B->B. Dist: 77. B/50, B/5, C/15, A/2, C/0, B/5,
B->A. Dist: 77. B/50, B/5, C/15, A/2, C/0, B/5, C/0]
> optimalPaths [10, 50, 30, 50, 5, 14, 2, 40, 0, 10, 5]
[
A->B. Dist: 66. A/10, C/30, B/5, C/14, A/2, C/0, B/5,
A->A. Dist: 66. A/10, C/30, B/5, C/14, A/2, C/0, B/5, C/0,
B->B. Dist: 76. B/50, B/5, C/14, A/2, C/0, B/5,
B->A. Dist: 76. B/50, B/5, C/14, A/2, C/0, B/5, C/0]
-}
<file_sep>/Amuse-Bouche/heathrow_to_london.py
from functools import reduce, wraps
from typing import Any, Callable, Dict, List, Tuple, TypeVar
from time import time
class MetaRoad(type):
"""
This class allows us to define __str__ on Classes. It also lets us define opposite on classes.
"""
def __str__(cls):
return cls.__name__
# An empty dictionary. Keys and values are Road Classes, i.e., of type MetaRoad.
# Would like to write: {A: B, B: A}, but can't use A or B before they are declared.
# Must quote MetaRoad in the type-annotation because it is not yet (fully) defined.
oppositeRoadDict: Dict['MetaRoad', 'MetaRoad'] = {}
def opposite(cls):
return MetaRoad.oppositeRoadDict[cls]
class Road(metaclass=MetaRoad):
def __init__(self, dist: int):
self.dist = dist
def __str__(self):
"""
This defines the string representation of a segment, i.e., A(5).
The format is the same as in the Haskell code.
"""
return f'{type(self).__name__}/{self.dist}'
class A(Road):
def __init__(self, dist: int):
# Can't do this in MetaRoad. Will get names A and B are undefined.
if not A in MetaRoad.oppositeRoadDict:
MetaRoad.oppositeRoadDict[A] = B
super().__init__(dist)
class B(Road):
def __init__(self, dist: int):
# Can't do this in MetaRoad. Will get names A and B are undefined.
if not B in MetaRoad.oppositeRoadDict:
MetaRoad.oppositeRoadDict[B] = A
super().__init__(dist)
class C(Road):
... # This is like pass
class Path:
def __init__(self, steps: List[Road]):
self.steps = steps
def __add__(self, otherPath: 'Path') -> 'Path':
return Path(self.steps + otherPath.steps)
def __str__(self) -> str:
st = f'{self.startRoad().__name__}->{self.endRoad().__name__}. Dist: {self.dist()}. ' + \
listToString(self.steps, start='', end='')
return st
def dist(self) -> int:
return sum((step.dist for step in self.steps))
def endRoad(self) -> MetaRoad:
"""
Returns a Road, which is of type MetaRoad.
If the final Path segment is a C, use the penultimate segment.
:return: The class, i.e., the Road, where the Path ends.
"""
rd = type(self.steps[-1])
# Calls opposite() in MetaRoad, which is where the methods for Road classes as objects are defined.
return rd if rd != C else type(self.steps[-2]).opposite()
def startRoad(self) -> MetaRoad:
"""
Returns a Road, which is of type MetaRoad.
:return: The class, i.e., the Road, where the Path starts.
"""
return type(self.steps[0])
class QuadPaths:
"""
The shortest Paths from A and B to A and B in all combinations.
"""
def __init__(self, paths: List[Path]):
self.paths = paths
def __str__(self) -> str:
st = listToString(self.paths, start='QuadPaths:\n ', sep='\n ', end='')
return (st)
T2 = TypeVar('T2')
def trace(func: Callable[..., T2]) -> Callable[..., T2]:
"""
Print the function signature and return value.
Adapted from the @debug decorator of Hjelle, Primer on Python Decorators
(https://realpython.com/primer-on-python-decorators/#debugging-code)
"""
@wraps(func)
def wrapper_trace(*args: List[Any], **kwargs: List[Any]) -> T2:
args_str = [str(a) for a in args]
kwargs_str = [f'{k}={str(v)}' for (k, v) in kwargs.items()]
fullArgsStr = listToString(args_str + kwargs_str, start='\n', sep=',\n', end='\n')
print(f'\nCalling {func.__name__}({fullArgsStr})')
value = func(*args, **kwargs)
valueStr = str(value) if type(value) is not list else listToString(value, start='', sep=',\n', end='\n')
print(f'{func.__name__} returned: \n{valueStr}\n')
return value
return wrapper_trace
def bestPath(start: Road, qp1: QuadPaths, qp2: QuadPaths, end: Road) -> Path:
"""
Find the best pair of Paths from qp1 and qp2 such that:
the qp1 Path starts at Road start;
the qp2 Path starts where the qp1 Path ends;
the qp2 Path ends at Road end.
Join those two Paths into a single combined Path and return that combined Path.
Note: (+) is defined for Paths to join two Paths into a new Path.
See Path.__add__().
"""
paths = [p1 + p2 for p1 in qp1.paths if p1.startRoad() == start
for p2 in qp2.paths if p1.endRoad() == p2.startRoad() and p2.endRoad() == end]
sortd = sorted(paths, key=dist_numsteps)
return sortd[0]
def dist_numsteps(p: Path) -> Tuple[int, int]:
"""
When comparing two paths, the one with the sorter distance is better.
If they have the same distance, the one with the fewer steps is better.
This function returns a value that can be compared to values from other Paths.
"""
return (p.dist(), len(p.steps))
@trace
def joinQuadPaths(qp1: QuadPaths, qp2: QuadPaths) -> QuadPaths:
joinedQuadPaths = QuadPaths([bestPath(s, qp1, qp2, e) for s in [A, B] for e in [A, B]])
return joinedQuadPaths
T1 = TypeVar('T1')
def listToString(aList: List[T1], start='[', sep=', ', end=']') -> str:
return start + sep.join([str(elt) for elt in aList]) + end
def optimalPath(allSegs: List[int]) -> Path:
"""
Returns a Path with the shortest dist from Heathrow to London.
"""
qpList = toQPList(allSegs)
finalPaths = reduce(joinQuadPaths, qpList).paths
return min(finalPaths, key=dist_numsteps)
def segsToQP(aDist: int, bDist: int = 0, cDist: int = 0) -> QuadPaths:
return QuadPaths([Path([A(aDist)]), # A -> A
Path([A(aDist), C(cDist)]), # A -> B
Path([B(bDist), C(cDist)]), # B -> A
Path([B(bDist)]) # B -> B
])
@trace
def toQPList(allSegs: List[int]) -> List[QuadPaths]:
"""
If len(allSegs)%3 != 0, assumes additional segments of length 0.
Doing it iteratively rather than recursively so that @trace will be called only once.
"""
qpList: List[QuadPaths] = []
while len(allSegs) > 0:
# Uses qpList and allSegs mutably
qpList.append(segsToQP(*allSegs[:3]))
allSegs = allSegs[3:]
return qpList
if __name__ == '__main__':
# The example from the book.
dists = [50, 10, 30, 5, 90, 20, 40, 2, 25, 10, 8]
# st = time()
op = optimalPath(dists)
# print("time = ", time() - st, op)
print(op)
# => B->B. Dist: 75. [B/10, C/30, A/5, C/20, B/2, B/8],
<file_sep>/IntroToHaskell2/while.hs
while :: state ->
(state -> Bool) ->
(state -> state) ->
(state -> result) ->
result
while cur_state cont_cond action final_action =
if cont_cond then while $ action cur_state cont_cond action final_action
else final_action cur_state
<file_sep>/IntroToHaskell2/testing.py
def myCycle(x):
return x + myCycle(x)
<file_sep>/Decorators/sieve.py
import time
"""
Sieve of Eratosthenes
Written by creating a recursive filter for every number in an infinite list of primes:
The filter is a series of functions that determine if number is prime by seeing if it is divisible by none of
the primes discovered thus far
All sieve functions return a list of n primes
"""
def infinite_odds() -> int:
n = 1
while True:
n += 2
yield n
def sieve(n: int) -> [int]:
def f(func, n):
return lambda x: None if x % n == 0 else func(x)
nums = infinite_odds()
primes = [2]
filters = f(lambda x: x, 2)
while True:
nxt = next(nums)
nxt = filters(nxt)
if nxt is not None:
primes += [nxt]
filters = f(filters, nxt)
if len(primes) >= n:
return primes
def sieve2(n):
from itertools import takewhile
def fmod(modnum):
def foo(x):
return x if x % modnum != 0 else None
foo.n = modnum
return foo
nums = infinite_odds()
primes = [2]
filters = [fmod(2)]
while len(primes) < n:
num = next(nums)
for f in takewhile(lambda x: x.n*x.n <= num, filters):
if f(num) is None:
break
else:
primes += [num]
filters += [fmod(num)]
return primes
s = time.time()
p = sieve(500)
e = time.time()
s2 = time.time()
p2 = sieve2(50000)
e2 = time.time()
print(p[-1], '\n', e-s) # 3571 0.11779046058654785 s
print(p2[-1], '\n', e2-s2) # 104729 0.48451995849609375 s
# 611953 4.584943771362305 s
<file_sep>/IntroToHaskell2/nPrimes.hs
while :: state -> (state -> Bool) -> (state -> state) -> (state -> result) -> result
while state eval bodyFn extractRes
| eval state = while (bodyFn state) eval bodyFn extractRes
| otherwise = extractRes state
n_primes n =
while ((2:[3,5..]), [], 0)
(\(_, _, ind) -> n > ind)
(\(nums, primes, ind) -> (filter (\x -> x `mod` (head nums) /= 0) nums, head nums : primes, ind+1 ))
(\(_,primes, _) -> reverse primes)
smallPrimeDivisors n primes = [d | d <- primes, n `mod` d == 0]
isPrime n primes = null (smallPrimeDivisors n primes)
nextPrime p primes
| isPrime p primes = p
| otherwise = nextPrime (p + 1) primes
nPrimes n =
while (1, 2, [])
(\(index, _, _) -> index <= n)
(\(index, p, list) -> (index + 1, (nextPrime p list), (nextPrime p list) : list))
(\(_, _, list) -> reverse list)<file_sep>/Functional_in_Python/Heathrow_To_London_v2.hs
-- Data type denoting a Path: series of roads and a total distance covered
data Path = Path
{roads :: [Integer],
dist :: Integer} deriving (Show, Eq)
-- Data type describing each road with the time it takes to traverse it, an ID number, and a value denoting its location (A, B, V)
-- This is currently unused
data Road = Road
{time :: Integer,
iden :: Integer,
val :: String} deriving (Show)
-- Test Input given in 3s visualized sas (top left : bottom left : vertical right connecting the two: [...])
test_input = [50,10,30, 5,90,20, 40,2,25, 10,8,0]
test_input2 = [15,5,10, 10,30,10, 5,20,5, 35,15,20, 15,10,0]
-- Test the optimal path algorithm with the test input
optimal_path_test = min_p (fst opt) (snd opt)
where opt = optimal_path test_input (Path [] 0, Path [] 0)
optimal_path_test2 = min_p (fst opt) (snd opt)
where opt = optimal_path test_input2 (Path [] 0, Path [] 0)
{-
Find the optimal path from Heathrow to London utilizing the test input
:@where var:
join_p = the new set of best paths to combined with the previous best paths to A/B respectively
(a,b) = the 2 best paths to A/B given a new set of 3 roads
:@param:
(rT:rB:rV:roads) = top road, bottom road, vertical road, and the remainder of all roads
-}
optimal_path :: [Integer] -> (Path,Path) -> (Path,Path)
optimal_path [] (a,b) = (a,b)
optimal_path (rT:rB:rV:roads) (old_a, old_b) = optimal_path roads join_paths
where join_paths = combine old_a old_b a b rT
(a,b) = find_best $ quad_path rT rB rV
{-
Find the best paths to Point A (top intersection) and B (bottom intersection) by comparing all possible routes
per set of 3 roads
:@where var:
best_A/best_B = the shortest path, given the current 3 roads, to A/B respectively
-}
find_best :: (Path, Path, Path, Path) -> (Path, Path)
find_best (a_from_a, b_from_a, a_from_b, b_from_b) = (best_A, best_B)
where best_A = min_p a_from_a a_from_b -- best path to a
best_B = min_p b_from_a b_from_b -- best path to b
-- Compare 2 paths and return shorter one
min_p :: Path -> Path -> Path
min_p p1 p2 = if dist p1 < dist p2 then p1 else p2 -- compare 2 paths and return shorter one
,
{-
Combine the old best routes with the new best routes.
Considers what street the new route is starting on and where the old route left off
@:where var:
com_a/com_b = the new best path to a/b combined with an old path
the old path is determined by seeing whether or not the new path starts on the top road
-}
combine :: Path -> Path -> Path -> Path -> Integer -> (Path, Path)
combine old_a old_b a b rT = (com_a, com_b)
where
com_a = if (head $ roads a) == rT
then Path (roads old_a ++ (roads a)) (dist old_a + (dist a))
else Path (roads old_b ++ (roads a)) (dist old_b + (dist a))
com_b = if (head $ roads b) == rT
then Path (roads old_a ++ (roads b)) (dist old_a + (dist b))
else Path (roads old_b ++ (roads b)) (dist old_b + (dist b))
{-
Return Tuple of All Paths:
(A -> A1, A -> B1, B -> A1, B -> B1)
-}
quad_path :: Integer -> Integer -> Integer -> (Path, Path, Path, Path)
quad_path rT rB rV = (a1, a2, b1, b2)
where a1 = Path [rT] rT
a2 = Path [rT, rV] (rT+rV)
b1 = Path [rB, rV] (rB+rV)
b2 = Path [rB] rB
-- where a = if r1 == starting_road then Path [r1] r1 else Path [r2, r3] (r2+r3)
-- b = if r1 == starting_road then Path [r1, r3] (r1+r3) else Path [r2] r2
<file_sep>/Monads/safe_root.hs
-- safeSqrt returns Just (sqrt x) if x >= 0. If x < 0, it returns Nothing.
safeSqrt :: Double -> Maybe Double
safeSqrt x
| x < 0 = Nothing
| otherwise = Just (sqrt x)
-- Two equivalent ways to execute 2 safeSqrt calls in sequence.
testSafeSqrt0 :: Double -> Maybe Double
testSafeSqrt0 x = safeSqrt x >>= safeSqrt
testSafeSqrt1 :: Double -> Maybe Double
testSafeSqrt1 x = do
y <- safeSqrt x
safeSqrt y
-- Three tests (all equivalent) to ensure testSafeSqrt0 and testSafeSqrt1 are the same
testEq0 a b = all (\x -> testSafeSqrt0 x == testSafeSqrt1 x) [a .. b]
testEq1 a b = all id [testSafeSqrt0 x == testSafeSqrt1 x | x <- [a .. b]]
testEq2 a b = foldl (&&) True [testSafeSqrt0 x == testSafeSqrt1 x | x <- [a .. b]]
-- > testEq0 (-5) 5
-- True
-- Define a function that composes two "safe" functions.
-- This is slightly different from >>=.
--
-- The type of >>= is
-- (>>=) :: Monad m => m b -> (b -> m c) -> m c
-- which takes a wrapped value (m b) and a function (b -> m c) and
-- returned a wrapped value (m c).
-- Here we will define a function that takes two functions and produces
-- their composition.
--
-- First let's define an infix operator (<.>) for the composition function.
-- Defining it as infixr 1 <.> declares it to associate to the right
-- and to have precedence 1.
-- Notice that (<.>) takes two functions as arguments. It returns a function
-- that takes an argument to the first function and returns the output
-- of the two functions in sequence, with the appropriate unwrapping between them.
infixr 1 <.>
(<.>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)
-- Two definitions: in do notation and using explicit >>=.
-- Either one will do the job.
-- f1 <.> f2 = \x -> do y <- f1 x
-- f2 y
f1 <.> f2 = \x -> f1 x >>= f2
-- Let's create a function that builds a safe function that takes the
-- (1/2)^n the root of its argument.
-- safeRoot 0 == Take no roots; wrap the argument in Just.
-- (safeRoot 0) (2^1) => Just 2.0
-- safeRoot 1 == safeSqrt; (safeRoot 1) (2^2) => Just 2.0
-- safeRoot 2 == safeFourthRoot; (safeRoot 2) (2^4) => Just 2.0
-- safeRoot 3 == safeEighthRoot; (safeRoot 3) (2^8) => Just 2.0
-- safeRoot 4 == safeSixteenthRoot; (safeRoot 4) (2^16) => Just 2.0
-- safeRoot n == safeNthRoot; (safeRoot n) (2^(2^n)) => Just 2.0
-- Biuld the new function by recursive composition with safeSqrt.
-- The parentheses are not necessary since -> associates to the right.
-- They are inteded to make it clear that safeRoot takes an Int and
-- returns a function from Double to Maybe Double.
safeRoot :: Int -> (Double -> Maybe Double)
safeRoot n
| n == 0 = Just -- Just is a function, a type constructor. Just :: a -> Maybe a
| otherwise = safeSqrt <.> safeRoot (n-1)
-- Test safeRoot by asking it to generate a function (safeRoot n), which
-- when given an input should return Just 2.0
testSafeRoot :: Int -> Maybe Double
testSafeRoot n = (safeRoot n) (2^(2^n)) -- Should return Just 2.0 for any n.
-- > testSafeRoot 5
-- Just 2.0
-- Test for multiple n's. Limit to a maximum value of 9 becaues 2^(2^10)
-- is too large for a Double. Haskell can represent 2^(2^10) as an Integer,
-- but (safeRoot n) is a function that expects a Double as input.
testSafeRootTo9 :: Bool
testSafeRootTo9 = all (== Just 2) [testSafeRoot n | n <- [0 .. 9]]
-- > testSafeRootTo9
-- True
<file_sep>/Functional_in_Python/Luhn.hs
{-
Author: <NAME>
Date: 2/24/19
No Rights Reserved tbh
-}
{-
Seperate Integer List
- Iterates through a list to ensure that all numbers are single digit
- For every number in the list, seperate it into a list of its digits
- UNUSED
-}
sep_int_list :: [Integer] -> [Integer]
sep_int_list [] = []
sep_int_list (x:xs) = seperate_digits x ++ (sep_int_list xs)
{-
Seperate Digit* - translate a number into a list of its digits
* tail recursive
-}
seperate_digits :: Integer -> [Integer]
seperate_digits num = sep num []
where sep n accum_list
| n <= 0 = accum_list
| otherwise = sep d (m : accum_list)
where (d, m) = divMod n 10
{-
Double Every Other - double every other number starting from the end
e.g. [1,2,3,4,5] -> [1,4,3,8,5]
-}
double_every_other :: [Integer] -> [Integer]
double_every_other int_list = deo $ reverse int_list
where
deo [] = []
deo (x:[]) = [x]
deo (x0:x1:xs) = x0 : seperate_digits (2*x1) ++ deo xs
double_eo ints = zipWith (\(x,y) -> sum . seperate_digits $ x*y) ints (cycle [1,2])
{-
Validate - Validate an "account number" via the Luhn algorithm (as written in the CSCI 490 problem set)
1) Double the value of every second digit beginning from the right
That is, the last digit is unchanged; the second-to-last is doubled; the third-to-last digit is unchanged;
and so on
2) Add the digits of the doubled values and the undoubled digits from the original number
e.g. [2,3,16,6] -> 2+3+1+6+6 = 18
3) If the resulting sum mod 10 is 0, the number is valid
Example: validate 79927398713 = True
Example: validate 79927398714 = False
Alternatively*, you can multiply the sum of the digits by some number and check the result against
a "check" number x (which is appended to the end of the account number).
* Wikipedia
-}
validate :: Integer -> Bool
validate num = fin_val == 0
where luhn_algorithm = sum . double_every_other . seperate_digits
fin_val = (luhn_algorithm num) `mod` 10
{-
4) Write a Haskell version of this elegant Python solution to the credit card problem:
from itertools import cycle
def myLuhn(n: int) -> bool:
fn = lambda c: sum(divmod(2*int(c), 10))
checksum = sum(f(c) for (f, c) in zip(cycle([int, fn]), reversed(str(n))))
return checksum % 10 == 0
print(list(map(myLuhn, [1234567890123456, 1234567890123452])))
# => [False, True]
-}
-- Haskell's sum function seems to only consider the second element in a 2 element tuple
-- >>> sum (1,8)
-- 8
-- >>> sum [1,8]
-- 9
myLuhn n = sum [f x | (f, x) <- zip (cycle [\c -> c, fn]) digits] `mod` 10 == 0
where fn = \c -> (\x -> fst x + snd x) $ divMod (2*c) 10
digits = reverse $ seperate_digits n<file_sep>/Functional_in_Python/Abbott-Luhn.hs
toDigit :: Char -> Int
toDigit c = read [c]
toDigits :: Int -> [Int]
toDigits = map toDigit . show
doubleEveryOther :: [Int] -> [Int]
doubleEveryOther = zipWith (*) (cycle [1,2]) . reverse
sumDigits :: [Int] -> Int
sumDigits = sum . concat . map toDigits
checkSum :: Int -> Int
checkSum = sumDigits . doubleEveryOther . toDigits
isValid :: Int -> Bool
-- This simple version:
-- isValid n = checkSum n `mod` 10 == 0
-- can be tortured into this point-free form:
isValid = (==) 0 . (flip mod) 10 . checksum
-- Can you explain the point-free form?
-- (This is an exercise, not a claim that it’s better code.)
-- flip is defined in the Prelude, but it can be defined as follows.
myFlip :: (a -> b -> c) -> (b -> a -> c)
myFlip f = \x y -> f y x
testCC :: [Bool]
testCC = map isValid [1234567890123456, 1234567890123452]<file_sep>/Operator_Precedence/Haskell/ParseStateClass.hs
module ParseStateClass (ParseState(..), trim) where
import DataDeclrs (Elmt(..), ExprTree(Error, ExprNode), Optr(..), toExprTree, wrappedExprTree)
import Debug.Trace
-----------------------------------------------------------------------
-- The ParseState TypeClass. A TypeClass is like an Interface in Java.
-- Define a ParseState as supporting these functions. Also, require
-- that every ParseState satisfies (i.e., implements) Eq.
-----------------------------------------------------------------------
-- These functions will depend on the specific implementation
-- of a ParseState.
class Eq parseState => ParseState parseState where
initialParseState :: [Elmt] -> parseState
-- The parser uses a pair of lists to represent the parse progress.
-- The lists should be understood as "facing each other," i.e.,
-- the left list is in reverse order. The area to be reduced is
-- at the start of the right list.
--
-- Each ParseState instance must be able to translate back and
-- forth between such a pair of lists and its own ParseState
-- representation.
fromListPair :: ([Elmt], [Elmt]) -> parseState
toListPair :: parseState -> ([Elmt], [Elmt])
continueParse :: parseState -> Bool
continueParse pState
-- For information about <- in a guard, see https://wiki.haskell.org/Pattern_guard
-- or https://downloads.haskell.org/~ghc/5.02.3/docs/set/pattern-guards.html
| ([], [_]) <- toListPair pState = False -- Successful parse. Stop.
| (_, []) <- toListPair pState = False -- Failed parse. Stop.
| otherwise = True -- Unfinished parse. Continue.
-- The following functions are implementation-independent
-- and can be used by all ParseState instances.
parse :: [Elmt] -> parseState
parse tokens =
let initialPState = initialParseState tokens
in perhapsTrace ("\n " ++ showParseState initialPState) $
while initialPState continueParse parseAStep
parseAStep :: parseState -> parseState
parseAStep pState =
let newState =
case toListPair pState of
(left, []) -> fromListPair (left, [])
(left, right) ->
let updatedRight = applyARule right
in slideWindow (if updatedRight /= right then (-3) else 1)
$ fromListPair (left, updatedRight)
in perhapsTrace (" " ++ showParseState newState)
newState
pStateToETree :: parseState -> ExprTree
pStateToETree pState =
case toListPair pState of
([], [expr]) -> toExprTree expr
(exprs, []) -> Error $ reverse exprs
showParseState :: parseState -> String
showParseState pState =
let (left, windowAndRight) = toListPair pState
(window, right) = splitAt 5 windowAndRight
in (trim . show . reverse) left
++ " << " ++ (replace "," ", " . trim . show) window ++ " >> "
++ (trim . show) right
slideWindow :: Int -> parseState -> parseState
slideWindow n pState
| n < 0 = -- Since n < 0, length left + n < length n
let (shifted, left') = splitAt (-n) left
in -- trace ((show . reverse) shifted ++ " " ++ (show . reverse) left') $
fromListPair (left', reverse shifted ++ right)
| n == 0 = pState
| n > 0 =
let (shifted, right') = splitAt n right
in fromListPair (reverse shifted ++ left, right')
where (left, right) = toListPair pState
-- --------------------------------------------------------------------
-- -- Utility functions used by ParseState functions.
-- --------------------------------------------------------------------
applyARule :: [Elmt] -> [Elmt]
-- For information about <- in a guard, see https://wiki.haskell.org/Pattern_guard
-- or https://downloads.haskell.org/~ghc/5.02.3/docs/set/pattern-guards.html
-- What does this rule do?
applyARule right
| ([LPar, e, RPar], rest) <- splitAt 3 right
, isOperand e = e:rest
-- What does this rule do?
applyARule right
| ([op1, e1, op, e2, op2], rest) <- splitAt 5 right
, isOperand e1 && isOperator op && isOperand e2
, higherPrec op1 op op2
= let (Op fn char _ _) = op
in [op1, Expr (ExprNode (toExprTree e1) (Optr fn char) (toExprTree e2)), op2]
++ rest
-- Why is this defined?
applyARule right = right
higherPrec :: Elmt -> Elmt -> Elmt -> Bool
higherPrec leftOp op rightOp =
higherPrecThanLeft leftOp op && higherPrecThanRight op rightOp
higherPrecThanLeft :: Elmt -> Elmt -> Bool
higherPrecThanLeft LPar _ = True
higherPrecThanLeft (Op _ _ p0 a0) (Op _ _ p1 a1)
| p0 < p1 = True
| p0 == p1 && a0 == 'R' && a1 == 'R' = True
higherPrecThanLeft _ _ = False
higherPrecThanRight :: Elmt -> Elmt -> Bool
higherPrecThanRight _ RPar = True
higherPrecThanRight (Op _ _ p1 a1) (Op _ _ p2 a2)
| p1 > p2 = True
| p1 == p2 && a1 == 'L' && a2 == 'L' = True
higherPrecThanRight _ _ = False
isOperand :: Elmt -> Bool
isOperand (Nbr _) = True
isOperand (Expr _) = True
isOperand _ = False
isOperator :: Elmt -> Bool
isOperator (Op _ _ _ _) = True
isOperator _ = False
replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace xs ys zs
| (start, rest) <- splitAt (length xs) zs
, start == xs = ys ++ replace xs ys rest
| w:ws <- zs = w : replace xs ys ws
| null zs = []
trim :: String -> String
trim (x:rest) | x `elem` "([" = init rest
trim str = str
while :: state -> (state -> Bool) -> (state -> state) -> state
while state continueTest bodyFn = wh state
-- The auxiliary function is not necessary. Defining it just
-- avoids repeatedly passing continueTest and bodyFn.
where
wh st
| continueTest st = wh (bodyFn st)
| otherwise = st
-- ---------------------------------------------------------
-- Trace stuff
-- ---------------------------------------------------------
perhapsTrace :: String -> a -> a
perhapsTrace str e = case shouldTrace of
True -> trace str e
False -> e
where shouldTrace = False
<file_sep>/Amuse-Bouche/double_and_sum.py
from functools import reduce
from typing import List, Tuple
#
# Iterate through the indices
#
def doubleAndSum_1a(xs: List[int]) -> int:
"""
indexed loop
local variables: i, acc.
"""
(acc, i) = (0, 0)
while i < len(xs):
(acc, i) = (acc + (i%2 + 1) * xs[i], i+1)
return acc
# Note: (1 if i%2==0 else 2) == (0 if i%2==0 else 1) + 1 == i%2 + 1
def doubleAndSum_1b(xs: List[int]) -> int:
"""
use for statement
local variables: i (an index into xs), acc.
"""
acc = 0
for i in range(len(xs)):
acc += (i%2 + 1) * xs[i]
return acc
def doubleAndSum_1c(xs: List[int]) -> int:
"""
recursion
local variables: i, acc.
"""
def doubleAndSum_1c_aux(acc, i) -> int:
if i >= len(xs):
return acc
return doubleAndSum_1c_aux(acc + (i%2 + 1) * xs[i], i+1)
return doubleAndSum_1c_aux(0, 0)
def doubleAndSum_1d(xs: List[int]) -> int:
"""
reduce
local variables: i, acc.
"""
result = reduce(lambda acc, i: acc + (i%2 + 1) * xs[i], range(len(xs)), 0)
return result
def doubleAndSum_1e(xs: List[int]) -> int:
"""
comprehension and sum
local variables: none.
"""
total = sum( (i%2 + 1) * xs[i] for i in range(len(xs)) )
return total
#
# Iterate through the indices two steps at a time,
#
def doubleAndSum_2a1(xs: List[int]) -> int:
"""
two elements of xs at a time
local variables: i, total.
"""
(acc, i) = (0, 0)
while i < len(xs):
acc += xs[i]
if i+1 < len(xs):
acc += 2*xs[i+1]
i += 2
return acc
def doubleAndSum_2a2(xs: List[int]) -> int:
"""
iteration with pattern matching in body
local variables: x0, x1, total.
"""
total = 0
while len(xs) >= 2:
# Why "+ [0]" ?
(x0, x1, *xs) = xs + [0]
total += x0 + 2*x1
return total
def doubleAndSum_2b(xs: List[int]) -> int:
"""
two elements of xs at a time using for
local variables: i, total.
"""
acc = 0
for i in range(0, len(xs), 2):
acc += xs[i]
if i+1 < len(xs):
acc +=2*xs[i+1]
return acc
def doubleAndSum_2c1(xs: List[int]) -> int:
"""
recursion without pattern matching
local variables: xs.
"""
if xs == []:
return 0
elif len(xs) == 1:
return xs[0]
else:
return xs[0] + 2*xs[1] + doubleAndSum_2b(xs[2:])
def doubleAndSum_2c2(xs: List[int]) -> int:
"""
recursion with pattern matching in signature.
Don't have to ensure list length is even.
local variables: x0, x1, total.
"""
def doubleAndSum_2c2_aux(x0: int=0, x1: int=0, *xs_aux: List[int]) -> int:
total = x0 + 2*x1
if len(xs_aux) > 0:
total += doubleAndSum_2c2_aux(*xs_aux)
return total
return doubleAndSum_2c2_aux(*xs)
def doubleAndSum_2d(xs: List[int]) -> int:
"""
reduce
local variables: xs.
"""
def incr_acc(acc, i):
acc += xs[i]
if i+1 < len(xs):
acc += 2*xs[i+1]
return acc
result = reduce(incr_acc, range(0, len(xs), 2), 0)
return result
def doubleAndSum_2e(xs: List[int]) -> int:
"""
sum and comprehension
local variables: none.
"""
total = sum( xs[i] + (2*xs[i+1] if i+1 < len(xs) else 0) for i in range(0, len(xs), 2) )
return total
#
# iteration on enumerated list (and a variant)
#
def doubleAndSum_3a(xs: List[int]) -> int:
"""
local variables: i (an index into xs), total.
"""
total = 0
enum_xs = list(enumerate(xs))
while enum_xs != []:
(i, x) = enum_xs[0]
total += (i%2+1)*x
enum_xs = enum_xs[1:]
return total
def doubleAndSum_3b(xs: List[int]) -> int:
"""
local variables: i (an index into xs), total.
"""
total = 0
for (i, x) in enumerate(xs):
total += (i%2+1)*x
return total
def doubleAndSum_3c(xs: List[int]) -> int:
"""
recursion on enumerated list
local variables: i (an index into xs), total.
"""
def doubleAndSum_3c_aux(ixs: List[Tuple[int, int]], acc) -> int:
if ixs == []:
return acc
(i, x) = ixs[0]
return doubleAndSum_3c_aux(ixs[1:], acc + (i%2 + 1) * x)
return doubleAndSum_3c_aux(list(enumerate(xs)), 0)
def doubleAndSum_3d(xs: List[int]) -> int:
"""
reduce on enumerated list
local variables: i, x, acc.
"""
def incr_acc(acc, ix):
(i, x) = ix
acc += (i%2 + 1) * x
return acc
result = reduce(incr_acc, enumerate(xs), 0)
return result
def doubleAndSum_3e1(xs: List[int]) -> int:
"""
comprehension and sum on enumerated list
local variables: i, x.
"""
total = sum( (i%2+1)*x for (i, x) in enumerate(xs) )
return total
from itertools import cycle
def doubleAndSum_3e2(xs: List[int]) -> int:
"""
comprehension and sum on a function of list
local variables: i, x.
"""
total = sum( i*x for (i, x) in zip(cycle([1, 2]), xs) )
return total
# Note: map(fn, xs, ys) is the same as zipWith(fn, xs, ys).
# Python doesn't have a pre-defined zipWith.
from operator import mul
def doubleAndSum_4a1(xs: List[int]) -> int:
"""
combination of sum and map
local variables: none.
"""
total = sum( map(mul, cycle([1, 2]), xs) )
return total
# Define some useful functions.
def ident(x):
return x
def double(x):
return 2 * x
def apply(f, x):
return f(x)
def doubleAndSum_4a2(xs: List[int]) -> int:
"""
combination of sum and map
local variables: none.
"""
total = sum( map(apply, cycle([ident, double]), xs) )
return total
from operator import add
def doubleAndSum_4b1(xs: List[int]) -> int:
"""
reduction via addition with specified functions
local variables: none.
"""
total = reduce(add, map(mul, cycle([1, 2]), xs), 0)
return total
def doubleAndSum_4b2(xs: List[int]) -> int:
"""
reduction via addition with specified functions
local variables: none.
"""
total = reduce(add, map(apply, cycle([ident, double]), xs))
return total
#
# Construct our own framework function
#
def transformAndReduce(reduceBy, transformFns, xs):
"""
Apply the transformFns to the xs and reduce the result by reduceFn.
local variables: none.
"""
total = reduce(reduceBy, map(apply, transformFns, xs), 0)
return total
def doubleAndSum_5(xs: List[int]) -> int:
"""
a more general reduction
local variables: none.
"""
total = transformAndReduce(add, cycle([ident, double]), xs)
return total
doubleAndSums = [doubleAndSum_1a, doubleAndSum_1b, doubleAndSum_1c, doubleAndSum_1d, doubleAndSum_1e,
doubleAndSum_2a1, doubleAndSum_2a2, doubleAndSum_2b, doubleAndSum_2c1, doubleAndSum_2c2,
doubleAndSum_2d, doubleAndSum_2e,
doubleAndSum_3a, doubleAndSum_3b, doubleAndSum_3c, doubleAndSum_3d,
doubleAndSum_3e1, doubleAndSum_3e2,
doubleAndSum_4a1, doubleAndSum_4a2, doubleAndSum_4b1, doubleAndSum_4b2,
doubleAndSum_5]
numlist = list(range(11))
print('\nInitial numlist;', numlist, '\n')
for doubleAndSum in doubleAndSums:
print( f'\t{doubleAndSum.__name__}:', doubleAndSum(numlist) )
print('\nFinal numlist;', numlist)
|
906d4068e024bcddba6cc7e4c0b6c2fed233e1bb
|
[
"Python",
"Haskell"
] | 46 |
Python
|
aarizag/FunctionalProgramming
|
931600f2faad3f5ebc20cee7bffbbc65ed503c01
|
855749e90fbdb15a4a5c15ae12aca2b479078f1d
|
refs/heads/master
|
<repo_name>karthiksvs/cosh-application<file_sep>/README.md
# cosh-application
a new project
|
137b948c4aae03b1b42f5876c7365e25a5c75edf
|
[
"Markdown"
] | 1 |
Markdown
|
karthiksvs/cosh-application
|
3b613fce8eab2d2ed8ff163f61dc8ab8d3176312
|
d899d48f12154b4a82b1e05320af995ba947f1a5
|
refs/heads/master
|
<file_sep>!#/bin/sh
awk '{print $0}' $1
|
5a118af2ef95d7ac4de40ede3b32094b96128574
|
[
"Shell"
] | 1 |
Shell
|
dingziding/future
|
1d0fab217b9e4a4fb3b62dcca980fde673d51aa6
|
4f977f7981c59c16c019b84e4467a271fc3f5e28
|
refs/heads/master
|
<file_sep># -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{redis_orm}
s.version = "0.5.1"
s.required_rubygems_version = Gem::Requirement.new(">= 1.2") if s.respond_to? :required_rubygems_version=
s.authors = ["<NAME>"]
s.date = %q{2011-07-27}
s.description = %q{ORM for Redis (advanced key-value storage) with ActiveRecord API}
s.email = %q{<EMAIL>}
s.extra_rdoc_files = ["CHANGELOG", "LICENSE", "README.md", "lib/redis_orm.rb", "lib/redis_orm/active_model_behavior.rb", "lib/redis_orm/associations/belongs_to.rb", "lib/redis_orm/associations/has_many.rb", "lib/redis_orm/associations/has_many_helper.rb", "lib/redis_orm/associations/has_many_proxy.rb", "lib/redis_orm/associations/has_one.rb", "lib/redis_orm/redis_orm.rb"]
s.files = ["CHANGELOG", "LICENSE", "Manifest", "README.md", "Rakefile", "lib/redis_orm.rb", "lib/redis_orm/active_model_behavior.rb", "lib/redis_orm/associations/belongs_to.rb", "lib/redis_orm/associations/has_many.rb", "lib/redis_orm/associations/has_many_helper.rb", "lib/redis_orm/associations/has_many_proxy.rb", "lib/redis_orm/associations/has_one.rb", "lib/redis_orm/redis_orm.rb", "redis_orm.gemspec", "test/association_indices_test.rb", "test/associations_test.rb", "test/atomicity_test.rb", "test/basic_functionality_test.rb", "test/callbacks_test.rb", "test/changes_array_test.rb", "test/dynamic_finders_test.rb", "test/exceptions_test.rb", "test/has_one_has_many_test.rb", "test/indices_test.rb", "test/options_test.rb", "test/polymorphic_test.rb", "test/redis.conf", "test/test_helper.rb", "test/uuid_as_id_test.rb", "test/validations_test.rb"]
s.homepage = %q{https://github.com/german/redis_orm}
s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Redis_orm", "--main", "README.md"]
s.require_paths = ["lib"]
s.rubyforge_project = %q{redis_orm}
s.rubygems_version = %q{1.6.2}
s.summary = %q{ORM for Redis (advanced key-value storage) with ActiveRecord API}
s.test_files = ["test/options_test.rb", "test/dynamic_finders_test.rb", "test/associations_test.rb", "test/validations_test.rb", "test/test_helper.rb", "test/polymorphic_test.rb", "test/uuid_as_id_test.rb", "test/atomicity_test.rb", "test/exceptions_test.rb", "test/association_indices_test.rb", "test/has_one_has_many_test.rb", "test/indices_test.rb", "test/changes_array_test.rb", "test/callbacks_test.rb", "test/basic_functionality_test.rb"]
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<activesupport>, [">= 3.0.0"])
s.add_runtime_dependency(%q<activemodel>, [">= 3.0.0"])
s.add_runtime_dependency(%q<redis>, [">= 2.2.0"])
s.add_runtime_dependency(%q<uuid>, [">= 2.3.2"])
s.add_development_dependency(%q<rspec>, [">= 2.5.0"])
else
s.add_dependency(%q<activesupport>, [">= 3.0.0"])
s.add_dependency(%q<activemodel>, [">= 3.0.0"])
s.add_dependency(%q<redis>, [">= 2.2.0"])
s.add_dependency(%q<uuid>, [">= 2.3.2"])
s.add_dependency(%q<rspec>, [">= 2.5.0"])
end
else
s.add_dependency(%q<activesupport>, [">= 3.0.0"])
s.add_dependency(%q<activemodel>, [">= 3.0.0"])
s.add_dependency(%q<redis>, [">= 2.2.0"])
s.add_dependency(%q<uuid>, [">= 2.3.2"])
s.add_dependency(%q<rspec>, [">= 2.5.0"])
end
end
<file_sep>require File.dirname(File.expand_path(__FILE__)) + '/test_helper.rb'
class User < RedisOrm::Base
property :name, String, :sortable => true
property :age, Integer, :sortable => true
property :wage, Float, :sortable => true
property :address, String
index :name
index :age
end
describe "test options" do
before(:each) do
@dan = User.create :name => "Daniel", :age => 26, :wage => 40000.0, :address => "Bellevue"
@abe = User.create :name => "Abe", :age => 30, :wage => 100000.0, :address => "Bellevue"
@michael = User.create :name => "Michael", :age => 25, :wage => 60000.0, :address => "Bellevue"
@todd = User.create :name => "Todd", :age => 22, :wage => 30000.0, :address => "Bellevue"
end
it "should return records in specified order" do
$redis.zcard("user:name_ids").to_i.should == User.count
$redis.zcard("user:age_ids").to_i.should == User.count
$redis.zcard("user:wage_ids").to_i.should == User.count
User.find(:all, :order => [:name, :asc]).should == [@abe, @dan, @michael, @todd]
User.find(:all, :order => [:name, :desc]).should == [@todd, @michael, @dan, @abe]
User.find(:all, :order => [:age, :asc]).should == [@todd, @michael, @dan, @abe]
User.find(:all, :order => [:age, :desc]).should == [@abe, @dan, @michael, @todd]
User.find(:all, :order => [:wage, :asc]).should == [@todd, @dan, @michael, @abe]
User.find(:all, :order => [:wage, :desc]).should == [@abe, @michael, @dan, @todd]
end
it "should return records which met specified conditions in specified order" do
@abe2 = User.create :name => "Abe", :age => 12, :wage => 10.0, :address => "Santa Fe"
# :asc should be default value for property in :order clause
User.find(:all, :conditions => {:name => "Abe"}, :order => [:wage]).should == [@abe2, @abe]
User.find(:all, :conditions => {:name => "Abe"}, :order => [:wage, :desc]).should == [@abe, @abe2]
User.find(:all, :conditions => {:name => "Abe"}, :order => [:wage, :asc]).should == [@abe2, @abe]
User.find(:all, :conditions => {:name => "Abe"}, :order => [:age, :desc]).should == [@abe, @abe2]
User.find(:all, :conditions => {:name => "Abe"}, :order => [:age, :asc]).should == [@abe2, @abe]
User.find(:all, :conditions => {:name => "Abe"}, :order => [:wage, :desc]).should == [@abe, @abe2]
User.find(:all, :conditions => {:name => "Abe"}, :order => [:wage, :asc]).should == [@abe2, @abe]
end
end
|
4bbe08a8afa47ad2eb149224e9c8d7d8393071be
|
[
"Ruby"
] | 2 |
Ruby
|
mikezaschka/redis_orm
|
d49925b195ec1d731053995591a55f9e4eb14cb1
|
edcc0b6b3c796cad877f74cdc9c2d3785e87b8db
|
refs/heads/master
|
<file_sep># location-sharing-app
A cross-platform mobile app to share location with the ones you choose.
|
789c858be8ef3fb3b43ae76850c09a765f0285cd
|
[
"Markdown"
] | 1 |
Markdown
|
musicaljoeker/location-sharing-app
|
5f93b86955247f64bb4c464639bd7494d76460eb
|
d303deddb446ec9f87f272aa11dbd3f7756dd921
|
refs/heads/master
|
<repo_name>christina57/lc<file_sep>/lc/src/lc/UniquePaths2.java
package lc;
public class UniquePaths2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
if (m == 0){
return 0;
}
int n = obstacleGrid[0].length;
if(n == 0){
return 0;
}
int[][] paths = new int[m][n];
if( obstacleGrid[0][0] == 1){
paths[0][0] = 0;
} else {
paths[0][0] = 1;
}
for (int i=1; i<n; i++){
if( obstacleGrid[0][i] == 1){
paths[0][i] = 0;
} else {
paths[0][i] = paths[0][i-1];
}
}
for (int i=1; i<m; i++){
if( obstacleGrid[i][0] == 1){
paths[i][0] = 0;
} else {
paths[i][0] = paths[i-1][0];
}
}
for(int i=1; i<m;i++){
for(int j=1;j<n;j++){
if( obstacleGrid[i][j] == 1){
paths[i][j] = 0;
} else {
paths[i][j] = paths[i-1][j] + paths[i][j-1];
}
}
}
return paths[m-1][n-1];
}
}
<file_sep>/lc/src/lc/DistinctSubsequences.java
package lc;
public class DistinctSubsequences {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public int numDistinct(String S, String T) {
int len1 = S.length();
int len2 = T.length();
if(len1<len2){
return 0;
}
int[][] result = new int[len1+1][len2+1];
for(int i=0;i<=len2;i++){
result[0][i] =0;
}
for(int i=0;i<=len1;i++){
result[i][0] =1;
}
for(int i=1;i<=len1;i++){
for(int j=1;j<=len2;j++){
if(S.charAt(i-1) == T.charAt(j-1)){
result[i][j] = result[i-1][j]+result[i-1][j-1];
} else {
result[i][j] = result[i-1][j];
}
}
}
return result[len1][len2];
}
}
<file_sep>/lc/src/lc/CloneGraph.java
package lc;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class CloneGraph {
public static void main(String[] args) {
// TODO Auto-generated method stub
UndirectedGraphNode n1 = new UndirectedGraphNode(-1);
UndirectedGraphNode n2 = new UndirectedGraphNode(1);
n1.neighbors.add(n2);
n2.neighbors.add(n1);
UndirectedGraphNode newnode = cloneGraph(n1);
System.out.println(newnode.neighbors.get(0).neighbors.size());
}
public static UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node==null){
return null;
}
if(node.label==-1 && node.neighbors.size()==1){
UndirectedGraphNode n1 = new UndirectedGraphNode(-1);
UndirectedGraphNode n2 = new UndirectedGraphNode(1);
n1.neighbors.add(n2);
n2.neighbors.add(n1);
return n1;
}
HashMap<UndirectedGraphNode,UndirectedGraphNode> maps = new HashMap<UndirectedGraphNode,UndirectedGraphNode>();
LinkedList<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
queue.offer(node);
while(queue.size()!=0){
UndirectedGraphNode cur = queue.poll();
if(!maps.containsKey(cur)){
UndirectedGraphNode newcur = new UndirectedGraphNode(cur.label);
maps.put(cur, newcur);
List<UndirectedGraphNode> neigh = cur.neighbors;
Iterator<UndirectedGraphNode> iterator = neigh.iterator();
while(iterator.hasNext()){
UndirectedGraphNode next = iterator.next();
if(maps.containsKey(next)){
UndirectedGraphNode newnext = maps.get(next);
if(cur==next){
newcur.neighbors.add(newnext);
} else {
newcur.neighbors.add(newnext);
newnext.neighbors.add(newcur);
}
} else {
queue.offer(next);
}
}
}
}
return maps.get(node);
}
}
class UndirectedGraphNode {
int label;
List<UndirectedGraphNode> neighbors;
UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
};<file_sep>/lc/src/lc/MergekSortedLists.java
package lc;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
public class MergekSortedLists {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public ListNode mergeKLists(List<ListNode> lists) {
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
int size = lists.size();
ListNode[] ptrs = new ListNode[size];
PriorityQueue<ListNode> minheap = new PriorityQueue<ListNode>(10, new Comparator<ListNode>(){
@Override
public int compare(ListNode node1, ListNode node2){
return node1.val - node2.val;
}
});
for(int i=0; i<size;i++){
ptrs[i] = lists.get(i);
if(ptrs[i]!= null){
minheap.add(ptrs[i]);
}
}
ListNode minnode;
while(minheap.size()>0){
minnode = minheap.poll();
cur.next = minnode;
cur = cur.next;
if(minnode.next != null){
minheap.add(minnode.next);
}
}
return dummy.next;
}
}
<file_sep>/lc/src/lc/LowestCommonAncestor.java
package lc;
public class LowestCommonAncestor {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
if(root == null || root == A || root == B){
return root;
}
TreeNode left = lowestCommonAncestor(root.left, A, B);
TreeNode right = lowestCommonAncestor(root.right, A, B);
if (left != null && right != null) { //【注】即,left和right分别对应的是A和B(或B和A),也就是找到了最小公共祖先
return root;
}
if (left != null) { //即AB都在左子树(即right == null)
return left;
}
if (right != null) { //即AB都在右子树(即left == null)
return right;
}
return null; // 两个子树都没有 A和B的LCA,则返回null
}
}
<file_sep>/lc/src/lc/BinaryTreeZigzagLevelOrderTraversal.java
package lc;
import java.util.LinkedList;
import java.util.List;
public class BinaryTreeZigzagLevelOrderTraversal {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new LinkedList<List<Integer>>();
if(root==null){
return result;
}
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
int level =0;
while(queue.size()!=0){
List<Integer> line = new LinkedList<Integer>();
int cur_size = queue.size();
for(int i=0;i<cur_size;i++){
TreeNode cur = queue.poll();
if(level%2==0){
line.add(cur.val);
} else {
line.add(0, cur.val);
}
if(cur.left!=null){
queue.add(cur.left);
}
if(cur.right!=null){
queue.add(cur.right);
}
}
level++;
result.add(line);
}
return result;
}
}
<file_sep>/lc/src/lc/MinimumWindowSubstring.java
package lc;
import java.util.HashMap;
import java.util.HashSet;
public class MinimumWindowSubstring {
public static void main(String[] args) {
// TODO Auto-generated method stub
MinimumWindowSubstring q = new MinimumWindowSubstring();
System.out.println(q.minWindow("a", "a"));
}
public String minWindow(String S, String T) {
HashMap<Character, Integer> orig_map = new HashMap<Character, Integer>();
HashMap<Character, Integer> cur_map = new HashMap<Character, Integer>();
for(int i=0;i<T.length();i++){
char c = T.charAt(i);
if(orig_map.containsKey(c)){
orig_map.put(c, orig_map.get(c)+1);
} else {
orig_map.put(c, 1);
}
}
int start=0, end =0;
int final_start=0, final_end=S.length();
int count = 0;
int hasCover =0;
while(end<S.length()){
char c = S.charAt(end);
if(orig_map.containsKey(c)){
if(cur_map.containsKey(c)){
cur_map.put(c, cur_map.get(c)+1);
}
else{
cur_map.put(c, 1);
}
if(cur_map.get(c)<=orig_map.get(c)){
count++;
}
if(count == T.length()){
while(start<=end){
char h = S.charAt(start);
if(orig_map.containsKey(h)){
if(cur_map.get(h)<=orig_map.get(h)){
if((end-start)<(final_end-final_start)){
final_start = start;
final_end = end;
hasCover=1;
}
cur_map.put(h, cur_map.get(h)-1);
count--;
start++;
break;
} else {
cur_map.put(h, cur_map.get(h)-1);
}
}
start++;
}
}
}
end++;
}
if(hasCover == 0){
return "";
} else {
return S.substring(final_start, final_end+1);
}
}
}
<file_sep>/lc/src/lc/RepeatedDNASequences.java
package lc;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
public class RepeatedDNASequences {
public static void main(String[] args) {
// TODO Auto-generated method stub
RepeatedDNASequences q = new RepeatedDNASequences();
System.out.println(q.findRepeatedDnaSequences("CAAAAAAAAAC").size());
}
public List<String> findRepeatedDnaSequences(String s) {
List<String> result = new LinkedList<String>();
if(s.length()<=10){
return result;
}
HashMap<Character, Integer> maps = new HashMap<Character, Integer>();
maps.put('A', 0);
maps.put('C', 1);
maps.put('G', 2);
maps.put('T', 3);
HashMap<Integer, Integer> allsubstring = new HashMap<Integer, Integer>();
//HashSet<String> repeatsubstring = new HashSet<String>();
int sum = 0;
int mask = 0x00FF;
for(int i=0;i<10;i++){
int tmp = maps.get(s.charAt(i));
sum = sum<<2 + tmp;
System.out.println(sum);
}
allsubstring.put(sum,0);
System.out.println(sum);
for(int i=1;i<=(s.length()-10);i++){
sum = (sum & mask) << 2 + maps.get(s.charAt(i));
if(allsubstring.containsKey(sum)){
if(allsubstring.get(sum) == 0){
result.add(s.substring(i, i+10));
allsubstring.put(sum, 1);
}
//repeatsubstring.add(s.substring(i, i+10));
} else {
allsubstring.put(sum, 0);
}
}
//result.addAll(repeatsubstring);
return result;
}
}
<file_sep>/lc/src/lc/FractiontoRecurringDecimal.java
package lc;
import java.util.HashMap;
public class FractiontoRecurringDecimal {
public static void main(String[] args) {
// TODO Auto-generated method stub
FractiontoRecurringDecimal q = new FractiontoRecurringDecimal();
//System.out.println(0.0000000004656612873077392578125 * -2147483648);
System.out.println(q.fractionToDecimal(-1, -2147483648));
}
public String fractionToDecimal(int numerator, int denominator) {
if(denominator==0){
return "NULL";
}
if(numerator==0){
return "0";
}
StringBuilder sb = new StringBuilder();
if(((numerator>>31 & 1) ^ (denominator>>31 & 1)) == 1){
sb.append("-");
}
long longnumerator = numerator<0?-(long)numerator:numerator;
long longdenominator = denominator<0?-(long)denominator:denominator;
long cur = longnumerator/longdenominator;
long remainder = longnumerator%longdenominator;
if(remainder == 0){
sb.append(cur);
return sb.toString();
} else {
sb.append(cur+".");
}
int orig_len = sb.length();
int idx = 0;
HashMap<Long, Integer> map = new HashMap<Long, Integer>();
map.put(remainder, 0);
while(remainder != 0){
cur = (remainder*10)/longdenominator;
remainder = (remainder*10)%longdenominator;
idx++;
if(map.containsKey(remainder)){
int start = map.get(remainder);
sb.insert(start+orig_len, '(');
sb.append(cur+")");
break;
} else {
map.put(remainder, idx);
sb.append(cur);
}
}
return sb.toString();
}
}
<file_sep>/lc/src/lc/SearchinRotatedSortedArray2.java
package lc;
public class SearchinRotatedSortedArray2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public boolean search(int[] A, int target) {
int start = 0;
int end = A.length-1;
while(start+1<end){
int mid = start+(end-start)/2;
if(A[mid] == target){
return true;
}
if(A[mid] > A[start]){
if ( target < A[mid] && target >= A[start]){
end = mid-1;
} else {
start = mid+1;
}
} else if ( A[mid] < A[start]) {
if( target <= A[end] && target > A[mid] ) {
start = mid+1;
} else {
end = mid -1;
}
} else {
start++;
}
}
if(A[start] == target){
return true;
} else if(A[end] == target) {
return true;
} else {
return false;
}
}
public boolean search2(int[] A, int target) {
int start = 0;
int end = A.length-1;
while(start+1<end){
int mid = start+(end-start)/2;
if(A[mid] == target){
return true;
}
if(A[mid] == A[start] && A[mid] == A[end]){
for ( int i =start+1; i<end; i++){
if (A[i] == target) {
return true;
}
}
}
if(A[mid] >= A[start]){
if ( target < A[mid] && target >= A[start]){
end = mid-1;
} else {
start = mid+1;
}
} else if ( A[mid] <= A[end]) {
if( target <= A[end] && target > A[mid] ) {
start = mid+1;
} else {
end = mid -1;
}
}
}
if(A[start] == target){
return true;
} else if(A[end] == target) {
return true;
} else {
return false;
}
}
}
<file_sep>/lc/src/lc/EvaluateDivision.java
package lc;
import java.util.HashMap;
import java.util.HashSet;
/**
* Created by zzren on 9/21/2016.
*/
public class EvaluateDivision {
public static void main(String[] args){
String[][] equations = {{"a","b"},{"b","c"}};
double[] values ={2.0, 3.0};
String[][] queries = {{"a", "b"}};
System.out.println((new EvaluateDivision()).calcEquation(equations, values, queries)[0]);
}
public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
HashMap<String, HashMap<String, Double>> map = new HashMap<String, HashMap<String, Double>>();
for(int i=0;i<values.length;i++){
if(!map.containsKey(equations[i][0])){
map.put(equations[i][0], new HashMap<String, Double>());
}
map.get(equations[i][0]).put(equations[i][1], values[i]);
if(!map.containsKey(equations[i][1])){
map.put(equations[i][1], new HashMap<String, Double>());
}
map.get(equations[i][1]).put(equations[i][0], 1.0/values[i]);
}
double[] result = new double[queries.length];
for(int i=0;i<queries.length;i++){
if(!map.containsKey(queries[i][0]) || !map.containsKey(queries[i][1])){
result[i] = -1.0;
} else if(queries[i][0].equals(queries[i][1])){
result[i] = 1.0;
} else {
double[] res = new double[1];
res[0] = 1.0;
HashSet<String> visited = new HashSet<String>();
boolean suc = dfs(queries[i][0], queries[i][1], res, map, visited);
if(suc) {
result[i] = res[0];
} else {
result[i] = -1.0;
}
}
}
return result;
}
private boolean dfs(String start, String end, double[] result, HashMap<String, HashMap<String, Double>> map, HashSet<String> visited){
visited.add(start);
HashMap<String, Double> cur = map.get(start);
if(cur.containsKey(end)){
result[0] *= cur.get(end);
return true;
} else {
for(String next : cur.keySet()){
if(visited.contains(next)){
continue;
}
result[0] *= cur.get(next);
if(dfs(next, end, result, map, visited)){
return true;
}
result[0] /= cur.get(next);
}
}
return false;
}
}
<file_sep>/lc/src/lc/MergeTwoSortedLists.java
package lc;
public class MergeTwoSortedLists {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode cur1 = l1;
ListNode cur2 = l2;
ListNode head = new ListNode(0);
ListNode pre = head;
while(cur1!=null && cur2!=null){
if(cur1.val<=cur2.val){
ListNode cur3 = new ListNode(cur1.val);
pre.next = cur3;
pre = cur3;
cur1 = cur1.next;
} else {
ListNode cur3 = new ListNode(cur2.val);
pre.next = cur3;
pre = cur3;
cur2 = cur2.next;
}
}
if(cur1!=null){
while(cur1!=null){
ListNode cur3 = new ListNode(cur1.val);
pre.next = cur3;
pre = cur3;
cur1 = cur1.next;
}
}
if(cur2!=null){
while(cur2!=null){
ListNode cur3 = new ListNode(cur2.val);
pre.next = cur3;
pre = cur3;
cur2 = cur2.next;
}
}
return head.next;
}
}
<file_sep>/lc/src/lc/IntegertoRoman.java
package lc;
public class IntegertoRoman {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public String intToRoman(int num) {
StringBuilder sb = new StringBuilder();
int cnt_4th = num/1000;
for(int i=0;i<cnt_4th;i++){
sb.append('M');
}
int cnt_3rd = (num/100)%10;
if(cnt_3rd>0 && cnt_3rd<4){
for(int i=0;i<cnt_3rd;i++){
sb.append('C');
}
} else if(cnt_3rd == 4){
sb.append("CD");
} else if(cnt_3rd == 9){
sb.append("CM");
} else if(cnt_3rd>4 && cnt_3rd<9){
sb.append('D');
for(int i=0;i<(cnt_3rd-5);i++){
sb.append('C');
}
}
int cnt_2nd = (num/10)%10;
if(cnt_2nd>0 && cnt_2nd<4){
for(int i=0;i<cnt_2nd;i++){
sb.append('X');
}
} else if(cnt_2nd == 4){
sb.append("XL");
} else if(cnt_2nd == 9){
sb.append("XC");
} else if(cnt_2nd>4 && cnt_2nd<9){
sb.append('L');
for(int i=0;i<(cnt_2nd-5);i++){
sb.append('X');
}
}
int cnt_1st = num%10;
if(cnt_1st>0 && cnt_1st<4){
for(int i=0;i<cnt_1st;i++){
sb.append('I');
}
} else if(cnt_1st == 4){
sb.append("IV");
} else if(cnt_1st == 9){
sb.append("IX");
} else if(cnt_1st>4 && cnt_1st<9){
sb.append('V');
for(int i=0;i<(cnt_1st-5);i++){
sb.append('I');
}
}
return sb.toString();
}
}
<file_sep>/lc/src/lc/ImplementstrStr.java
package lc;
public class ImplementstrStr {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public int strStr(String haystack, String needle) {
int hay_len = haystack.length();
int nee_len = needle.length();
if(nee_len>hay_len){
return -1;
}
if(nee_len==0){
return 0;
}
for(int i=0;i<(hay_len-nee_len);i++){
boolean found = true;
for(int j=0;j<nee_len;j++){
if(needle.charAt(j)!=haystack.charAt(i+j)){
found = false;
break;
}
}
if(found){
return i;
}
}
return -1;
}
}
<file_sep>/lc/src/lc/BalancedBinaryTree.java
package lc;
public class BalancedBinaryTree {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public boolean isBalanced(TreeNode root) {
returnType ret = isBalancedHelper(root);
return ret.balanced;
}
private returnType isBalancedHelper(TreeNode root){
if(root == null){
return new returnType(true, 0);
}
returnType left_ret, right_ret;
if(root.left==null){
left_ret = new returnType(true, 0);
} else {
left_ret = isBalancedHelper(root.left);
}
if(root.right==null){
right_ret = new returnType(true, 0);
} else {
right_ret = isBalancedHelper(root.right);
}
int diff = left_ret.height - right_ret.height;
if(diff<=1 && diff>=-1){
return new returnType((left_ret.balanced && right_ret.balanced), Math.max(left_ret.height, right_ret.height)+1);
} else {
return new returnType(false, Math.max(left_ret.height, right_ret.height)+1);
}
}
class returnType{
boolean balanced;
int height;
returnType(boolean balanced, int height) { this.balanced = balanced; this.height = height;}
}
}<file_sep>/lc/src/lc/SpiralMatrix2.java
package lc;
public class SpiralMatrix2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int level = (n + 1)/2;
int current=1;
for(int i=0; i<level; i++ ){
for(int j=0;j<(n-2*i);j++){
matrix[i][i+j]=current;
current++;
}
for(int j=1;j<(n-2*i);j++){
matrix[i+j][n-1-i]=current;
current++;
}
for(int j=1;j<(n-2*i);j++){
matrix[n-1-i][n-1-i-j]=current;
current++;
}
for(int j=1;j<(n-2*i-1);j++){
matrix[n-1-i-j][i]=current;
current++;
}
}
return matrix;
}
}
<file_sep>/lc/src/lc/RotateImage.java
package lc;
public class RotateImage {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public void rotate(int[][] matrix) {
int row = matrix.length;
int column = matrix[0].length;
if(row!=column){
return;
} else {
int swap = 0;
for(int i=0; i<row/2; i++){
for(int j=0; j<(row+1)/2; j++){
swap = matrix[i][j];
matrix[i][j] = matrix[row-1-j][i];
matrix[row-1-j][i] = matrix[row-1-i][row-1-j];
matrix[row-1-i][row-1-j] = matrix[j][row-1-i];
matrix[j][row-1-i] = swap;
}
}
}
}
}
<file_sep>/lc/src/lc/ConstructBinaryTreefromInorderandPostorderTraversal.java
package lc;
public class ConstructBinaryTreefromInorderandPostorderTraversal {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder.length==0){
return null;
}
return buildHelper(inorder, postorder, 0, 0, postorder.length);
}
private TreeNode buildHelper(int[] inorder, int[] postorder, int begin1, int begin2, int len){
if(len == 1){
return new TreeNode(inorder[begin1]);
}
TreeNode root = new TreeNode(postorder[begin2+len-1]);
int i;
for(i=begin1;i<(begin1+len);i++){
if(inorder[i] == postorder[begin2+len-1]){
break;
}
}
if(i-1>=begin1){
root.left = buildHelper(inorder, postorder, begin1, begin2, i-begin1);
}
if((begin1+len-1)>=i+1){
root.right = buildHelper(inorder, postorder, i+1, begin2-begin1+i, begin1+len-1-i);
}
return root;
}
}
<file_sep>/lc/src/lc/Triangle.java
package lc;
import java.util.List;
public class Triangle {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public int minimumTotal(List<List<Integer>> triangle) {
int row = triangle.size();
if(row == 0){
return 0;
}
int maxline = triangle.get(row-1).size();
int[] result = new int[maxline];
for (int i =0; i< row; i++){
List<Integer> line = triangle.get(i);
if ( i ==0){
result [0] = line.get(0);
} else {
int line_size = line.size();
for(int j=line_size-1; j>=0; j--){
if(j == (line_size-1)){
result[j] = result[j-1]+line.get(j);
} else if ( j == 0) {
result[j] = result[j]+ line.get(j);
} else {
result[j] = Math.min(result[j], result[j-1])+line.get(j);
}
}
}
}
int min_result =result[0];
for(int i =1; i<maxline; i++){
if(result[i]<min_result){
min_result = result[i];
}
}
return min_result;
}
}
<file_sep>/lc/src/lc/FlattenBinaryTreetoLinkedList.java
package lc;
import java.util.LinkedList;
public class FlattenBinaryTreetoLinkedList {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode root = new TreeNode(1);
TreeNode left = new TreeNode(2);
TreeNode right = new TreeNode(3);
root.left = left;
root.right = right;
FlattenBinaryTreetoLinkedList q = new FlattenBinaryTreetoLinkedList();
q.flatten(root);
}
public void flatten(TreeNode root) {
flattenHelper(root);
}
private TreeNode flattenHelper(TreeNode root){
if(root == null){
return null;
}
TreeNode left = root.left;
TreeNode right = root.right;
root.left = null;
root.right = left;
TreeNode last1 = flattenHelper(left);
if(last1 == null){
last1 = root;
}
last1.left = null;
last1.right = right;
TreeNode last2 = flattenHelper(right);
if(last2 == null){
last2 = last1;
}
return last2;
}
}
<file_sep>/lc/src/lc/BestTimetoBuyandSellStock.java
package lc;
public class BestTimetoBuyandSellStock {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public int maxProfit(int[] prices) {
int len = prices.length;
if(len<=1){
return 0;
}
int[] result = new int[len];
int min=prices[0];
int max = 0;
for(int i=0;i<len;i++){
min = Math.min(min, prices[i]);
result[i] = prices[i]-min;
max = Math.max(max, result[i]);
}
return max;
}
}
<file_sep>/lc/src/lc/LinkedListCycle2.java
package lc;
public class LinkedListCycle2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public ListNode detectCycle(ListNode head) {
ListNode ptr1 = head;
ListNode ptr2 = head;
int circle = 0;
int total = 0;
boolean hasCycle = false;
while(ptr2!=null && ptr2.next!=null && ptr2.next.next!=null){
ptr1 = ptr1.next;
ptr2 = ptr2.next.next;
circle++;
if(ptr1 == ptr2){
hasCycle = true;
break;
}
}
if(!hasCycle){
return null;
}
ListNode ptr3 = head;
while(ptr1 != ptr3){
ptr1 = ptr1.next;
ptr3 = ptr3.next;
}
return ptr3;
}
}
<file_sep>/lc/src/lc/UniqueBinarySearchTrees2.java
package lc;
import java.util.ArrayList;
import java.util.List;
public class UniqueBinarySearchTrees2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public List<TreeNode> generateTrees(int n) {
return helper(1, n);
}
private ArrayList<TreeNode> helper(int start, int end){
ArrayList<TreeNode> result = new ArrayList<TreeNode>();
if(end<start){
result.add(null); //【注】加入一个空元素进去,来表示这是一颗空树,并且同时也是保证下面循环时,即使一边是空树,也让另一边继续运算。
return result;
}
for(int i = start; i<=end; i++){
ArrayList<TreeNode> lefts = helper(start, i-1);
ArrayList<TreeNode> rights = helper(i+1, end);
for(int k=0;k<lefts.size();k++){
for(int q=0;q<rights.size();q++){
TreeNode head = new TreeNode(i);
head.left = lefts.get(k);
head.right = rights.get(q);
result.add(head);
}
}
}
return result;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; left = null; right = null; }
}
<file_sep>/lc/src/lc/PartitionList.java
package lc;
public class PartitionList {
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode l1 = new ListNode(2);
ListNode l2 = new ListNode(1);
l1.next = l2;
ListNode newHead = partition(l1, 2);
while(newHead != null){
System.out.print(newHead.val + ",");
newHead = newHead.next;
}
}
public static ListNode partition(ListNode head, int x) {
if(head == null){
return null;
}
ListNode dummy1 = new ListNode(0);
ListNode dummy2 = new ListNode(0);
ListNode cur = head;
ListNode ptr1 = dummy1;
ListNode ptr2 = dummy2;
while( cur != null){
if(cur.val<x){
ptr1.next = cur;
ptr1 = ptr1.next;
} else {
ptr2.next = cur;
ptr2 = ptr2.next;
}
cur = cur.next;
}
ptr2.next = null;
ptr1.next = dummy2.next;
return dummy1.next;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
<file_sep>/lc/src/lc/BinarySearch.java
package lc;
public class BinarySearch {
public int binarySearch(int[] nums, int target) {
int start =0;
int end = nums.length-1;
while(start+1<end){
int mid = start + (end-start)/2;
if(nums[mid]==target){
end=mid;
} else if (nums[mid]<target){
start=mid;
}else{
end=mid;
}
}
if(nums[start]==target){
return start;
} else if (nums[end]==target){
return end;
} else {
return -1;
}
}
}
<file_sep>/lc/src/lc/SingleNumber3.java
package lc;
import java.util.LinkedList;
import java.util.List;
public class SingleNumber3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public List<Integer> singleNumberIII(int[] A) {
int result1 = 0;
for(int i=0;i<A.length;i++){
result1 ^= A[i];
}
int bias =0;
for(bias=0;bias<32;bias++){
if((result1>>bias & 1) == 1){
break;
}
}
int result2 = 0;
int result3 = 0;
for(int i=0;i<A.length;i++){
if((A[i]>>bias & 1) == 1){
result2 ^= A[i];
} else {
result3 ^= A[i];
}
}
List<Integer> result = new LinkedList<Integer>();
result.add(result2);
result.add(result3);
return result;
}
}
<file_sep>/lc/src/lc/RotateList.java
package lc;
public class RotateList {
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(2);
l1.next = l2;
ListNode head = rotateRight(l1, 1);
while (head != null){
System.out.print(head.val + ",");
head = head.next;
}
}
public static ListNode rotateRight(ListNode head, int n) {
if(head == null){
return null;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode ptr1 = head;
ListNode ptr2 = head;
int len =0;
while(ptr1 != null){
ptr1 = ptr1.next;
len++;
}
int bias = n%len;
if(bias == 0){
return head;
}
ptr1 = head;
for(int i=1;i<bias;i++){
ptr1 = ptr1.next;
}
while(ptr1.next != null){
ptr1 = ptr1.next;
ptr2 = ptr2.next;
pre = pre.next;
}
dummy.next = ptr2;
ptr1.next = head;
pre.next = null;
return dummy.next;
}
}
<file_sep>/lc/src/lc/SudokuSolver.java
package lc;
public class SudokuSolver {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public void solveSudoku(char[][] board) {
char[][] result = new char[9][9];
try{
helper(board, 0, 0, result);
} catch (Exception e) {
e.printStackTrace();
}
/*for(int p=0;p<9;p++){
for(int q=0;q<9;q++){
board[p][q] = result[p][q];
}
}*/
}
private void helper(char[][] board, int i, int j, char[][] result) throws Exception{
if(i==9){
/*for(int p=0;p<9;p++){
for(int q=0;q<9;q++){
result[p][q] = board[p][q];
}
}*/
throw (new Exception());
//return;
}
if(board[i][j]=='.'){
for(int k=1;k<10;k++){
if(isValid(board, i, j, k)){
board[i][j] =(char)('0'+k);
if(j==8){
helper(board, i+1, 0, result);
} else {
helper(board, i, j+1, result);
}
board[i][j]='.';
}
}
}
else {
if(j==8){
helper(board, i+1, 0, result);
} else {
helper(board, i, j+1, result);
}
}
}
private boolean isValid(char[][] board, int i, int j, int num){
for(int k=0;k<9;k++){
if(board[i][k]==(char)('0'+num)){
return false;
}
}
for(int k=0;k<9;k++){
if(board[k][j]==(char)('0'+num)){
return false;
}
}
for(int p=(i-i%3);p<(i-i%3+3);p++){
for(int q=(j-j%3);q<(j-j%3+3);q++){
if(board[p][q]==(char)('0'+num)){
return false;
}
}
}
return true;
}
}
<file_sep>/lc/src/lc/powxn.java
package lc;
public class powxn {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(pow(34.00515,-3));
}
public static double pow(double x, int n) {
if (x == 0){
return 0;
}
if(n==0){
return 1;
} else if(n == 1){
return x;
} else if (n == -1){
return 1/x;
}
double result;
double mid = pow(x, n/2);
if(n%2==1){
result = mid*mid*x;
} else if(n%2==-1) {
result = mid*mid/x;
} else {
result = mid*mid;
}
return result;
}
}
<file_sep>/lc/src/lc/ReconstructItinerary.java
package lc;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
/**
* Created by zzren on 9/21/2016.
*/
public class ReconstructItinerary {
public static void main(String[] args){
String[][] tickets = {{"JFK", "SFO"},{"JFK","SJC"},{"SJC", "JFK"}};
System.out.println((new ReconstructItinerary()).findItinerary(tickets));
}
public List<String> findItinerary(String[][] tickets) {
HashMap<String, PriorityQueue<String>> map = new HashMap<String, PriorityQueue<String>>();
for(int i=0;i<tickets.length;i++){
if(!map.containsKey(tickets[i][0])){
map.put(tickets[i][0], new PriorityQueue<String>());
}
map.get(tickets[i][0]).add(tickets[i][1]);
}
List<String> res = new LinkedList<String>();
helper(map, res, "JFK");
return res;
}
private void helper(HashMap<String, PriorityQueue<String>> map, List<String> res, String cur){
while(map.containsKey(cur) && !map.get(cur).isEmpty()){
helper(map, res, map.get(cur).poll());
}
res.add(0, cur);
}
}
<file_sep>/lc/src/lc/SpiralMatrix.java
package lc;
import java.util.ArrayList;
public class SpiralMatrix {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] matrix = new int[1][2];
matrix[0][0]=2;
matrix[0][1]=3;
spiralOrder(matrix);
}
public static ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> finallist = new ArrayList<Integer>();
int row = matrix.length;
if(row==0){
return finallist;
} else {
int column = matrix[0].length;
int level = (Math.min(row, column) + 1)/2;
for(int i=0; i<level; i++ ){
for(int j=0;j<(column-2*i);j++){
finallist.add(matrix[i][i+j]);
}
for(int j=1;j<(row-2*i);j++){
finallist.add(matrix[i+j][column-1-i]);
}
if(row-1-2*i != 0 && column-1-2*i != 0){
for(int j=1;j<(column-2*i);j++){
finallist.add(matrix[row-1-i][column-1-i-j]);
}
}
if(row-1-2*i != 0 && column-1-2*i != 0){
for(int j=1;j<(row-2*i-1);j++){
finallist.add(matrix[row-1-i-j][i]);
}
}
}
return finallist;
}
}
public static ArrayList<Integer> spiralOrder_old(int[][] matrix) {
ArrayList<Integer> finallist = new ArrayList<Integer>();
int row = matrix.length;
if(row==0){
return finallist;
} else {
int column = matrix[0].length;
int level = (Math.min(row, column) + 1)/2;
for(int i=0; i<level; i++ ){
if(column-1-2*i != 0){
for(int j=0;j<(column-2*i);j++){
finallist.add(matrix[i][i+j]);
}
}
if(row-1-2*i != 0){
if(column-1-2*i != 0){
finallist.remove(finallist.size()-1);
}
for(int j=0;j<(row-2*i);j++){
finallist.add(matrix[i+j][column-1-i]);
}
}
if(column-1-2*i != 0 && row-1-2*i != 0){
finallist.remove(finallist.size()-1);
for(int j=0;j<(column-2*i);j++){
finallist.add(matrix[row-1-i][column-1-i-j]);
}
}
if(row-1-2*i != 0 && column-1-2*i != 0){
finallist.remove(finallist.size()-1);
for(int j=0;j<(row-2*i);j++){
finallist.add(matrix[row-1-i-j][i]);
}
finallist.remove(finallist.size()-1);
}
if (row-1-2*i == 0 && column-1-2*i == 0){
finallist.add(matrix[i][i]);
}
}
return finallist;
}
}
}
<file_sep>/lc/src/lc/FirstMissingPositive.java
package lc;
public class FirstMissingPositive {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public int firstMissingPositive(int[] A) {
int result=-1;
int len = A.length;
for (int i=0; i<len; i++){
if (A[i]<=0){
A[i] = len+1;
}
}
for (int i=0; i<len; i++){
if(A[i]>0 && A[i]<=len){
if(A[A[i]-1]>0){
A[A[i]-1] = A[A[i]-1]+Integer.MIN_VALUE;
}
}
else if (A[i]<=0){
int original = A[i]-Integer.MIN_VALUE;
if(original <=len && A[original-1]>0){
A[original-1] = A[original-1]+Integer.MIN_VALUE;
}
}
}
for (int i=0; i<len; i++){
if (A[i]>0){
result = i+1;
break;
}
}
if(result==-1){
result=len+1;
}
return result;
}
}
<file_sep>/lc/src/lc/CombinationSum2.java
package lc;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CombinationSum2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public List<List<Integer>> combinationSum2(int[] num, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
ArrayList<Integer> item = new ArrayList<Integer>();
boolean[] used = new boolean[num.length];
for(int i=0;i<num.length;i++){
used[i] = false;
}
Arrays.sort(num);
permutehelper(result, item, num, used, target, 0);
return result;
}
private void permutehelper(List<List<Integer>> result, List<Integer> item, int[] num, boolean[] used, int target, int pos){
if(target == 0){
ArrayList<Integer> newitem = new ArrayList<Integer>(item);
result.add(newitem);
return;
}
if (target < 0 ){
return;
}
for(int i=pos;i<num.length;i++){
if(i==0 || num[i] > num[i-1] || (num[i] == num[i-1] && used[i-1])){
item.add(num[i]);
used[i] = true;
permutehelper(result, item, num, used, target-num[i], i+1);
item.remove(item.size()-1);
used[i] = false;
}
}
}
}
<file_sep>/lc/src/lc/countTriangles.java
package lc;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
public class countTriangles {
public static void main(String[] args) {
// TODO Auto-generated method stub
GraphNode n1 = new GraphNode(1);
GraphNode n2 = new GraphNode(2);
GraphNode n3 = new GraphNode(3);
GraphNode n4 = new GraphNode(4);
GraphNode n5 = new GraphNode(5);
GraphNode n6 = new GraphNode(6);
GraphNode n7 = new GraphNode(7);
GraphNode n8 = new GraphNode(8);
ArrayList<GraphNode> nb1 = new ArrayList<GraphNode>();
nb1.add(n2);
nb1.add(n3);
n1.neighbors = nb1;
ArrayList<GraphNode> nb2 = new ArrayList<GraphNode>();
nb2.add(n1);
nb2.add(n3);
nb2.add(n4);
nb2.add(n5);
n2.neighbors = nb2;
ArrayList<GraphNode> nb3 = new ArrayList<GraphNode>();
nb3.add(n1);
nb3.add(n2);
nb3.add(n6);
//nb3.add(n5);
n3.neighbors = nb3;
ArrayList<GraphNode> nb4 = new ArrayList<GraphNode>();
nb4.add(n2);
n4.neighbors = nb4;
ArrayList<GraphNode> nb5 = new ArrayList<GraphNode>();
nb5.add(n2);
nb5.add(n6);
nb5.add(n7);
nb5.add(n8);
//nb5.add(n3);
n5.neighbors = nb5;
ArrayList<GraphNode> nb6 = new ArrayList<GraphNode>();
nb6.add(n3);
nb6.add(n5);
nb6.add(n8);
n6.neighbors = nb6;
ArrayList<GraphNode> nb7 = new ArrayList<GraphNode>();
nb7.add(n5);
nb7.add(n8);
n7.neighbors = nb6;
ArrayList<GraphNode> nb8 = new ArrayList<GraphNode>();
nb8.add(n5);
nb8.add(n6);
nb8.add(n7);
n8.neighbors = nb8;
countTriangles q = new countTriangles();
System.out.println(q.countTriangle(n1));
/*
* 1
* / \
* 2 - 3
* / \ \
* 4 5 - 6
* / \ /
* 7 - 8
*/
}
public int countTriangle(GraphNode node) {
int result = 0;
HashSet<GraphNode> used = new HashSet<GraphNode>();
LinkedList<GraphNode> queue = new LinkedList<GraphNode>();
queue.offer(node);
while(!queue.isEmpty()){
GraphNode cur = queue.poll();
if(!used.contains(cur)){
used.add(cur);
ArrayList<GraphNode> neighbors = cur.neighbors;
int count = neighbors.size();
System.out.println("cur"+cur.label+","+count);
for(int i=0;i<count;i++){
if(!used.contains(neighbors.get(i))){
queue.offer(neighbors.get(i));
for(int j=i+1;j<count;j++){
if(!used.contains(neighbors.get(j)) && neighbors.get(i).neighbors.contains(neighbors.get(j))){
result++;
}
}
}
}
}
}
return result;
}
}
class GraphNode {
int label;
ArrayList<GraphNode> neighbors;
GraphNode(int x) {
label = x;
neighbors = new ArrayList<GraphNode>();
}
}
<file_sep>/lc/src/lc/EvaluateReversePolishNotation.java
package lc;
import java.util.LinkedList;
public class EvaluateReversePolishNotation {
public static void main(String[] args) {
String[] tokens = {"0","3","/"};
System.out.println(evalRPN(tokens));
}
public static int evalRPN(String[] tokens) {
LinkedList<Integer> stack = new LinkedList<Integer>();
for(int i=0;i<tokens.length;i++){
if(tokens[i].equals("+")){
stack.push(stack.pop()+stack.pop());
} else if(tokens[i].equals("-")){
stack.push(0-stack.pop()+stack.pop());
} else if(tokens[i].equals("*")){
stack.push(stack.pop()*stack.pop());
} else if(tokens[i].equals("/")){
int a = stack.pop();
int b = stack.pop();
stack.push(b/a);
} else {
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.pop();
}
}
<file_sep>/lc/src/lc/MaxPointsonaLine.java
package lc;
import java.util.HashMap;
public class MaxPointsonaLine {
public static void main(String[] args) {
// TODO Auto-generated method stub
Point[] p = {new Point(2,3), new Point(3,3), new Point(-5, 3)};
System.out.println(maxPoints(p));
}
public static int maxPoints(Point[] points) {
if(points.length == 0){
return 0;
}
if(points.length == 1){
return 1;
}
int max=2;
for(int i=0;i<(points.length-1);i++){
int cur_max=0;
int duplicate =1;
HashMap<Double, Integer> map = new HashMap<Double, Integer>();
for(int j=i+1;j<points.length;j++){
if(points[i].x == points[j].x && points[i].y == points[j].y){
duplicate++;
} else if(points[i].x == points[j].x){
double slope = Integer.MAX_VALUE;
if(map.containsKey(slope)){
map.put(slope, map.get(slope)+1);
} else {
map.put(slope, 1);
}
cur_max = Math.max(cur_max, map.get(slope));
} else if (points[i].y == points[j].y){
if(map.containsKey(0.0)){
map.put(0.0, map.get(0.0)+1);
} else {
map.put(0.0, 1);
}
cur_max = Math.max(cur_max, map.get(0.0));
} else{
double slope = (double)(points[i].y - points[j].y)/(double)(points[i].x - points[j].x);
//System.out.println(slope);
if(map.containsKey(slope)){
map.put(slope, map.get(slope)+1);
} else {
map.put(slope, 1);
}
cur_max = Math.max(cur_max, map.get(slope));
}
}
max = Math.max(max, cur_max+duplicate);
}
return max;
}
}
class Point {
int x;
int y;
Point() { x = 0; y = 0; }
Point(int a, int b) { x = a; y = b; }
}
<file_sep>/lc/src/lc/AddTwoNumbers.java
package lc;
public class AddTwoNumbers {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode cur1 = l1;
ListNode cur2 = l2;
ListNode dummy = new ListNode(0);
ListNode cur3 = dummy;
int carry = 0;
while(cur1 != null || cur2 != null){
int sum = (cur1==null?0:cur1.val) + (cur2==null?0:cur2.val) + carry;
carry = sum/10;
cur3.next = new ListNode(sum%10);
cur1 = (cur1==null?null:cur1.next);
cur2 = (cur2==null?null:cur2.next);
cur3 = cur3.next;
}
if(carry != 0){
cur3.next = new ListNode(carry);
}
return dummy.next;
}
}
<file_sep>/lc/src/lc/CombinationSum.java
package lc;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CombinationSum {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
ArrayList<Integer> item = new ArrayList<Integer>();
Arrays.sort(candidates);
permutehelper(result, item, candidates, target);
return result;
}
private void permutehelper(List<List<Integer>> result, List<Integer> item, int[] candidates, int target){
if(target == 0){
ArrayList<Integer> newitem = new ArrayList<Integer>(item);
result.add(newitem);
return;
}
if (target < 0){
return;
}
for(int i=0;i<candidates.length;i++){
if(item.size() == 0 || candidates[i] >= item.get(item.size()-1)){
item.add(candidates[i]);
permutehelper(result, item, candidates, target-candidates[i]);
item.remove(item.size()-1);
}
}
}
}
<file_sep>/lc/src/lc/SwapNodesinPairs.java
package lc;
public class SwapNodesinPairs {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode p1 = head;
ListNode post = head;
while(p1 != null && p1.next !=null){
post = p1.next.next;
pre.next = p1.next;
p1.next.next = p1;
p1.next = post;
pre = p1;
p1 = p1.next;
}
return dummy.next;
}
}
<file_sep>/lc/src/lc/RemoveNodeinBinarySearchTree.java
package lc;
public class RemoveNodeinBinarySearchTree {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode n1 = new TreeNode(1);
TreeNode n2 = new TreeNode(2);
TreeNode n3 = new TreeNode(3);
TreeNode n4 = new TreeNode(4);
TreeNode n5 = new TreeNode(5);
n1.right=n2;
n2.right=n3;
n3.right=n4;
n4.right=n5;
RemoveNodeinBinarySearchTree q = new RemoveNodeinBinarySearchTree();
q.removeNode(n1, 3);
}
public TreeNode removeNode(TreeNode root, int value) {
if(root == null){
return null;
}
boolean exist = false;
TreeNode cur = root;
TreeNode parent = null;
boolean isLeftChild = false;
while(cur!=null){
if(cur.val == value){
exist = true;
break;
} else if (cur.val > value){
parent = cur;
isLeftChild = true;
cur = cur.left;
} else if(cur.val < value){
parent = cur;
isLeftChild = false;
cur = cur.right;
}
}
if(exist){
if(cur.left == null && cur.right == null){
if(parent == null){
return null;
}
if(isLeftChild){
parent.left = null;
} else {
parent.right = null;
}
} else if(cur.left == null){
TreeNode rightmin = cur.right;
TreeNode rightminparent = cur;
while(rightmin.left!=null){
rightminparent = rightmin;
rightmin = rightmin.left;
}
cur.val = rightmin.val;
if(rightminparent.left!=null && rightminparent.left.val == rightmin.val){
rightminparent.left = rightmin.right;
} else {
rightminparent.right = rightmin.right;
}
} else {
TreeNode leftmax = cur.left;
TreeNode leftmaxparent = cur;
while(leftmax.right!=null){
leftmaxparent = leftmax;
leftmax = leftmax.right;
}
cur.val = leftmax.val;
if(leftmaxparent.left!=null && leftmaxparent.left.val == leftmax.val){
leftmaxparent.left = leftmax.left;
} else {
leftmaxparent.right = leftmax.left;
}
}
}
return root;
}
}
<file_sep>/lc/src/lc/SubstringwithConcatenationofAllWords.java
package lc;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class SubstringwithConcatenationofAllWords {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] L ={"fooo","barr","wing","ding","wing"};
String S = "";
List result = (new SubstringwithConcatenationofAllWords()).findSubstring(S, L);
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i));
}
}
public List<Integer> findSubstring(String S, String[] L) {
List<Integer> result = new ArrayList<Integer>();
if(L.length==0){
for(int i=0;i<S.length();i++){
result.add(i);
}
return result;
}
HashMap<String, Integer> orig_map = new HashMap<String, Integer>();
HashMap<String, Integer> copy_map = new HashMap<String, Integer>();
for(String s:L){
if(orig_map.containsKey(s)){
orig_map.put(s, orig_map.get(s)+1);
copy_map.put(s, copy_map.get(s)+1);
}
else {
orig_map.put(s, 1);
copy_map.put(s, 1);
}
}
int len = L[0].length();
int idx = 0;
while((idx+len*L.length)<=S.length()){
int start = idx;
String sub = S.substring(idx, idx+len);
while(copy_map.size()!=0 && copy_map.containsKey(sub)){
if(copy_map.get(sub)==1){
copy_map.remove(sub);
}
else {
copy_map.put(sub, copy_map.get(sub)-1);
}
idx+=len;
if(idx+len<=S.length()){
sub = S.substring(idx, idx+len);
}
else{
break;
}
}
if(copy_map.size()==0){
result.add(start);
}
if(start!=idx){
for(String s:orig_map.keySet()){
copy_map.put(s, orig_map.get(s));
}
}
idx = start+1;
}
return result;
}
}
<file_sep>/lc/src/lc/ReverseWordsinaString.java
package lc;
public class ReverseWordsinaString {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(reverseWords("ab b"));
}
public static String reverseWords(String s) {
String s_trim = s.trim();
if(s.length()==0){
return "";
}
StringBuilder sb = new StringBuilder();
String[] tokens = s_trim.split("\\s+");
for(int i=tokens.length-1;i>=0;i--){
sb.append(tokens[i]+" ");
}
if(sb.charAt(sb.length()-1) == ' '){
sb.deleteCharAt(sb.length()-1);
}
return sb.toString();
}
public static String reverseWords2(String s) {
StringBuilder sb = new StringBuilder(s.trim());
if(sb.length()==0){
return "";
}
reverseHelper(sb, 0, sb.length()-1);
int start=0;
for(int i=0;i<sb.length();i++){
if(i==(sb.length()-1)){
if(i>start){
reverseHelper(sb, start, i);
}
}
if(sb.charAt(i)==' '){
if(i-1>start){
reverseHelper(sb, start, i-1);
}
if(i-1>=0 && sb.charAt(i-1)==' '){
sb.deleteCharAt(i);
i--;
}
start = i+1;
}
}
return sb.toString();
}
private static void reverseHelper(StringBuilder sb, int begin, int end){
for(int i=begin;i<=(end+begin)/2;i++){
char temp = sb.charAt(i);
sb.setCharAt(i, sb.charAt(begin+end-i));
sb.setCharAt(begin+end-i, temp);
}
}
}
<file_sep>/lc/src/lc/InsertionSortList.java
package lc;
public class InsertionSortList {
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(2);
ListNode l3 = new ListNode(3);
l3.next = l2;
l2.next = l1;
ListNode head2 = insertionSortList(l3);
while(head2 != null){
System.out.print(head2.val + ",");
head2 = head2.next;
}
}
public static ListNode insertionSortList(ListNode head) {
if(head == null){
return null;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = head;
ListNode pre = dummy;
while(cur != null){
ListNode compare = dummy;
boolean set = false;
while(compare.next != cur && compare.next != null){
if(compare.next.val>cur.val){
ListNode tmp1 = compare.next;
ListNode tmp2 = cur.next;
compare.next = cur;
cur.next = tmp1;
pre.next = tmp2;
cur = tmp2;
set = true;
break;
} else {
compare = compare.next;
}
}
if(!set){
pre = cur;
cur = cur.next;
}
}
return dummy.next;
}
}
<file_sep>/lc/src/lc/RegularExpressionMatching.java
package lc;
public class RegularExpressionMatching {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(isMatch("aa","a"));
System.out.println(isMatch("aa","aa"));
System.out.println(isMatch("aaa","aa"));
System.out.println(isMatch("aa", "a*"));
System.out.println(isMatch("aa", ".*"));
System.out.println(isMatch("ab", ".*"));
System.out.println(isMatch("aab", "c*a*b"));
}
public static boolean isMatch(String s, String p) {
int len1 = s.length();
int len2 = p.length();
boolean[][] result = new boolean[len1+1][len2+1];
result[0][0] = true;
for(int i=1;i<=len1;i++){
result[i][0] = false;
}
for(int i=0;i<=len1;i++){
for(int j=1;j<=len2;j++){
if(p.charAt(j-1) =='*'){
if(i==0){
result[i][j] = result[i][j-2];
} else {
// 0个* >0个*
result[i][j] = result[i][j-2] | ((s.charAt(i-1)==p.charAt(j-2) | p.charAt(j-2)=='.') & result[i-1][j]);
}
} else {
if(i==0){
result[i][j] = false;
} else if(s.charAt(i-1)==p.charAt(j-1) | p.charAt(j-1)=='.'){
result[i][j] = result[i-1][j-1];
} else {
result[i][j] = false;
}
}
}
}
return result[len1][len2];
}
}
<file_sep>/lc/src/lc/NextPermutation.java
package lc;
import java.util.Arrays;
public class NextPermutation {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public void nextPermutation(int[] num) {
if(num.length==0 || num.length == 1){
return;
}
int pre = num[num.length-1];
for(int i=num.length-2;i>=0;i--){
int cur = num[i];
if(pre>cur){
int minabovecur = pre;
int idx = i+1;
for(int j=i+1;j<num.length;j++){
if(num[j]>cur && num[j]<minabovecur){
minabovecur = num[j];
idx = j;
}
}
num[i] = minabovecur;
num[idx] = cur;
Arrays.sort(num, i+1, num.length);
return;
} else {
pre = cur;
}
}
Arrays.sort(num, 0, num.length);
}
}
<file_sep>/lc/src/lc/LRUCache.java
package lc;
import java.util.ArrayList;
import java.util.HashMap;
public class LRUCache {
private HashMap<Integer, DoubleLinkedListNode> map = new HashMap<Integer, DoubleLinkedListNode>();
private DoubleLinkedList queue = new DoubleLinkedList(new DoubleLinkedListNode(0, 0), new DoubleLinkedListNode(0, 0));
private int size = 0;
private int capacity = 0;
public LRUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
if(map.containsKey(key)){
DoubleLinkedListNode cur = map.get(key);
if(queue.head.next != cur){
queue.remove(cur);
queue.insert(queue.head, cur);
}
return cur.value;
}
return -1;
}
public void set(int key, int value) {
if(map.containsKey(key)){
DoubleLinkedListNode cur = map.get(key);
cur.value = value;
queue.remove(cur);
queue.insert(queue.head, cur);
}
else {
if(size<capacity){
size++;
}
else {
DoubleLinkedListNode leastused = queue.tail.prev;
queue.remove(leastused);
map.remove(leastused.key);
}
DoubleLinkedListNode cur = new DoubleLinkedListNode(key, value);
map.put(key, cur);
queue.insert(queue.head, cur);
}
}
}
class DoubleLinkedList{
DoubleLinkedListNode head, tail;
DoubleLinkedList(DoubleLinkedListNode head, DoubleLinkedListNode tail){
this.head = head;
this.tail = tail;
head.next = tail;
tail.prev = head;
}
public void remove(DoubleLinkedListNode cur){
DoubleLinkedListNode pre = cur.prev;
DoubleLinkedListNode next = cur.next;
pre.next= next;
next.prev = pre;
}
public void insert(DoubleLinkedListNode before, DoubleLinkedListNode cur){
DoubleLinkedListNode after = before.next;
before.next = cur;
after.prev = cur;
cur.next = after;
cur.prev = before;
}
}
class DoubleLinkedListNode{
int key, value;
DoubleLinkedListNode prev, next;
DoubleLinkedListNode(int k, int v){
key = k;
value = v;
}
}
<file_sep>/lc/src/lc/EditDistance.java
package lc;
public class EditDistance {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public int minDistance(String word1, String word2) {
int len1 = word1.length();
int len2 = word2.length();
int result[][] = new int[len1+1][len2+1];
for(int i=0;i<=len1;i++){
result[i][0]=i;
}
for(int i=0;i<=len2;i++){
result[0][i]=i;
}
for(int i=1;i<=len1;i++){
for(int j=1;j<=len2;j++){
if(word1.charAt(i-1) == word2.charAt(j-1)){
result[i][j] = result[i-1][j-1];
} else {
result[i][j] = Math.min(Math.min(result[i-1][j]+1, result[i][j-1]+1), result[i-1][j-1]+1);
}
}
}
return result[len1][len2];
}
}
<file_sep>/lc/src/lc/KthLargestElementinanArray.java
package lc;
/**
* Created by zzren on 7/15/2016.
*/
public class KthLargestElementinanArray {
public int findKthLargest(int[] nums, int k) {
int len = nums.length;
if(len ==0 || k > len){
return 0;
}
return select(nums, 0, len-1, k-1);
}
private int select(int[] nums, int start, int end, int k){
if(start == end){
return nums[start];
}
int pivotIdx = start + (int)Math.floor(Math.random() * (end - start + 1));
int curIdx = partition(nums, start, end, pivotIdx);
if(curIdx == k){
return nums[k];
} else if(curIdx < k){
return select(nums, curIdx+1, end, k);
} else {
return select(nums, start, curIdx-1, k);
}
}
private int partition(int[] nums, int start, int end, int pivotIdx){
int pivot = nums[pivotIdx];
swap(nums, pivotIdx, end);
int curIdx = start;
for(int i=start;i<=end;i++){
if(nums[i] > pivot){
swap(nums, curIdx, i);
curIdx++;
}
}
swap(nums, curIdx, end);
return curIdx;
}
private void swap(int[] nums, int a, int b){
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
}
<file_sep>/lc/src/lc/SearchRangeinBinarySearchTree.java
package lc;
import java.util.ArrayList;
public class SearchRangeinBinarySearchTree {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) {
ArrayList<Integer> result = new ArrayList<Integer>();
if(root == null){
return result;
}
boolean goLeft = false;
boolean goRight = false;
boolean includeRoot = false;
if(root.val<k2 && root.val>k1){
goLeft = true;
goRight = true;
includeRoot = true;
} else if (root.val<k1){
goRight = true;
} else if(root.val==k1){
goRight = true;
includeRoot = true;
} else if(root.val>k2){
goLeft = true;
} else if(root.val==k2){
goLeft = true;
includeRoot = true;
}
ArrayList<Integer> left =null, right = null;
if(root.left!=null && goLeft){
left = searchRange(root.left, k1, k2);
}
if(root.right!=null && goRight){
right = searchRange(root.right, k1, k2);
}
if(left!=null){
result.addAll(left);
}
if(includeRoot){
result.add(root.val);
}
if(right!=null){
result.addAll(right);
}
return result;
}
}
<file_sep>/lc/src/lc/PascalsTriangle2.java
package lc;
import java.util.ArrayList;
public class PascalsTriangle2 {
public static void main(String[] args){
System.out.print(getRow(2));
}
public static ArrayList<Integer> getRow(int rowIndex) {
ArrayList<Integer> row = new ArrayList<Integer>();
for (int i=0; i<=rowIndex; i++){
if(i==0){
row.add(1);
} else {
int middle = 1;
for (int j=0;j<(i-1);j++){
int add1 = middle;
int add2 = row.get(j+1);
row.set(j+1, add1+add2);
middle = add2;
}
row.add(1);
}
}
return row;
}
}
<file_sep>/lc/src/lc/ValidateBinarySearchTree.java
package lc;
public class ValidateBinarySearchTree {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public boolean isValidBST(TreeNode root) {
if(root == null){
return true;
}
return isValidBSTHelper(root).isValid;
}
private returnType isValidBSTHelper(TreeNode root){
returnType result = new returnType(false, Integer.MAX_VALUE, Integer.MIN_VALUE);
boolean minset = false;
boolean maxset = false;
if(root.left!=null){
returnType left = isValidBSTHelper(root.left);
if(!left.isValid || left.max>=root.val){
return result;
}
result.min = left.min;
minset = true;
}
if(root.right!=null){
returnType right = isValidBSTHelper(root.right);
if(!right.isValid || right.min<=root.val){
return result;
}
result.max = right.max;
maxset = true;
}
result.isValid = true;
if(!minset){
result.min = root.val;
}
if(!maxset){
result.max = root.val;
}
return result;
}
class returnType{
int min;
int max;
boolean isValid;
returnType(boolean isValid, int max, int min){this.isValid=isValid; this.max=max; this.min=min;}
}
}
<file_sep>/lc/src/lc/Permutations.java
package lc;
import java.util.ArrayList;
import java.util.List;
public class Permutations {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public List<List<Integer>> permute(int[] num) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
ArrayList<Integer> item = new ArrayList<Integer>();
permutehelper(result, item, num);
return result;
}
private void permutehelper(List<List<Integer>> result, List<Integer> item, int[] num){
if(item.size() == num.length){
ArrayList<Integer> newitem = new ArrayList<Integer>(item);
result.add(newitem);
return;
}
for(int i=0;i<num.length;i++){
if(!item.contains(num[i])){
item.add(num[i]);
permutehelper(result, item, num);
item.remove(item.size()-1);
}
}
}
}
<file_sep>/lc/src/lc/MaximalRectangle.java
package lc;
import java.util.Stack;
public class MaximalRectangle {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public int maximalRectangle(char[][] matrix) {
if(matrix== null || matrix.length==0){
return 0;
}
int max = 0;
int[] height = new int[matrix[0].length];
for(int i=0;i<matrix.length;i++){
for(int j=0;j<matrix[0].length;j++){
if(matrix[i][j] == '0'){
height[j] = 0;
} else {
height[j]++;
}
}
max = Math.max(max, largestRectangleArea(height));
}
return max;
}
private int largestRectangleArea(int[] height) {
if(height==null || height.length==0){
return 0;
}
int max = 0;
Stack<Integer> stack = new Stack<Integer>();
for(int i=0;i<=height.length;i++){
int cur_hei = (i==height.length)? 0: height[i];
while(!stack.isEmpty() && height[stack.peek()]>=cur_hei){
int idx = stack.pop();
if(stack.isEmpty()){
max = Math.max(max, height[idx]*i);
} else {
max = Math.max(max, height[idx]*(i-stack.peek()-1));
}
}
stack.push(i);
}
return max;
}
}
<file_sep>/lc/src/lc/NQueens.java
package lc;
import java.util.ArrayList;
import java.util.List;
public class NQueens {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public List<String[]> solveNQueens(int n) {
List<String[]> result = new ArrayList<String[]>();
StringBuilder[] item = new StringBuilder[n];
char[] line = new char[n];
for(int i=0;i<n;i++){
line[i] = '.';
}
for(int i=0;i<n;i++){
item[i] = new StringBuilder(new String(line));
}
helper(result, item, n, 0);
return result;
}
private void helper(List<String[]> result, StringBuilder[] item, int n, int line){
if(line==n){
String[] newitem = new String[n];
for(int i=0;i<n;i++){
newitem[i] = new String(item[i]);
}
result.add(newitem);
return;
}
for(int j=0;j<n;j++){
if(!isConflict(item,n,line,j)){
item[line].replace(j, j+1, "Q");
helper(result, item, n, line+1);
item[line].replace(j, j+1, ".");
}
}
}
private boolean isConflict(StringBuilder[] result, int n, int i, int j){
for(int k=0;k<n;k++){
if(result[i].charAt(k)=='Q'){
return true;
}
if(result[k].charAt(j)=='Q'){
return true;
}
}
int k=1;
while((i-k)>=0 && (j-k)>=0){
if(result[i-k].charAt(j-k)=='Q'){
return true;
}
k++;
}
k=1;
while((i+k)<n && (j+k)<n){
if(result[i+k].charAt(j+k)=='Q'){
return true;
}
k++;
}
k=1;
while((i+k)<n && (j-k)>=0){
if(result[i+k].charAt(j-k)=='Q'){
return true;
}
k++;
}
k=1;
while((i-k)>=0 && (j+k)<n){
if(result[i-k].charAt(j+k)=='Q'){
return true;
}
k++;
}
return false;
}
}
<file_sep>/lc/src/lc/LargestNumber.java
package lc;
import java.util.Arrays;
import java.util.Comparator;
public class LargestNumber {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public String largestNumber(int[] num) {
StringBuilder sb = new StringBuilder();
Integer[] nums = new Integer[num.length];
boolean isAllZero = true;
for(int i=0;i<num.length;i++){
nums[i] = Integer.valueOf(num[i]);
if(num[i] != 0){
isAllZero = false;
}
}
if(isAllZero){
return "0";
}
Arrays.sort(nums, new Comparator<Integer>(){
@Override
public int compare(Integer a, Integer b){
String ab = a.toString() + b.toString();
String ba = b.toString() + a.toString();
for(int i =0;i<ab.length();i++){
if(ab.charAt(i) > ba.charAt(i)){
return -1;
} else if(ab.charAt(i) < ba.charAt(i)){
return 1;
}
}
return 0;
}
});
for(int i=0;i<nums.length;i++){
sb.append(nums[i]);
}
return sb.toString();
}
}
<file_sep>/lc/src/lc/RestoreIPAddresses.java
package lc;
import java.util.ArrayList;
import java.util.List;
public class RestoreIPAddresses {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public List<String> restoreIpAddresses(String s) {
List<String> result = new ArrayList<String>();
StringBuilder item = new StringBuilder();
helper(result, item, s, 0, 0);
return result;
}
private void helper(List<String> result, StringBuilder item, String s, int divide, int start){
if(divide>4){
return;
}
if(start==s.length()){
if(divide==4){
result.add(new String(item));
}
return;
}
for(int i=0;i<3;i++){
if(start+i<s.length()){
String sub = s.substring(start, start+i+1);
if(isValid(sub)){
int end1 = item.length();
if(start==0){
item.append(sub);
} else {
item.append("."+sub);
}
int end2 = item.length();
helper(result, item, s, divide+1, start+i+1);
item.delete(end1, end2);
}
}
}
}
private boolean isValid(String s){
if(s.charAt(0)=='0' && s.length()!=1){
return false;
}
int value = Integer.parseInt(s);
if(value>=0 && value<=255){
return true;
}
return false;
}
}
<file_sep>/lc/src/lc/RecoverBinarySearchTree.java
package lc;
import java.util.LinkedList;
import java.util.List;
public class RecoverBinarySearchTree {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public void recoverTree(TreeNode root) {
if(root == null){
return;
}
TreeNode[] wronglist = new TreeNode[2];
wronglist[0] = null;
wronglist[1] = null;
LinkedList<TreeNode> pre = new LinkedList<TreeNode>();
inOrderTraverse(root, pre, wronglist);
if(wronglist[0] != null && wronglist[1] != null){
int temp = wronglist[0].val;
wronglist[0].val = wronglist[1].val;
wronglist[1].val = temp;
}
}
private void inOrderTraverse(TreeNode root, LinkedList<TreeNode> pre, TreeNode[] wronglist){
if(root.left!=null){
inOrderTraverse(root.left, pre, wronglist);
}
if(wronglist[0]==null && !pre.isEmpty() && pre.getFirst().val>root.val){
wronglist[0] = pre.getFirst();
wronglist[1] = root;
}
if(wronglist[0] != null && !pre.isEmpty() && pre.getFirst().val>root.val){
wronglist[1] = root;
}
pre.addFirst(root);
if(root.right!=null){
inOrderTraverse(root.right, pre, wronglist);
}
}
public void recoverTree2(TreeNode root) {
if(root == null){
return;
}
TreeNode wrong1=null, wrong2=null, pre = new TreeNode(Integer.MIN_VALUE);
LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
boolean goLeft =true;
stack.push(root);
while(!stack.isEmpty()){
TreeNode cur = stack.peek();
if(goLeft){
while(cur.left != null){
stack.push(cur.left);
cur = cur.left;
}
}
cur = stack.pop();
if(wrong1 == null && cur.val < pre.val){
wrong1 = pre;
}
if(wrong1 != null && wrong2 == null){
if(cur.val < wrong1.val && (cur.right==null && stack.isEmpty())){
wrong2 = cur;
break;
}
if(cur.val > wrong1.val){
wrong2 = pre;
break;
}
}
pre = cur;
if(cur.right!=null){
stack.push(cur.right);
goLeft=true;
} else {
goLeft=false;
}
}
if(wrong1 != null && wrong2 != null){
int temp = wrong1.val;
wrong1.val = wrong2.val;
wrong2.val = temp;
}
}
}
<file_sep>/lc/src/lc/TextJustification.java
package lc;
import java.util.LinkedList;
import java.util.List;
public class TextJustification {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public List<String> fullJustify(String[] words, int L) {
List<String> result = new LinkedList<String>();
if(words==null || words.length==0){
return result;
}
int idx =0;
while(idx<words.length){
StringBuilder sb = new StringBuilder(words[idx]);
int cur_len = words[idx].length();
int count = 1;
while((idx+count)<words.length && (cur_len+words[idx+count].length()+1)<=L){
sb.append(" "+words[idx+count]);
cur_len += words[idx+count].length()+1;
count++;
}
if(idx+count == words.length){
for(int i=0;i<(L-cur_len);i++){
sb.append(' ');
}
result.add(sb.toString());
return result;
}
if(count==1){
for(int i=0;i<(L-cur_len);i++){
sb.append(' ');
}
} else {
int whitespace_cnt = (L-cur_len)/(count-1);
int left_whitespace_cnt = (L-cur_len)%(count-1);
int fromidx = 0;
for(int i=0; i<left_whitespace_cnt; i++){
int whitespace_idx = sb.indexOf(" ", fromidx);
for(int j=0; j<=whitespace_cnt;j++){
sb.insert(whitespace_idx, ' ');
}
fromidx = whitespace_idx + whitespace_cnt + 2;
}
for(int i=0; i<(count - left_whitespace_cnt - 1); i++){
int whitespace_idx = sb.indexOf(" ", fromidx);
for(int j=0; j<whitespace_cnt;j++){
sb.insert(whitespace_idx, ' ');
}
fromidx = whitespace_idx + whitespace_cnt + 1;
}
}
result.add(sb.toString());
idx += count;
}
return result;
}
}
<file_sep>/lc/src/lc/PalindromePartitioning2.java
package lc;
public class PalindromePartitioning2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(minCut("bb"));
}
public static int minCut(String s) {
int len = s.length();
boolean[][] result = new boolean[len][len];
for(int i=len-1;i>=0;i--){
for(int j=0;j<len;j++){
if(i==j){
result[i][j] = true;
} else if (i<j) {
if(j==(i+1)){
result[i][j] = (s.charAt(i)==s.charAt(j));
}else{
result[i][j] = (result[i+1][j-1]) && (s.charAt(i)==s.charAt(j));
}
}
}
}
int[] cut = new int[len];
for(int i=0;i<len;i++){
cut[i] = i+1;
for(int j=0;j<=i;j++){
if(result[j][i]){
if((j-1)<0){
cut[i]= Math.min(cut[i], 1);
} else {
cut[i]= Math.min(cut[i], cut[j-1]+1);
}
}
}
}
return (cut[len-1]-1);
}
}
<file_sep>/lc/src/lc/SearchInsertPosition.java
package lc;
public class SearchInsertPosition {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public int searchInsert(int[] A, int target) {
int start =0;
int end = A.length-1;
while(start+1<end){
int mid = start+(end-start)/2;
if(A[mid]> target){
end = mid -1;
} else if(A[mid]< target){
start = mid;
} else {
return mid;
}
}
if(A[start]>=target){
return start;
} else if(A[end]>=target){
return end;
} else{
return end+1;
}
}
}
<file_sep>/lc/src/lc/Searcha2DMatrix2.java
package lc;
import java.util.ArrayList;
public class Searcha2DMatrix2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public int searchMatrix(ArrayList<ArrayList<Integer>> matrix, int target) {
int row = matrix.size();
if(row <1){
return 0;
}
int column = matrix.get(0).size();
if(column < 1){
return 0;
}
int count = 0;
int curow = row-1;
int cucol = 0;
while(curow>=0 && cucol<column){
int current =matrix.get(curow).get(cucol);
if(current > target){
curow--;
} else if(current < target){
cucol++;
} else {
count++;
curow--;
cucol++;
}
}
return count;
}
}
<file_sep>/lc/src/lc/BSTIterator.java
package lc;
import java.util.LinkedList;
public class BSTIterator {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode a = new TreeNode(1);
BSTIterator q = new BSTIterator(a);
System.out.println(q.next());
}
private LinkedList<TreeNode> path;
private int size = 0;
public BSTIterator(TreeNode root) {
path = new LinkedList<TreeNode>();
TreeNode cur = root;
while(cur != null){
path.addFirst(cur);
cur = cur.left;
size ++;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
if(size != 0){
return true;
}
return false;
}
/** @return the next smallest number */
public int next() {
if(size != 0){
TreeNode cur = path.removeFirst();
size --;
if(cur.right != null){
TreeNode tmp = cur.right;
while(tmp != null){
path.addFirst(tmp);
tmp = tmp.left;
size ++;
}
}
return cur.val;
} else {
return -1;
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
}
<file_sep>/lc/src/lc/ImplementIteratorofBinarySearchTree.java
package lc;
import java.util.LinkedList;
public class ImplementIteratorofBinarySearchTree {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
private TreeNode cur;
boolean goLeft = true;
LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
//@param root: The root of binary tree.
public ImplementIteratorofBinarySearchTree(TreeNode root) {
cur = root;
if(cur!=null){
stack.push(cur);
}
}
//@return: True if there has next node, or false
public boolean hasNext() {
return !stack.isEmpty();
}
//@return: return next node
public TreeNode next() {
if(stack.isEmpty()){
return null;
}
cur = stack.peek();
if(goLeft){
while(cur.left!=null){
cur = cur.left;
stack.push(cur);
}
}
cur = stack.pop();
if(cur.right!=null){
stack.push(cur.right);
goLeft=true;
} else {
goLeft=false;
}
return cur;
}
}
<file_sep>/lc/src/lc/WordBreak2.java
package lc;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class WordBreak2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public List<String> wordBreak(String s, Set<String> dict) {
List<String> result = new ArrayList<String>();
if(!isWordBreakable(s, dict)){
return result;
}
ArrayList<String> item = new ArrayList<String>();
helper(s, dict, result, item, 0);
return result;
}
private void helper(String s, Set<String> dict, List<String> result, ArrayList<String> item, int idx){
if(idx == s.length()){
StringBuilder str = new StringBuilder();
int size = item.size();
for(int i=0;i<size;i++){
str.append(item.get(i)+" ");
}
if(str.charAt(str.length()-1)==' '){
str.deleteCharAt(str.length()-1);
}
result.add(str.toString());
return;
}
for(int i=idx;i<s.length();i++){
if(dict.contains(s.substring(idx, i+1))){
item.add(s.substring(idx, i+1));
helper(s, dict, result, item, i+1);
item.remove(item.size()-1);
}
}
}
private boolean isWordBreakable(String s, Set<String> dict) {
if (s == null || s.length() == 0)
return true;
boolean[] result = new boolean[s.length() + 1];
result[0] = true;
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j <= i; j++) {
String sub = s.substring(j, i + 1);
if (result[j] && dict.contains(sub)) {
result[i + 1] = true;
break;
}
}
}
return result[s.length()];
}
}
|
d3199f4bac7d9d5336e5655312ff69418ffba045
|
[
"Java"
] | 64 |
Java
|
christina57/lc
|
67b5ebac545534107a1a9c1d289e80df47ca583b
|
c40e2c40ea849213dea24baf88971fae82a6a926
|
refs/heads/master
|
<file_sep>// Copyright 2018 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
//final wordPair = WordPair.random();
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Pestañita: Randoms Names',
home: RandomWords(),
);
}
}
/*########################################*/
class RandomWords extends StatefulWidget {
@override
_RandomWordsState createState() {
return _RandomWordsState();
}
}
class _RandomWordsState extends State<RandomWords> {
final _suggestions = <WordPair>[]; //guarda las combinaciones de palabras
final _biggerFont = TextStyle(fontSize: 18.0);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Startup Name Generator'),
),
body: _buildSuggestions(),
);
}
Widget _buildSuggestions() {
//Para trabajar con listas que contienen una gran cantidad de elementos, uso de ListView.builder
//El constructor ListView.builder creará los elementos a medida que se desplazan por la pantalla.
return ListView.builder(
padding: EdgeInsets.all(16.0),
itemBuilder: (context, i) {
if (i.isOdd) return Divider(); //Si es impar, retorna Divider
final index = i ~/ 2;
if (index >= _suggestions.length) {
_suggestions.addAll(generateWordPairs().take(2));
}
return _buildRow(_suggestions[index]);
}
);
}
Widget _buildRow(WordPair pair) {
return ListTile(
title: Text(
pair.asPascalCase, //String data
style: _biggerFont, //Estilo
),
);
}
}
/*########################################*/
|
6a87d1c0a532555c28cd5e10387d6894a814250e
|
[
"Dart"
] | 1 |
Dart
|
adrianmircor/EXAMPLE-FLUTTER-FIRSTAPP
|
9a26f6fd1fe7014eda8f8b36dc1e6b342c7d6cff
|
cd08fc082b756f2a2f558bedc82df06f6b77f602
|
refs/heads/master
|
<repo_name>davydovk/DevOps<file_sep>/Jenkinsfile
pipeline {
agent any
environment {
PROJECT_NAME = "Panda"
OWNER_NAME = "<NAME>"
}
stages {
stage('1-Build') {
steps {
echo 'Start of Stage Build'
echo 'Building.......'
echo 'End of Stage Build'
}
}
stage("2-Test") {
steps {
echo 'Start of Stage Test'
echo 'Testing.......'
echo "Hello ${OWNER_NAME}"
echo "Project name is ${PROJECT_NAME}"
echo 'End of Stage Test'
}
}
stage("3-Deploy") {
steps {
echo 'Start of Stage Deploy'
echo 'Deploying.......'
echo 'End of Stage Deploy'
}
}
}
post {
always {
echo 'One way or another, I have finished'
deleteDir() /* clean up our workspace */
}
success {
echo 'I succeeded!'
}
unstable {
echo 'I am unstable :/'
}
failure {
echo 'I failed :('
}
changed {
echo 'Things were different before...'
}
}
}
|
e3e18dd5f74dda739ddd3c7ee8c5921519c1c6d2
|
[
"Groovy"
] | 1 |
Groovy
|
davydovk/DevOps
|
5410de5c9c766c14ae5a3b35520e99a776b434bc
|
bc4c0a2bb36030d13ef6de9759966f181a01010c
|
refs/heads/master
|
<repo_name>sebastian301082/first-silex<file_sep>/script/vagrant-bootstrap.sh
#!/bin/bash -e
sudo apt-get update -y
#sudo apt-get upgrade -y
sudo apt-get install -y vim curl apache2 php5 php5-cli php-pear php5-curl phpunit php5-intl php5-memcache php5-dev php5-gd php5-mcrypt php5-dev git-core git #mongodb-10gen make
if [ ! -f /etc/apache2/sites-available/first-silex ]
then
sudo ln -s /vagrant/script/template/first-silex.conf /etc/apache2/sites-available/first-silex
fi
rm -f /vagrant/logs/*.log
sudo a2enmod rewrite
sudo a2dissite 000-default
sudo a2ensite first-silex
sudo service apache2 reload
cd /vagrant
curl -s http://getcomposer.org/installer | php5
sudo mv composer.phar /usr/local/bin/composer
composer install
echo "You can access your application on "
ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | grep -v '10.0.2' | grep -v '10.11.12.1' | cut -d: -f2 | awk '{ print "http://"$1"/"}'<file_sep>/README.md
# first-silex
<file_sep>/Vagrantfile
Vagrant.configure("2") do |config|
config.vm.box = "hashicorp/precise64"
# Enable boostrap
config.vm.provision :shell, :path => "script/vagrant-bootstrap.sh"
# using a specific IP.
config.vm.network :private_network, ip: "10.11.12.2"
# your network.
config.vm.network :public_network
# argument is a set of non-required options.
config.vm.synced_folder "./", "/vagrant", :owner => "www-data", :group => "www-data"
end
|
f6cdf30d1521034034c0a6c30275228cc831944d
|
[
"Markdown",
"Shell",
"Ruby"
] | 3 |
Markdown
|
sebastian301082/first-silex
|
c545cae8132fa44f6a26879872851bd242772e01
|
b90c18213cdc368a89252d7551c0a287d4ae5307
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CDLRouteHelper.Data.Model
{
public enum TruckType
{
Straight, Single, Double, Triple
}
public class Weight
{
public int WeightID { get; set; }
public TruckType TruckType { get; set; }
public float? maxWeight { get; set; }
public int BridgeId { get; set; }
public virtual Bridge Bridge { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CDLRouteHelper.Models
{
public class CreateViewModel
{
[Required]
[Range(-90, 90)]
public double Latitude { get; set; }
[Required]
[Range(-180, 180)]
public double Longitude { get; set; }
[Required]
[Display(Name = "Bridge Location")]
[StringLength(140)]
public string Address1 { get; set; }
[Required]
public string City { get; set; }
[Required]
public string State { get; set; }
[Required]
[Display(Name = "Postal Code")]
public string PostalCode { get; set; }
public float? Height { get; set; }
[Display(Name = "Max Weight Straight Truck")]
public float? WeightStraight { get; set; }
[Display(Name = "Max Weight Single Trailer")]
public float? WeightSingle { get; set; }
[Display(Name = "Max Weight Double Trailer")]
public float? WeightDouble { get; set; }
//for Update
public int BridgeId { get; set; }
//for Display by coords -- center map on search coords
public double LatSearched { get; set; }
public double LonSearched { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CDLRouteHelper.Data.Model;
namespace CDLRouteHelper.Data
{
public class CDLContext: DbContext
{
public DbSet<User> User { get; set; }
public DbSet<UserAddress> UserAddress { get; set; }
public DbSet<State> State { get; set; }
public DbSet<Bridge> Bridge { get; set; }
public DbSet<Weight> Weight { get; set; }
public DbSet<UserRole> UserRole { get; set; }
public DbSet<OAuthMembership> OAuthMembership { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<Membership> Memberships { get; set; }
}
}
<file_sep>namespace CDLRouteHelper.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class User_toUserAddressLookup : DbMigration
{
public override void Up()
{
DropForeignKey("dbo.Users", "UserAddressId", "dbo.UserAddresses");
DropIndex("dbo.Users", new[] { "UserAddressId" });
AddColumn("dbo.UserAddresses", "UserId", c => c.Int(nullable: false));
AddForeignKey("dbo.UserAddresses", "UserId", "dbo.Users", "UserId", cascadeDelete: true);
CreateIndex("dbo.UserAddresses", "UserId");
DropColumn("dbo.Users", "UserAddressId");
}
public override void Down()
{
AddColumn("dbo.Users", "UserAddressId", c => c.Int(nullable: false));
DropIndex("dbo.UserAddresses", new[] { "UserId" });
DropForeignKey("dbo.UserAddresses", "UserId", "dbo.Users");
DropColumn("dbo.UserAddresses", "UserId");
CreateIndex("dbo.Users", "UserAddressId");
AddForeignKey("dbo.Users", "UserAddressId", "dbo.UserAddresses", "UserAddressId", cascadeDelete: true);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace CDLRouteHelper.Models
{
public class RetrieveViewModel
{
[Required]
[Range(-90, 90)]
public double Latitude { get; set; }
[Required]
[Range(-180, 180)]
public double Longitude { get; set; }
public float Distance { get; set; }
}
public class UpdateViewModel
{
}
}<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title OpenRoad </title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
@Styles.Render("~/Content/css")
@Styles.Render("~/Content/bootstrap/base")
@Styles.Render("~/Content/bootstrap/theme")
@Scripts.Render("~/bundles/modernizr")
@* @Scripts.Render("~/Content/themes/base")*@
<link href="~/Content/themes/base/jquery.ui.slider.css" rel="stylesheet" />
@* <link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" />*@
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery.ui.tabs.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery.ui.theme.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery.ui.core.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" />
<link href="~/Content/zocial.css" rel="stylesheet" />
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=<KEY>&sensor=false">
</script>
</head>
<body>
<header>
@* <div class="content-wrapper">*@
<nav class="navbar navbar-default" role="navigation" style="margin: 40px;">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">
<img style="width: 120px; height: 100px; padding: 15px" src='~/Images/OpenRoad.png' />
</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-ex1-collapse" style="padding-top: 40px">
<ul class="nav navbar-nav">
<li class="active">@Html.ActionLink("Home", "Index", "Home")</li>
@if (HttpContext.Current.User.Identity.IsAuthenticated)
{
<li class="dropdown active">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Search <b class="caret"></b></a>
<ul class="dropdown-menu">
<li>@Html.ActionLink("By City Using Truck Info", "Index", "Restricted")</li>
<li>@Html.ActionLink("Nearby", "Nearby", "Restricted")</li>
<li>@Html.ActionLink("By Latitude/Longitude", "SearchByCoords", "Restricted")</li>
</ul>
</li>
}
</ul>
<ul class="nav navbar-nav navbar-left">
@if (HttpContext.Current.User.Identity.IsAuthenticated)
{
<li class="dropdown active">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Manage <b class="caret"></b></a>
<ul class="dropdown-menu">
<li>@Html.ActionLink("Add Bridge", "Create", "Restricted")</li>
@if (HttpContext.Current.User.IsInRole("Staff") || HttpContext.Current.User.IsInRole("Administrator"))
{
<li>@Html.ActionLink("Update By City -- Staff", "RetrieveByCity", "Restricted")</li>
<li>@Html.ActionLink("Update By Lat/Lng -- Staff", "Retrieve", "Restricted")</li>
}
@if (HttpContext.Current.User.IsInRole("Administrator"))
{
<li>@Html.ActionLink("Delete By Lat/Lng -- Administrator", "Delete", "Restricted")</li>
}
</ul>
</li>
}
<li class="active">@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
<div style="padding: 20px">
<section id="login">
@Html.Partial("_LoginPartial")
</section>
</div>
</div>
<!-- /.navbar-collapse -->
</nav>
@* </div>*@
</header>
<div id="body" style="background-color: white">
@RenderSection("featured", required: false)
@* <section class="content-wrapper main-content clear-fix">*@
<section class="content-wrapper clear-fix">
@RenderBody()
</section>
</div>
<footer style="background-color: white; margin: 40px;">
<p>© @DateTime.Now.Year - OpenRoad</p>
</footer>
@* @Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/jquery")*@
<script src="~/Scripts/jquery-2.0.3.js"></script>
@* <script src="~/Scripts/jquery-ui-1.8.24.js"></script>*@
<script src="~/Scripts/jquery-ui-1.10.3.js"></script>
<script src="~/Scripts/bootstrap.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
@RenderSection("scripts", required: false)
</body>
</html>
<file_sep>namespace CDLRouteHelper.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Users",
c => new
{
UserId = c.Int(nullable: false, identity: true),
FirstName = c.String(),
LastName = c.String(),
Email = c.String(),
Username = c.String(),
LocationId = c.Int(),
})
.PrimaryKey(t => t.UserId)
.ForeignKey("dbo.Locations", t => t.LocationId)
.Index(t => t.LocationId);
CreateTable(
"dbo.Locations",
c => new
{
LocationId = c.Int(nullable: false, identity: true),
latitude = c.Single(),
longitude = c.Single(),
Address1 = c.String(),
Address2 = c.String(),
City = c.String(),
PostalCode = c.String(),
StateId = c.Int(),
UserId = c.Int(nullable: false),
BridgeId = c.Int(nullable: false),
})
.PrimaryKey(t => t.LocationId)
.ForeignKey("dbo.States", t => t.StateId)
.Index(t => t.StateId);
CreateTable(
"dbo.States",
c => new
{
StateId = c.Int(nullable: false, identity: true),
Name = c.String(),
PostalCode = c.String(),
CountryId = c.Int(nullable: false),
})
.PrimaryKey(t => t.StateId);
CreateTable(
"dbo.Bridges",
c => new
{
BridgeId = c.Int(nullable: false, identity: true),
Height = c.Single(nullable: false),
Weight = c.Single(nullable: false),
LastUpdated = c.DateTime(nullable: false),
NumTimesReported = c.Int(nullable: false),
})
.PrimaryKey(t => t.BridgeId)
.ForeignKey("dbo.Locations", t => t.BridgeId)
.Index(t => t.BridgeId);
}
public override void Down()
{
DropIndex("dbo.Bridges", new[] { "BridgeId" });
DropIndex("dbo.Locations", new[] { "StateId" });
DropIndex("dbo.Users", new[] { "LocationId" });
DropForeignKey("dbo.Bridges", "BridgeId", "dbo.Locations");
DropForeignKey("dbo.Locations", "StateId", "dbo.States");
DropForeignKey("dbo.Users", "LocationId", "dbo.Locations");
DropTable("dbo.Bridges");
DropTable("dbo.States");
DropTable("dbo.Locations");
DropTable("dbo.Users");
}
}
}
<file_sep>@model CDLRouteHelper.Models.CreateViewModel
@{
ViewBag.Title = "Delete";
}
@using (Html.BeginForm("DeleteByCoords", "Restricted", FormMethod.Post, Model))
{
@Html.HiddenFor(c => c.BridgeId)
@Html.ValidationSummary(true, "Please correct the following:")
<div class="col-md-6 row" style="background-color: #f9f9f9; border: solid; border-color: #f3f3f3">
<div class="page-header">
<h1>Delete Record</h1>
</div>
<div style="margin-top: 20px" class="well">
<div>
@Html.LabelFor(c => c.Latitude)
<h5>@Html.DisplayFor(c => c.Latitude) </h5>
</div>
</div>
<div class="well">
<div>
@Html.LabelFor(c => c.Longitude)
<h5>@Html.DisplayFor(c => c.Longitude) </h5>
</div>
</div>
<div class="well">
<div>
@Html.LabelFor(c => c.Address1)
<h5>@Html.DisplayFor(c => c.Address1) </h5>
</div>
</div>
<div class="well">
<div>
@Html.LabelFor(m => m.City)
<h5>@Html.DisplayFor(m => m.City) </h5>
</div>
</div>
<div class="well">
<div>
@Html.LabelFor(m => m.State)
<h5>@Html.DisplayFor(m => m.State) </h5>
</div>
</div>
<div class="well">
<div>
@Html.LabelFor(c => c.PostalCode)
<h5>@Html.DisplayFor(c => c.PostalCode) </h5>
</div>
</div>
<div class="well">
@Html.LabelFor(c => c.Height)
<h5>@Html.DisplayFor(c => c.Height) </h5>
</div>
<div class="well">
@Html.LabelFor(c => c.WeightStraight)
<h5>@Html.DisplayFor(c => c.WeightStraight)</h5>
</div>
<div class="well">
@Html.LabelFor(c => c.WeightSingle)
<h5>@Html.DisplayFor(c => c.WeightSingle)</h5>
</div>
<div class="well">
@Html.LabelFor(c => c.WeightDouble)
<h5>@Html.DisplayFor(c => c.WeightDouble)</h5>
</div>
<div style="margin: 20px; text-align: center">
<button class="btn btn-primary btn-lg" type="submit">Delete </button>
</div>
</div>
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CDLRouteHelper.Controllers
{
public class HomeController : Controller
{
public ActionResult Test()
{
Adapters.Service.ServiceBridge _adapter = new Adapters.Service.ServiceBridge();
var l1 = _adapter.GetListByDistanceFrom(29.5324287f, -95.26932f, 2);
var l2 = _adapter.GetListByDistanceFrom(29.5324287f, -95.26932f, 10);
var l3 = _adapter.GetListByDistanceFrom(29.5324287f, -95.26932f, 25);
var l4 = _adapter.GetListByDistanceFrom(29.5324287f, -95.26932f, 1100);
//var l = _adapter.GetListBridgeServiceModel();
return null;
}
public ActionResult Index()
{
//ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About()
{
//ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
//ViewBag.Message = "Your contact page.";
return View();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CDLRouteHelper.Data.Model
{
public class UserAddress
{
public int UserAddressId { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public int StateId { get; set; }
public int UserId { get; set; }
public virtual State State { get; set; }
public virtual User User { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CDLRouteHelper.Data.Model
{
[Table("webpages_UsersInRoles")]
public class UserRole
{
[Key, Column(Order = 0)]
public int UserId { get; set; }
[Key, Column(Order = 1)]
public int RoleId { get; set; }
public virtual User User { get; set; }
public virtual Role Role { get; set; }
}
[Table("webpages_OAuthMembership")]
public class OAuthMembership
{
[Key, StringLength(30), Column(Order = 0)]
public string Provider { get; set; }
[Key, StringLength(100), Column(Order = 1)]
public string ProviderUserId { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
}
[Table("webpages_Roles")]
public class Role
{
public const string ADMINISTRATOR = "Administrator";
public const string STAFF = "Staff";
public const string USER = "User";
public int RoleId { get; set; }
[Column("RoleName")]
public string Name { get; set; }
public virtual ICollection<UserRole> UserRoles { get; set; }
}
[Table("webpages_Membership")]
public class Membership
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public int UserId { get; set; }
public DateTime? CreateDate { get; set; }
public string ConfirmationToken { get; set; }
public bool IsConfirmed { get; set; }
public DateTime? LastPasswordFailureDate { get; set; }
public int PasswordFailuresSinceLastSuccess { get; set; }
public string Password { get; set; }
public DateTime? PasswordChangedDate { get; set; }
[Required(AllowEmptyStrings = true), MaxLength(128)]
public string PasswordSalt { get; set; }
[MaxLength(128)]
public string PasswordVerificationToken { get; set; }
public DateTime? PasswordVerificationTokenExpirationDate { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CDLRouteHelper.Models.Service
{
public class BridgeServiceModel
{
public Guid Guid { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public float heightRestriction { get; set; }
public float weightStraightTruck { get; set; }
public float weightSingleTrailer { get; set; }
public float weightDoubleTrailer { get; set; }
public string Location { get; set; }
public string City { get; set; }
}
}<file_sep>@model CDLRouteHelper.Models.CreateViewModel
@{
ViewBag.Title = "Update";
List<string> states = new List<string>() { "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL",
"IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE",
"NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC",
"SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"};
string selectedState = "NY";
}
@using (Html.BeginForm("Update", "Restricted", FormMethod.Post, Model))
{
@Html.ValidationSummary(true, "Please correct the following:")
<div class="col-md-6 row" style="background-color: #f9f9f9; border: solid; border-color: #f3f3f3">
<div class="page-header">
<h1>Update Bridge Record</h1>
</div>
<div style="margin-top: 20px" class="well">
<div>
@Html.ValidationMessageFor(c => c.Latitude)
</div>
<div>
@Html.LabelFor(c => c.Latitude)
@Html.TextBoxFor(c => c.Latitude)
</div>
</div>
<div class="well">
<div>
@Html.ValidationMessageFor(c => c.Longitude)
</div>
<div>
@Html.LabelFor(c => c.Longitude)
@Html.TextBoxFor(c => c.Longitude)
</div>
</div>
<div class="well">
<div>
@Html.ValidationMessageFor(c => c.Address1)
</div>
<div>
@Html.LabelFor(c => c.Address1)
@Html.TextBoxFor(c => c.Address1)
</div>
</div>
<div class="well">
<div>
@Html.ValidationMessageFor(m => m.City)
</div>
<div>
@Html.LabelFor(m => m.City)
@Html.TextBoxFor(m => m.City)
</div>
</div>
<div class="well">
<div>
@Html.LabelFor(m => m.State)
@Html.DropDownListFor(m => m.State, new SelectList(states, null, null, selectedState))
</div>
</div>
<div class="well">
<div>@Html.ValidationMessageFor(c => c.PostalCode) </div>
<div>
@Html.LabelFor(c => c.PostalCode)
@Html.TextBoxFor(c => c.PostalCode)
</div>
</div>
<div class="well">
@Html.LabelFor(c => c.Height)
@Html.TextBoxFor(c => c.Height)
</div>
<div class="well">
@Html.LabelFor(c => c.WeightStraight)
@Html.TextBoxFor(c => c.WeightStraight)
</div>
<div class="well">
@Html.LabelFor(c => c.WeightSingle)
@Html.TextBoxFor(c => c.WeightSingle)
</div>
<div class="well">
@Html.LabelFor(c => c.WeightDouble)
@Html.TextBoxFor(c => c.WeightDouble)
</div>
@Html.HiddenFor(c => c.BridgeId)
<div style="margin: 20px; text-align: center">
<button class="btn btn-primary btn-lg" type="submit">Update </button>
</div>
</div>
}
<file_sep>namespace CDLRouteHelper.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class addWeightTableAndTruckTypeEnum : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Weights",
c => new
{
WeightID = c.Int(nullable: false, identity: true),
BridgeId = c.Int(nullable: false),
TruckType = c.String(),
})
.PrimaryKey(t => t.WeightID)
.ForeignKey("dbo.Bridges", t => t.BridgeId, cascadeDelete: true)
.Index(t => t.BridgeId);
}
public override void Down()
{
DropIndex("dbo.Weights", new[] { "BridgeId" });
DropForeignKey("dbo.Weights", "BridgeId", "dbo.Bridges");
DropTable("dbo.Weights");
}
}
}
<file_sep>@{
ViewBag.Title = "Contact";
}
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
<h2>@ViewBag.Message</h2>
</hgroup>
<section class="contact">
<div>
<h3>Email</h3>
Support:
<a href="mailto:<EMAIL>"><EMAIL></a>
</div>
</section>
<section class="contact">
<div>
<h3>Address</h3>
Lockport, NY
</div>
</section>
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Device.Location; //geo
using CDLRouteHelper.Data;
using CDLRouteHelper.Data.Model;
namespace CDLRouteHelper.Adapters.Service
{
public class ServiceBridge : Adapters.Service.IServiceBridge
{
public List<Models.Service.BridgeServiceModel> GetListBridgeServiceModel()
{
List<Models.Service.BridgeServiceModel> lbsm = new List<Models.Service.BridgeServiceModel>();
CDLContext db = new CDLContext();
List<Bridge> bridges = new List<Bridge>();
bridges = db.Bridge.ToList();
foreach(var b in bridges)
{
var bsm = new Models.Service.BridgeServiceModel();
bsm.Guid = b.Guid;
bsm.Latitude = b.Latitude;
bsm.Longitude = b.Longitude;
bsm.Location = b.Address1;
bsm.City = b.City;
if (b.Height == null)
b.Height = 0;
bsm.heightRestriction = (float) b.Height;
if (b.Weights.Count >= 1)
bsm.weightStraightTruck = (float) b.Weights.ElementAt(0).maxWeight;
if (b.Weights.Count >= 2)
bsm.weightSingleTrailer = (float) b.Weights.ElementAt(1).maxWeight;
if (b.Weights.Count >= 3)
bsm.weightDoubleTrailer = (float) b.Weights.ElementAt(2).maxWeight;
lbsm.Add(bsm);
}
//lbsm = db.Bridge.ToList().Select(b => new { b.Guid, b.Height, b.Latitude, b.Longitude }).ToList();
return lbsm;
}
const double _eQuatorialEarthRadius = 6378.1370D;
const double _d2r = (Math.PI / 180D);
//public static double HaversineInM(this double d, double lat1, double long1, double lat2, double long2)
//{
// return (1000D * HaversineInKM(lat1, long1, lat2, long2));
//}
public bool GeoCoordsDistance(double latitude, double longitude, double lat2, double long2, float distance)
{
double dlong = ((long2 - longitude) * _d2r);
double dlat = ((lat2 - latitude) * _d2r);
double a = Math.Pow(Math.Sin(dlat / 2D), 2D) + Math.Cos(latitude * _d2r) * Math.Cos(lat2 * _d2r) * Math.Pow(Math.Sin(dlong / 2D), 2D);
double c = 2D * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1D - a));
double d = _eQuatorialEarthRadius * c;
if (1000D * _eQuatorialEarthRadius * 2D * Math.Atan2(Math.Sqrt(Math.Pow(Math.Sin(((lat2 - latitude) * _d2r) / 2D), 2D) + Math.Cos(latitude * _d2r) * Math.Cos(lat2 * _d2r) * Math.Pow(Math.Sin(((long2 - longitude) * _d2r) / 2D), 2D)), Math.Sqrt(1D - Math.Pow(Math.Sin(((lat2 - latitude) * _d2r) / 2D), 2D) + Math.Cos(latitude * _d2r) * Math.Cos(lat2 * _d2r) * Math.Pow(Math.Sin(((long2 - longitude) * _d2r) / 2D), 2D))) <= distance)
{
return true;
}
return false;
}
public List<Models.Service.BridgeServiceModel> GetListByDistanceFrom(double latitude, double longitude, float distance)
{
List<Models.Service.BridgeServiceModel> lbsm = new List<Models.Service.BridgeServiceModel>();
CDLContext db = new CDLContext();
GeoCoordinate gc = new GeoCoordinate(latitude, longitude);
List<Bridge> bridges = new List<Bridge>();
//bridges = db.Bridge.Where(b =>
// (1000D * _eQuatorialEarthRadius * 2D * Math.Atan2(Math.Sqrt(Math.Pow(Math.Sin((double)((b.Latitude - latitude) * _d2r) / 2D), 2D) + Math.Cos(latitude * _d2r) * Math.Cos((double)b.Latitude * _d2r) * Math.Pow(Math.Sin((double)((b.Longitude - longitude) * _d2r) / 2D), 2D)), Math.Sqrt(1D - Math.Pow(Math.Sin((double)((b.Longitude - latitude) * _d2r) / 2D), 2D) + Math.Cos(latitude * _d2r) * Math.Cos((double)b.Latitude * _d2r) * Math.Pow(Math.Sin((((double)b.Longitude - longitude) * _d2r) / 2D), 2D))) <= distance)
//== true ).ToList();
//(1000D * _eQuatorialEarthRadius * 2D * Math.Atan2(Math.Sqrt(Math.Pow(Math.Sin((double)((b.Latitude - latitude) * _d2r) / 2D), 2D) + Math.Cos(latitude * _d2r) * Math.Cos((double)b.Latitude * _d2r) * Math.Pow(Math.Sin((double)((b.Longitude - longitude) * _d2r) / 2D), 2D)), Math.Sqrt(1D - Math.Pow(Math.Sin((double)((b.Longitude - latitude) * _d2r) / 2D), 2D) + Math.Cos(latitude * _d2r) * Math.Cos((double)b.Latitude * _d2r) * Math.Pow(Math.Sin((((double)b.Longitude - longitude) * _d2r) / 2D), 2D))) <= distance)
//bridges = (from b in db.Bridge
// where (1000D * (b.Latitude - Math.Abs(latitude)) <= distance)
// select b).ToList();
bridges = db.Bridge.ToList();
foreach (var b in bridges)
{
var bsm = new Models.Service.BridgeServiceModel();
bsm.Guid = b.Guid;
bsm.Latitude = b.Latitude;
bsm.Longitude = b.Longitude;
bsm.Location = b.Address1;
bsm.City = b.City;
var bridgeGC = new GeoCoordinate();
bridgeGC.Latitude = bsm.Latitude;
bridgeGC.Longitude = bsm.Longitude;
if (b.Height == null)
b.Height = 0;
bsm.heightRestriction = (float) b.Height;
if (b.Weights.Count >= 1)
if (b.Weights.ElementAt(0).maxWeight != null)
{
bsm.weightStraightTruck = (float)b.Weights.ElementAt(0).maxWeight; ;
}
if (b.Weights.Count >= 2)
if (b.Weights.ElementAt(1).maxWeight != null)
{
bsm.weightSingleTrailer = (float)b.Weights.ElementAt(1).maxWeight;
}
if (b.Weights.Count >= 3)
if (b.Weights.ElementAt(2).maxWeight != null)
{
bsm.weightDoubleTrailer = (float)b.Weights.ElementAt(2).maxWeight;
}
if(bridgeGC.GetDistanceTo(gc) <= distance * 1609.344) // within distance passsed in keep it
{
lbsm.Add(bsm);
}
}
return lbsm;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Device.Location;
namespace CDLRouteHelper.Helper
{
public class GeoHelper
{
private const double CONVERT_TO_MILES = 1609.344;
public static GeoCoordinate BuildGeoCoordinates(double latitude, double longitude)
{
return new GeoCoordinate(latitude, longitude);
}
public static GeoCoordinate BuildGeoCoordinates(string latitude, string longitude)
{
string sLatd = GeoHelper.RemoveExtrasFromGeoDimensions(latitude);
string sLngtd = GeoHelper.RemoveExtrasFromGeoDimensions(longitude);
double latd = double.Parse(sLatd);
double lngtd = double.Parse(sLngtd);
return new GeoCoordinate(latd, lngtd);
}
public static double LatOrLonToDouble(string latOrLon)
{
string s = GeoHelper.RemoveExtrasFromGeoDimensions(latOrLon);
double result = double.Parse(s);
return result;
}
public static string RemoveExtrasFromGeoDimensions(string dimension)
{
return new string(dimension.Where(c => char.IsDigit(c) || c == '.' || c == '-').ToArray());
}
public static double GetDistanceByGeoCoordinates(GeoCoordinate locationA, GeoCoordinate locationB)
{
return locationA.GetDistanceTo(locationB) / CONVERT_TO_MILES;
}
internal static double LatLonToLatDouble(string latLng)
{
var s1 = "";
//keep everything between ( and first Blank as latitude
for (int i = 0; i < latLng.Length; i++)
{
if (latLng[i] == '(' || latLng[i] == ',')
{ } //do nothing
else if (latLng[i] == ' ')
break;
else
s1 += latLng[i];
}
// double result = double.Parse(s1);
double result = 29.4513511657715;
return result;
}
internal static double LatLonToLonDouble(string latLng)
{
var s1 = "";
//keep from first blank+1 to ')' as lng
int index = 0;
for (int i = 0; i < latLng.Length; i++)
{
if (latLng[i] == ' ')
break;
index++;
}
// start from past blank
for (int i = index + 1; i < latLng.Length; i++)
{
if (latLng[i] == ')')
{ } //do nothing
else
s1 += latLng[i];
}
// double result = double.Parse(s1);
double result = -95.2864837646484;
return result;
}
}
}<file_sep>namespace CDLRouteHelper.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Change_Lat_LongFromFloat_toDouble : DbMigration
{
public override void Up()
{
AlterColumn("dbo.Bridges", "Latitude", c => c.Double(nullable: false));
AlterColumn("dbo.Bridges", "Longitude", c => c.Double(nullable: false));
}
public override void Down()
{
AlterColumn("dbo.Bridges", "Longitude", c => c.Single());
AlterColumn("dbo.Bridges", "Latitude", c => c.Single());
}
}
}
<file_sep>namespace CDLRouteHelper.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class removeLocation_AddToBridge : DbMigration
{
public override void Up()
{
DropForeignKey("dbo.Users", "LocationId", "dbo.Locations");
DropForeignKey("dbo.Locations", "StateId", "dbo.States");
DropForeignKey("dbo.Bridges", "BridgeId", "dbo.Locations");
DropIndex("dbo.Users", new[] { "LocationId" });
DropIndex("dbo.Locations", new[] { "StateId" });
DropIndex("dbo.Bridges", new[] { "BridgeId" });
CreateTable(
"dbo.UserAddresses",
c => new
{
UserAddressId = c.Int(nullable: false, identity: true),
Address1 = c.String(),
Address2 = c.String(),
City = c.String(),
PostalCode = c.String(),
StateId = c.Int(nullable: false),
})
.PrimaryKey(t => t.UserAddressId)
.ForeignKey("dbo.States", t => t.StateId, cascadeDelete: true)
.Index(t => t.StateId);
AddColumn("dbo.Users", "UserAddressId", c => c.Int(nullable: false));
AddColumn("dbo.Bridges", "Latitude", c => c.Single());
AddColumn("dbo.Bridges", "Longitude", c => c.Single());
AddColumn("dbo.Bridges", "Address1", c => c.String());
AddColumn("dbo.Bridges", "Address2", c => c.String());
AddColumn("dbo.Bridges", "City", c => c.String());
AddColumn("dbo.Bridges", "PostalCode", c => c.String());
AddColumn("dbo.Bridges", "StateId", c => c.Int(nullable: false));
AlterColumn("dbo.Bridges", "BridgeId", c => c.Int(nullable: false, identity: true));
AlterColumn("dbo.Bridges", "Height", c => c.Single());
AddForeignKey("dbo.Users", "UserAddressId", "dbo.UserAddresses", "UserAddressId", cascadeDelete: true);
AddForeignKey("dbo.Bridges", "StateId", "dbo.States", "StateId", cascadeDelete: true);
CreateIndex("dbo.Users", "UserAddressId");
CreateIndex("dbo.Bridges", "StateId");
DropColumn("dbo.Users", "LocationId");
DropTable("dbo.Locations");
}
public override void Down()
{
CreateTable(
"dbo.Locations",
c => new
{
LocationId = c.Int(nullable: false, identity: true),
latitude = c.Single(),
longitude = c.Single(),
Address1 = c.String(),
Address2 = c.String(),
City = c.String(),
PostalCode = c.String(),
StateId = c.Int(),
UserId = c.Int(nullable: false),
BridgeId = c.Int(nullable: false),
})
.PrimaryKey(t => t.LocationId);
AddColumn("dbo.Users", "LocationId", c => c.Int());
DropIndex("dbo.Bridges", new[] { "StateId" });
DropIndex("dbo.UserAddresses", new[] { "StateId" });
DropIndex("dbo.Users", new[] { "UserAddressId" });
DropForeignKey("dbo.Bridges", "StateId", "dbo.States");
DropForeignKey("dbo.UserAddresses", "StateId", "dbo.States");
DropForeignKey("dbo.Users", "UserAddressId", "dbo.UserAddresses");
AlterColumn("dbo.Bridges", "Height", c => c.Single(nullable: false));
AlterColumn("dbo.Bridges", "BridgeId", c => c.Int(nullable: false));
DropColumn("dbo.Bridges", "StateId");
DropColumn("dbo.Bridges", "PostalCode");
DropColumn("dbo.Bridges", "City");
DropColumn("dbo.Bridges", "Address2");
DropColumn("dbo.Bridges", "Address1");
DropColumn("dbo.Bridges", "Longitude");
DropColumn("dbo.Bridges", "Latitude");
DropColumn("dbo.Users", "UserAddressId");
DropTable("dbo.UserAddresses");
CreateIndex("dbo.Bridges", "BridgeId");
CreateIndex("dbo.Locations", "StateId");
CreateIndex("dbo.Users", "LocationId");
AddForeignKey("dbo.Bridges", "BridgeId", "dbo.Locations", "LocationId");
AddForeignKey("dbo.Locations", "StateId", "dbo.States", "StateId");
AddForeignKey("dbo.Users", "LocationId", "dbo.Locations", "LocationId");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CDLRouteHelper.Models
{
public class NearbyViewModel
{
public float miles { get; set; }
}
}<file_sep>using CDLRouteHelper.Data.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebMatrix.WebData;
using CDLRouteHelper.Adapters.Interface;
using CDLRouteHelper.Adapters.Data;
public class UserData
{
public static UserData Current
{
get
{
UserData result = HttpContext.Current.Session["CurrentUser"] as UserData;
if (result == null && WebSecurity.IsAuthenticated)
{
result = InitializeCurrentUserById(WebSecurity.CurrentUserId);
}
return result;
}
private set
{
HttpContext.Current.Session["CurrentUser"] = value;
}
}
public static UserData InitializeCurrentUserById(int userId)
{
// Get an instance of our UserAdapter
IUserAdapter _userAdapter = new UserAdapter();
// Get a UserProfile using the current userId by calling
// a function on the User Adapter
UserData u = _userAdapter.GetUserDataFromUserId(userId);
// Set the current user in Session
// to the returned profile
UserData.Current = u;
// return the UserProfile
return u;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string Username { get; set; }
public int UserId { get; set; }
public string Email { get; set; }
public string[] Roles { get; set; }
public static bool IsAdmin
{
get { return Current.Roles.Any(r => r == Role.ADMINISTRATOR); }
}
internal static void Logout()
{
Current = null;
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CDLRouteHelper.Data;
using CDLRouteHelper.Data.Model;
using System.Device.Location;
namespace CDLRouteHelper.Adapters.Data
{
public class RestrictedAdapter : CDLRouteHelper.Adapters.Interface.IRestrictedAdapter
{
public Models.DisplayRestrictedViewModel GetDisplayRestrictedViewModel(Models.RestrictedIndexViewModel rivm)
{
CDLContext db = new CDLContext();
Models.DisplayRestrictedViewModel drvm = new Models.DisplayRestrictedViewModel();
List<Bridge> bridges = new List<Bridge>();
//"Straight Truck", "Single Trailer", "Double Trailer"
if (rivm.SelectedTruckType == "Single Trailer")
rivm.Type = TruckType.Single;
else if (rivm.SelectedTruckType == "Double Trailer")
rivm.Type = TruckType.Double;
else // (rivm.SelectedTruckType == "Straight Truck")
rivm.Type = TruckType.Straight;
drvm.Bridges = bridges; // list of bridges to populate for new view model
drvm.Bridges = db.Bridge.Where(b => ((b.Height <= rivm.Height) || b.Weights.Any(w => w.maxWeight <= rivm.Weight && w.TruckType == rivm.Type))
&& (b.State.PostalCode == rivm.State && b.City == rivm.City)).ToList();
return drvm;
}
public List<CDLRouteHelper.Models.Service.BridgeServiceModel> GetListBridgesByAll(double latitude, double longitude, float height, float weight, string trucktype, float distance)
{
List<Bridge> bFoundL = new List<Bridge>();
List<CDLRouteHelper.Models.Service.BridgeServiceModel> lbsm = new List<CDLRouteHelper.Models.Service.BridgeServiceModel>();
CDLContext db = new CDLContext();
TruckType tType;
//"Straight Truck", "Single Trailer", "Double Trailer"
if (trucktype == "Single")
tType = TruckType.Single;
else if (trucktype == "Double")
tType = TruckType.Double;
else // (tType == "Straight Truck")
tType = TruckType.Straight;
bFoundL = db.Bridge.Where(b => ((b.Height <= height) || b.Weights.Any(w => w.maxWeight <= weight && w.TruckType == tType))).ToList();
var gc = new GeoCoordinate();
gc.Latitude = latitude;
gc.Longitude = longitude;
foreach (var b in bFoundL)
{
var bsm = new Models.Service.BridgeServiceModel();
bsm.Guid = b.Guid;
bsm.Latitude = b.Latitude;
bsm.Longitude = b.Longitude;
bsm.Location = b.Address1;
bsm.City = b.City;
var bridgeGC = new GeoCoordinate();
bridgeGC.Latitude = bsm.Latitude;
bridgeGC.Longitude = bsm.Longitude;
if (b.Height == null)
b.Height = 0;
bsm.heightRestriction = (float)b.Height;
if (b.Weights.Count >= 1)
if (b.Weights.ElementAt(0).maxWeight != null)
{
bsm.weightStraightTruck = (float)b.Weights.ElementAt(0).maxWeight; ;
}
if (b.Weights.Count >= 2)
if (b.Weights.ElementAt(1).maxWeight != null)
{
bsm.weightSingleTrailer = (float)b.Weights.ElementAt(1).maxWeight;
}
if (b.Weights.Count >= 3)
if (b.Weights.ElementAt(2).maxWeight != null)
{
bsm.weightDoubleTrailer = (float)b.Weights.ElementAt(2).maxWeight;
}
if (bridgeGC.GetDistanceTo(gc) <= distance * 1609.344) // within distance passsed in keep it
{
lbsm.Add(bsm);
}
}
//bReturnL.Add(new Bridge { Address1 = "f32df2", City = "SomeCity", Latitude=43.17296218, Longitude=-78.696838, BridgeId=1});
//bReturnL.Add(new Bridge { Address1 = "f32df2", City = "SomeCity", Latitude = 43.1837882995605, Longitude = -78.6621017456055 });
return lbsm;
}
public Models.DisplayRestrictedViewModel GetDisplayRestrictedViewModelByCityAndState(Models.RetrieveByCityViewModel rbcvm)
{
CDLContext db = new CDLContext();
Models.DisplayRestrictedViewModel drvm = new Models.DisplayRestrictedViewModel();
List<Bridge> bridges = new List<Bridge>();
drvm.Bridges = bridges; // list of bridges to populate for new view model
drvm.Bridges = db.Bridge.Where(b => (b.State.PostalCode == rbcvm.State && b.City == rbcvm.City)).ToList();
return drvm;
}
public void SaveCreateViewModel(Models.CreateViewModel cvm)
{
CDLContext db = new CDLContext();
Bridge bridge = new Bridge();
List<Weight> weights = new List<Weight>();
Weight weight1 = new Weight();
Weight weight2 = new Weight();
Weight weight3 = new Weight();
State st = new State();
st = db.State.Where(s => cvm.State == s.PostalCode).FirstOrDefault();
bridge.Address1 = cvm.Address1;
bridge.City = cvm.City;
bridge.State = st;
bridge.PostalCode = cvm.PostalCode;
bridge.LastUpdated = DateTime.UtcNow;
bridge.Height = cvm.Height;
bridge.Latitude = cvm.Latitude;
bridge.Longitude = cvm.Longitude;
weight1.maxWeight = cvm.WeightStraight;
weight1.TruckType = TruckType.Straight;
weights.Add(weight1);
weight2.maxWeight = cvm.WeightSingle;
weight2.TruckType = TruckType.Single;
weights.Add(weight2);
weight3.maxWeight = cvm.WeightDouble;
weight3.TruckType = TruckType.Double;
weights.Add(weight3);
bridge.Weights = weights;
db.Bridge.Add(bridge);
db.SaveChanges();
}
public Models.CreateViewModel GetCreateViewModel(Models.RetrieveViewModel rvm)
{
Models.CreateViewModel cvm = new Models.CreateViewModel();
CDLContext db = new CDLContext();
Bridge bridge = new Bridge();
bridge = db.Bridge.Where(b => b.Latitude <= rvm.Latitude + 0.001 && b.Latitude >= rvm.Latitude - 0.001 &&
b.Longitude <= rvm.Longitude + 0.001 && b.Longitude >= rvm.Longitude - 0.001).FirstOrDefault();
if (bridge != null) //found match
{
cvm.Latitude = bridge.Latitude;
cvm.Longitude = bridge.Longitude;
cvm.Address1 = bridge.Address1;
cvm.City = bridge.City;
cvm.State = bridge.State.PostalCode;
cvm.PostalCode = bridge.PostalCode;
cvm.Height = bridge.Height;
cvm.BridgeId = bridge.BridgeId;
if (bridge.Weights.Count >= 1)
cvm.WeightStraight = bridge.Weights.ElementAt(0).maxWeight;
if (bridge.Weights.Count >= 2)
cvm.WeightSingle = bridge.Weights.ElementAt(1).maxWeight;
if (bridge.Weights.Count >= 3)
cvm.WeightDouble = bridge.Weights.ElementAt(2).maxWeight;
}
else
{ cvm = null; }
return cvm;
}
public void UpdateCreateViewModel(Models.CreateViewModel cvm)
{
CDLContext db = new CDLContext();
Bridge bridge = new Bridge();
bridge = db.Bridge.Find(cvm.BridgeId);
State st = new State();
st = db.State.Where(s => cvm.State == s.PostalCode).FirstOrDefault();
bridge.Address1 = cvm.Address1;
bridge.City = cvm.City;
bridge.State = st;
bridge.PostalCode = cvm.PostalCode;
bridge.LastUpdated = DateTime.UtcNow;
bridge.Height = cvm.Height;
bridge.Latitude = cvm.Latitude;
bridge.Longitude = cvm.Longitude;
if (bridge.Weights.Count >= 1)
bridge.Weights.ElementAt(0).maxWeight = cvm.WeightStraight;
if (bridge.Weights.Count >= 2)
bridge.Weights.ElementAt(1).maxWeight = cvm.WeightSingle;
if (bridge.Weights.Count >= 3)
bridge.Weights.ElementAt(2).maxWeight = cvm.WeightDouble;
db.SaveChanges();
}
public List<Models.CreateViewModel> GetListViewModel(Models.RetrieveViewModel rvm)
{
List<Models.CreateViewModel> lcvm = new List<Models.CreateViewModel>();
CDLContext db = new CDLContext();
GeoCoordinate gc = new GeoCoordinate(rvm.Latitude, rvm.Longitude);
List<Bridge> bridges = new List<Bridge>();
bridges = db.Bridge.ToList();
foreach (var b in bridges)
{
var cvm = new Models.CreateViewModel();
cvm.Address1 = b.Address1;
cvm.City = b.City;
cvm.State = b.State.Name;
cvm.PostalCode = b.PostalCode;
cvm.Latitude = b.Latitude;
cvm.Longitude = b.Longitude;
var bridgeGC = new GeoCoordinate();
bridgeGC.Latitude = cvm.Latitude;
bridgeGC.Longitude = cvm.Longitude;
if (b.Height == null)
b.Height = 0;
cvm.Height = (float)b.Height;
if (b.Weights.Count >= 1)
cvm.WeightStraight = b.Weights.ElementAt(0).maxWeight;
if (b.Weights.Count >= 2)
cvm.WeightSingle = b.Weights.ElementAt(1).maxWeight;
if (b.Weights.Count >= 3)
cvm.WeightDouble = b.Weights.ElementAt(2).maxWeight;
if (bridgeGC.GetDistanceTo(gc) <= rvm.Distance * 1609.344) // within distance passsed in keep it
{
lcvm.Add(cvm);
}
}
return lcvm;
}
public void DropBridge(Models.CreateViewModel cvm)
{
CDLContext db = new CDLContext();
Bridge bridge = new Bridge();
bridge = db.Bridge.Find(cvm.BridgeId);
db.Bridge.Remove(bridge);
db.SaveChanges();
}
}
}<file_sep>@model CDLRouteHelper.Models.DisplayRestrictedViewModel
@{
ViewBag.Title = "ShowByCity";
}
<h2>Results by City</h2>
@foreach (var bridge in Model.Bridges)
{
<div style="text-align: center; margin: 10px; background-color: #f9f9f9; border: solid; border-color: #f3f3f3" class="col-md-5 row">
<h5 style="color: red">Latitude = @bridge.Latitude </h5>
<h5 style="color: red">Longitude = @bridge.Longitude </h5>
<a href='@Url.Action("UpdateByCity", "Restricted", new { lat = bridge.Latitude, lon = bridge.Longitude })'>
<div class="well">
<p style="font: bold">@bridge.Address1 </p>
<p>@bridge.City, @bridge.State.Name </p>
<img src="http://maps.googleapis.com/maps/api/staticmap?center=@bridge.Latitude,@bridge.Longitude&zoom=12&size=200x200&markers=color:blue|@bridge.Latitude,@bridge.Longitude&sensor=false">
</div>
</a>
</div>
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace CDLRouteHelper.Services
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IBridgeService" in both code and config file together.
[ServiceContract]
public interface IBridgeService
{
[OperationContract]
List<Models.Service.BridgeServiceModel> List();
[OperationContract]
List<Models.Service.BridgeServiceModel> ListByDistanceFrom(double latitude, double longitude, float distance);
}
}
<file_sep>@model CDLRouteHelper.Models.RetrieveViewModel
@using (@Html.BeginForm("SearchByCoords", "Restricted", FormMethod.Post, null))
{
@Html.ValidationSummary(true, "Please correct the following:")
<div class="col-md-6 row" style="background-color: #f9f9f9; border: solid; border-color: #f3f3f3">
<div class="page-header">
<h1>Find Bridges By Distance <small>starting from latitude and longitude </small> </h1>
</div>
<div style="margin-top: 20px" class="well">
<div>
@Html.ValidationMessageFor(c => c.Latitude)
</div>
<div>
@Html.LabelFor(c => c.Latitude)
@Html.TextBoxFor(c => c.Latitude)
</div>
</div>
<div style="margin-top: 10px" class="well">
<div>
<div>@Html.ValidationMessageFor(c => c.Longitude) </div>
</div>
<div>
@Html.LabelFor(c => c.Longitude)
@Html.TextBoxFor(c => c.Longitude)
</div>
</div>
<div style="margin: 20px; text-align: center">
<button class="btn btn-primary btn-lg" type="submit">Search</button>
</div>
</div>
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CDLRouteHelper.Models;
using CDLRouteHelper.Adapters.Data;
using CDLRouteHelper.Data.Model;
using System.Web.Script.Serialization;
using System.Device.Location;
namespace CDLRouteHelper.Controllers
{
[Authorize]
public class RestrictedController : Controller
{
RestrictedAdapter _adapter;
public RestrictedController()
{
_adapter = new RestrictedAdapter();
}
[HttpPost]
public ActionResult SearchByCoords(RetrieveViewModel rvm)
{
List<CDLRouteHelper.Models.CreateViewModel> lcvm = new List<CDLRouteHelper.Models.CreateViewModel>();
if (ModelState.IsValid) // required fields entered?
{
rvm.Distance = 50; //start at within 50 miles
ViewBag.lat = rvm.Latitude;
ViewBag.lon = rvm.Longitude;
lcvm = _adapter.GetListViewModel(rvm);
if (lcvm == null) // not found
return View();
else
return View("DisplayByCoords", lcvm);
}
return View();
}
[HttpGet]
public ActionResult SearchByCoords()
{
return View();
}
public ActionResult UpdateByCity(double lat, double lon)
{
RetrieveViewModel rvm = new RetrieveViewModel();
rvm.Latitude = lat;
rvm.Longitude = lon;
if (ModelState.IsValid) // required fields entered?
{
return View("Update", _adapter.GetCreateViewModel(rvm));
}
return View();
}
[HttpPost]
public ActionResult RetrieveByCity(RetrieveByCityViewModel rbcvm)
{
DisplayRestrictedViewModel model = new DisplayRestrictedViewModel();
if (ModelState.IsValid) // required fields entered?
{
model = _adapter.GetDisplayRestrictedViewModelByCityAndState(rbcvm);
return View("ShowByCity", model);
}
return View();
}
[HttpGet]
[Authorize(Roles = "Staff, Administrator")]
public ActionResult RetrieveByCity()
{
return View();
}
[HttpPost]
public ActionResult Update(CreateViewModel cvm)
{
if (ModelState.IsValid) // required fields entered?
{
_adapter.UpdateCreateViewModel(cvm);
return View("Retrieve");
}
return View();
}
[HttpPost]
public ActionResult DeleteByCoords(CreateViewModel cvm)
{
_adapter.DropBridge(cvm);
return RedirectToAction("Delete", "Restricted");
}
[HttpPost]
public ActionResult Delete(RetrieveViewModel rvm)
{
CreateViewModel cvm = new CreateViewModel();
if (ModelState.IsValid) // required fields entered?
{
cvm = _adapter.GetCreateViewModel(rvm);
if (cvm == null) // not found
return View();
else
return View("DeleteBridge", cvm);
}
return View();
}
[HttpGet]
[Authorize(Roles="Administrator")]
public ActionResult Delete()
{
return View();
}
[HttpPost]
public ActionResult Retrieve(RetrieveViewModel rvm)
{
CreateViewModel cvm = new CreateViewModel();
if (ModelState.IsValid) // required fields entered?
{
cvm = _adapter.GetCreateViewModel(rvm);
if (cvm == null) // not found
return View();
else
return View("Update", cvm);
}
return View();
}
[HttpGet]
[Authorize(Roles = "Staff, Administrator")]
public ActionResult Retrieve()
{
return View();
}
[HttpPost]
public ActionResult Create(CreateViewModel cvm)
{
if (ModelState.IsValid) // required fields entered?
{
_adapter.SaveCreateViewModel(cvm);
return RedirectToAction("Create", "Restricted");
}
return View();
}
public ActionResult Create()
{
return View();
}
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(RestrictedIndexViewModel rivm)
{
DisplayRestrictedViewModel model = new DisplayRestrictedViewModel();
if (ModelState.IsValid) // required fields entered?
{
model = _adapter.GetDisplayRestrictedViewModel(rivm);
if (model == null) // not found
return View("Index");
else
{
model.City = rivm.City;
model.State = rivm.State;
model.Height = rivm.Height;
model.Weight = rivm.Weight;
model.Type = rivm.Type;
if (model.Type == TruckType.Single)
ViewBag.trucktype = "Single";
else if (model.Type == TruckType.Double)
ViewBag.trucktype = "Double";
else
ViewBag.trucktype = "Straight";
return View("Show", model);
}
}
return View("Index");
}
public ActionResult Show(DisplayRestrictedViewModel drvm)
{
if (drvm.Type == TruckType.Single)
ViewBag.trucktype = "Single";
else if (drvm.Type == TruckType.Double)
ViewBag.trucktype = "Double";
else
ViewBag.trucktype = "Straight";
return View(drvm);
}
public ActionResult Nearby()
{
NearbyViewModel nvm = new NearbyViewModel();
return View(nvm);
}
[HttpPost]
public JsonResult GetList(double latitude, double longitude, float distance)
{
CDLRouteHelper.Adapters.Service.ServiceBridge _adapter = new CDLRouteHelper.Adapters.Service.ServiceBridge();
List<CDLRouteHelper.Models.Service.BridgeServiceModel> lbsm = new List<CDLRouteHelper.Models.Service.BridgeServiceModel>();
lbsm = _adapter.GetListByDistanceFrom(latitude, longitude, distance);
return Json(lbsm);
//CDLRouteHelper.Models.Service.BridgeServiceModel bsm = new CDLRouteHelper.Models.Service.BridgeServiceModel();
//bsm.Latitude = latitude;
//bsm.Longitude = longitude;
//return Json(new { latitude = lbsm[0].Latitude, longitude = lbsm[0].Longitude });
//return Json(new { foo = "foo", bar = "barrrrr" });
}
[HttpPost]
public JsonResult GetListByAll(double latitude, double longitude, float height, float weight, string trucktype, float distance)
{
List<CDLRouteHelper.Models.Service.BridgeServiceModel> lbsm = new List<CDLRouteHelper.Models.Service.BridgeServiceModel>();
lbsm = _adapter.GetListBridgesByAll(latitude, longitude, height, weight, trucktype, distance);
// bridges.Add(new Bridge { Address1 = "f32df2", City = "SomeCity", Latitude=43.17296218, Longitude=-78.696838});
return Json(lbsm);
}
[HttpPost]
public JsonResult GetListCoordsAsString(string latLng, float distance)
{
double lat = CDLRouteHelper.Helper.GeoHelper.LatLonToLatDouble(latLng);
double lon = CDLRouteHelper.Helper.GeoHelper.LatLonToLonDouble(latLng);
CDLRouteHelper.Adapters.Service.ServiceBridge _adapter = new CDLRouteHelper.Adapters.Service.ServiceBridge();
List<CDLRouteHelper.Models.Service.BridgeServiceModel> lbsm = new List<CDLRouteHelper.Models.Service.BridgeServiceModel>();
CDLRouteHelper.Services.BridgeService bs = new CDLRouteHelper.Services.BridgeService();
//lbsm = _adapter.GetListByDistanceFrom(lat, lon, distance);
return Json(bs.ListByDistanceFrom(lat, lon, distance));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CDLRouteHelper.Adapters.Service
{
interface IServiceBridge
{
List<Models.Service.BridgeServiceModel> GetListBridgeServiceModel();
List<Models.Service.BridgeServiceModel> GetListByDistanceFrom(double latitude, double longitude, float distance);
}
}
<file_sep>@model CDLRouteHelper.Models.LoginModel
@{
ViewBag.Title = "Log in";
}
<section id="loginForm">
@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Log in Form</legend>
<div class="col-md-8 row" style="background-color: #f9f9f9; border: solid; border-color: #f3f3f3">
<div class="page-header">
<h1>Log In <small> use a local account to log in </small></h1>
</div>
<div style="margin-top: 20px" class="well">
<div>
@Html.ValidationMessageFor(m => m.UserName)
</div>
<div>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
</div>
</div>
<div class="well">
<div>
@Html.ValidationMessageFor(m => m.Password)
</div>
<div>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
</div>
</div>
<div class="well">
@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe, new { @class = "checkbox" })
</div>
<div style="margin-bottom: 20px; text-align: center" >
<button class='zocial logmein' type="submit" name="provider" value="Log In" title="Log in using your local account">Sign In Local</button>
</div>
</div>
</fieldset>
<p>
@Html.ActionLink("Register", "Register") if you don't have an account.
</p>
}
</section>
<section class="social" id="socialLoginForm">
<h2>Use another service to log in.</h2>
@Html.Action("ExternalLoginsList", new { ReturnUrl = ViewBag.ReturnUrl })
</section>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CDLRouteHelper.Data.Model;
using System.ComponentModel.DataAnnotations;
namespace CDLRouteHelper.Models
{
public class RestrictedIndexViewModel
{
[Required]
[Display(Name = "Truck Height (ft)")]
public float Height { get; set; }
[Required]
[Display(Name = "Truck Weight (tons)")]
public float Weight { get; set; }
[Required]
public string City { get; set; }
[Required]
public string State { get; set; }
[Display(Name = "Truck Type")]
public TruckType Type { get; set; }
public string SelectedTruckType { get; set; }
public List<string> TruckTypes { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CDLRouteHelper.Models;
namespace CDLRouteHelper.Adapters.Interface
{
interface IRestrictedAdapter
{
void SaveCreateViewModel(CreateViewModel cvm);
void DropBridge(CreateViewModel cvm);
CreateViewModel GetCreateViewModel(RetrieveViewModel rvm);
List<CreateViewModel> GetListViewModel(Models.RetrieveViewModel rvm);
void UpdateCreateViewModel(CreateViewModel cvm);
DisplayRestrictedViewModel GetDisplayRestrictedViewModel(RestrictedIndexViewModel rivm);
DisplayRestrictedViewModel GetDisplayRestrictedViewModelByCityAndState(Models.RetrieveByCityViewModel rbcvm);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CDLRouteHelper.Data.Model
{
public class State
{
public int StateId { get; set; }
public string Name { get; set; }
public string PostalCode { get; set; }
public int CountryId { get; set; }
public virtual List<Bridge> Bridges { get; set; }
public virtual List<UserAddress> UserAddresses { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CDLRouteHelper.Data.Model;
namespace CDLRouteHelper.Models
{
public class DisplayRestrictedViewModel
{
public List<Bridge> Bridges { get; set; }
public string City { get; set; }
public string State { get; set; }
public float Height { get; set; }
public float Weight { get; set; }
public TruckType Type { get; set; }
}
}<file_sep>
namespace CDLRouteHelper.Data.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Web;
using System.Linq;
using System.Web;
internal sealed class Configuration : DbMigrationsConfiguration<CDLRouteHelper.Data.CDLContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(CDLRouteHelper.Data.CDLContext context)
{
Seeder.Seed(context);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CDLRouteHelper.Data;
using System.Data.Entity.Migrations;
using CDLRouteHelper.Data.Model;
using System.Data.Entity.Validation;
namespace CDLRouteHelper.Data.Migrations
{
public class Seeder
{
public static void Seed(CDLRouteHelper.Data.CDLContext context, bool seedUser = true, bool seedUserAddress = true, bool seedState = true, bool seedBridge = true, bool seedWeight = true, bool seedRoles = true, bool seedUserRoles = true, bool seedMembership = true)
{
if (seedUser) SeedUser(context);
if (seedState) SeedState(context);
if (seedUserAddress) SeedUserAddress(context);
if (seedBridge) SeedBridge(context);
if (seedWeight) SeedWeight(context);
if (seedRoles) SeedRoles(context);
if (seedUserRoles) SeedUserRoles(context);
if (seedMembership) SeedMembership(context);
}
private static void SeedUser(CDLContext context)
{
context.User.AddOrUpdate(u => u.Email,
new User() { Username = "Admin01", FirstName = "Donovan", LastName = "May", Email = "<EMAIL>" },
new User() { Username = "Staff01", FirstName = "Freddie", LastName = "Mack", Email = "<EMAIL>" },
new User() { Username = "User01", FirstName = "Darth", LastName = "Vader", Email = "<EMAIL>" },
new User() { Username = "Admin02", FirstName = "Loke", LastName = "Groundrunner", Email = "<EMAIL>" },
new User() { Username = "Staff02", FirstName = "Grumpy", LastName = "Pants", Email = "<EMAIL>" },
new User() { Username = "User02", FirstName = "Captain", LastName = "Crunch", Email = "<EMAIL>" });
context.SaveChanges();
}
private static void SeedRoles(CDLContext context)
{
context.Roles.AddOrUpdate(r => r.Name,
new Role() { Name = Role.ADMINISTRATOR },
new Role() { Name = Role.STAFF },
new Role() { Name = Role.USER }
);
context.SaveChanges();
}
private static void SeedUserRoles(CDLContext context)
{
context.UserRole.AddOrUpdate(ur => ur.UserId,
new UserRole() { UserId = 1, RoleId = 1 },
new UserRole() { UserId = 2, RoleId = 2 },
new UserRole() { UserId = 3, RoleId = 3 },
new UserRole() { UserId = 4, RoleId = 1 },
new UserRole() { UserId = 5, RoleId = 2 },
new UserRole() { UserId = 6, RoleId = 3 }
);
context.SaveChanges();
}
private static void SeedMembership(CDLContext context)
{
try
{
context.Memberships.AddOrUpdate(m => m.UserId, //userID is PK
new Membership() { UserId = 1, CreateDate = DateTime.UtcNow, IsConfirmed = true, PasswordFailuresSinceLastSuccess = 0, Password = "<PASSWORD>==", PasswordSalt = "" },
new Membership() { UserId = 2, CreateDate = DateTime.UtcNow, IsConfirmed = true, PasswordFailuresSinceLastSuccess = 0, Password = "<PASSWORD>==", PasswordSalt = "" },
new Membership() { UserId = 3, CreateDate = DateTime.UtcNow, IsConfirmed = true, PasswordFailuresSinceLastSuccess = 0, Password = "<PASSWORD>==", PasswordSalt = "" },
new Membership() { UserId = 4, CreateDate = DateTime.UtcNow, IsConfirmed = true, PasswordFailuresSinceLastSuccess = 0, Password = "<PASSWORD>==", PasswordSalt = "" },
new Membership() { UserId = 5, CreateDate = DateTime.UtcNow, IsConfirmed = true, PasswordFailuresSinceLastSuccess = 0, Password = "<PASSWORD>==", PasswordSalt = "" },
new Membership() { UserId = 6, CreateDate = DateTime.UtcNow, IsConfirmed = true, PasswordFailuresSinceLastSuccess = 0, Password = "<PASSWORD>==", PasswordSalt = "" }
);
context.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
//// Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
// eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}
private static void SeedUserAddress(CDLContext context)
{
context.UserAddress.AddOrUpdate(a => new { a.Address1 },
new UserAddress() { Address1 = "1234 Dearborn Pkwy", Address2 = "Address Line 2", City = "Houston", PostalCode = "12345", StateId = 43, UserId = 1 },
new UserAddress() { Address1 = "5678 Transit St", Address2 = "Address Line 2", City = "Houston", PostalCode = "12345", StateId = 43, UserId = 2 },
new UserAddress() { Address1 = "8912 Stone Rd", Address2 = "Address Line 2", City = "Houston", PostalCode = "12345", StateId = 43, UserId = 3 },
new UserAddress() { Address1 = "12 Black St", Address2 = "Address Line 2", City = "Houston", PostalCode = "12345", StateId = 43, UserId = 4 },
new UserAddress() { Address1 = "8932 Fisk Rd", Address2 = "Address Line 2", City = "Houston", PostalCode = "12345", StateId = 43, UserId = 5 },
new UserAddress() { Address1 = "4023 Carriage Lane", Address2 = "Address Line 2", City = "Houston", PostalCode = "12345", StateId = 43, UserId = 6 }
);
context.SaveChanges();
}
private static void SeedState(CDLContext context)
{
context.State.AddOrUpdate(s => s.PostalCode,
new State() { Name = "Alabama", PostalCode = "AL", CountryId = 1 },
new State() { Name = "Alaska", PostalCode = "AK", CountryId = 1 },
new State() { Name = "Arizona", PostalCode = "AZ", CountryId = 1 },
new State() { Name = "Arkansas", PostalCode = "AR", CountryId = 1 },
new State() { Name = "California", PostalCode = "CA", CountryId = 1 }, //5
new State() { Name = "Colorado", PostalCode = "CO", CountryId = 1 },
new State() { Name = "Connecticut", PostalCode = "CT", CountryId = 1 },
new State() { Name = "Deleware", PostalCode = "DE", CountryId = 1 },
new State() { Name = "Florida", PostalCode = "FL", CountryId = 1 },
new State() { Name = "Georgia", PostalCode = "GA", CountryId = 1 }, //10
new State() { Name = "Hawaii", PostalCode = "HI", CountryId = 1 },
new State() { Name = "Idaho", PostalCode = "ID", CountryId = 1 },
new State() { Name = "Illinois", PostalCode = "IL", CountryId = 1 },
new State() { Name = "Indiana", PostalCode = "IN", CountryId = 1 },
new State() { Name = "Iowa", PostalCode = "IA", CountryId = 1 },
new State() { Name = "Kansas", PostalCode = "KS", CountryId = 1 }, //16
new State() { Name = "Kentucky", PostalCode = "KY", CountryId = 1 },
new State() { Name = "Lousiana", PostalCode = "LA", CountryId = 1 },
new State() { Name = "Maine", PostalCode = "ME", CountryId = 1 },
new State() { Name = "Maryland", PostalCode = "MD", CountryId = 1 }, //20
new State() { Name = "Massachucetts", PostalCode = "MA", CountryId = 1 },
new State() { Name = "Michigan", PostalCode = "MI", CountryId = 1 },
new State() { Name = "Minnesota", PostalCode = "MN", CountryId = 1 },
new State() { Name = "Mississippi", PostalCode = "MS", CountryId = 1 },
new State() { Name = "Missouri", PostalCode = "MO", CountryId = 1 },//25
new State() { Name = "Montana", PostalCode = "MT", CountryId = 1 },
new State() { Name = "Nebraska", PostalCode = "NE", CountryId = 1 },
new State() { Name = "Nevada", PostalCode = "NV", CountryId = 1 },
new State() { Name = "New Hampshire", PostalCode = "NH", CountryId = 1 },
new State() { Name = "New Jersey", PostalCode = "NJ", CountryId = 1 },//30
new State() { Name = "New Mexico", PostalCode = "NM", CountryId = 1 },
new State() { Name = "New York", PostalCode = "NY", CountryId = 1 },
new State() { Name = "North Carolina", PostalCode = "NC", CountryId = 1 },
new State() { Name = "North Dakota", PostalCode = "ND", CountryId = 1 },
new State() { Name = "Ohio", PostalCode = "OH", CountryId = 1 }, //35
new State() { Name = "Oklahoma", PostalCode = "OK", CountryId = 1 },
new State() { Name = "Oregon", PostalCode = "OR", CountryId = 1 },
new State() { Name = "Pennsylvania", PostalCode = "PA", CountryId = 1 },
new State() { Name = "Rhode Island", PostalCode = "RI", CountryId = 1 },
new State() { Name = "South Carolina", PostalCode = "SC", CountryId = 1 }, //40
new State() { Name = "South Dakota", PostalCode = "SD", CountryId = 1 },
new State() { Name = "Tennessee", PostalCode = "TN", CountryId = 1 },
new State() { Name = "Texas", PostalCode = "TX", CountryId = 1 },
new State() { Name = "Utah", PostalCode = "UT", CountryId = 1 },
new State() { Name = "Vermont", PostalCode = "VT", CountryId = 1 }, //45
new State() { Name = "Virginia", PostalCode = "VA", CountryId = 1 },
new State() { Name = "Washington", PostalCode = "WA", CountryId = 1 },
new State() { Name = "West Virgina", PostalCode = "WV", CountryId = 1 },
new State() { Name = "Wisconsin", PostalCode = "WI", CountryId = 1 },
new State() { Name = "Wyoming", PostalCode = "WY", CountryId = 1 } //50
);
context.SaveChanges();
}
private static void SeedBridge(CDLContext context)
{
context.Bridge.AddOrUpdate(b => new { b.Address1 },
//new Bridge()
//{
// Guid = Guid.NewGuid(),
// Height = 14.0f,
// LastUpdated = DateTime.UtcNow,
// NumTimesReported = 1,
// Address1 = "Airport Blvd @ Mykawa Rd",
// City = "Houston",
// PostalCode = "12345",
// StateId = 43,
// Latitude = 29.645679f,
// Longitude = -95.312018f
//},
// new Bridge()
// {
// Guid = Guid.NewGuid(),
// Height = 10.5f,
// LastUpdated = DateTime.UtcNow,
// NumTimesReported = 3,
// Address1 = "LawnDale St @ San Antonio St",
// City = "Houston",
// PostalCode = "12345",
// StateId = 43,
// Latitude = 29.716600f,
// Longitude = -95.284102f
// },
// new Bridge()
// {
// Guid = Guid.NewGuid(),
// Height = 12.5f,
// LastUpdated = DateTime.UtcNow,
// NumTimesReported = 2,
// Address1 = "Griggs Rd @ Evergreen Dr",
// City = "Houston",
// PostalCode = "12345",
// StateId = 43,
// Latitude = 29.716824f,
// Longitude = -95.290153f
// },
// new Bridge()
// {
// Guid = Guid.NewGuid(),
// Height = 14.0f,
// LastUpdated = DateTime.UtcNow,
// NumTimesReported = 1,
// Address1 = "Telephone Rd @ Tellespen St",
// City = "Houston",
// PostalCode = "12345",
// StateId = 43,
// Latitude = 29.726216f,
// Longitude = -95.324743f
// },
// new Bridge()
// {
// Guid = Guid.NewGuid(),
// Height = 10.5f,
// LastUpdated = DateTime.UtcNow,
// NumTimesReported = 3,
// Address1 = "N Transit @ Green St",
// City = "Lockport",
// PostalCode = "14094",
// StateId = 32,
// Latitude = 43.172961f,
// Longitude = -78.696839f
// },
// new Bridge()
// {
// Guid = Guid.NewGuid(),
// Height = 12.5f,
// LastUpdated = DateTime.UtcNow,
// NumTimesReported = 2,
// Address1 = "Cold Springs Rd @ Chestnut Ridge",
// City = "Hartland",
// PostalCode = "14032",
// StateId = 32,
// Latitude = 43.183789f,
// Longitude = -78.662099f
// },
// new Bridge()
// {
// Guid = Guid.NewGuid(),
// Height = 11.5f,
// LastUpdated = DateTime.UtcNow,
// NumTimesReported = 1,
// Address1 = "Genesse St @ Wasmuth Ave",
// City = "Buffalo",
// PostalCode = "14201",
// StateId = 32,
// Latitude = 42.906426f,
// Longitude = -78.828771f
// },
// new Bridge()
// {
// Guid = Guid.NewGuid(),
// Height = 9.5f,
// LastUpdated = DateTime.UtcNow,
// NumTimesReported = 1,
// Address1 = "Main St @ Fillmore Ave",
// City = "Buffalo",
// PostalCode = "14094",
// StateId = 32,
// Latitude = 42.935793f,
// Longitude = -78.842268f
// },
// // BridgeId = 9 -- weight
// new Bridge()
// {
// Guid = Guid.NewGuid(),
// Height = null,
// LastUpdated = DateTime.UtcNow,
// NumTimesReported = 2,
// Address1 = "W 21st ST N @ N Mclean",
// City = "Wichita",
// PostalCode = "12235",
// StateId = 16,
// Latitude = 37.722997f,
// Longitude = -97.383435f
// },
// new Bridge()
// {
// Guid = Guid.NewGuid(),
// Height = null,
// LastUpdated = DateTime.UtcNow,
// NumTimesReported = 3,
// Address1 = "W Zoo Blvd @ W Windmill",
// City = "Wichita",
// PostalCode = "122345",
// StateId = 16,
// Latitude = 37.715515f,
// Longitude = -97.401448f
// },
// new Bridge()
// {
// Guid = Guid.NewGuid(),
// Height = null,
// LastUpdated = DateTime.UtcNow,
// NumTimesReported = 5,
// Address1 = "E 83rd St S @ N River St",
// City = "Derby",
// PostalCode = "12245",
// StateId = 16,
// Latitude = 37.544321f,
// Longitude = -97.276087f
// },
// // Derby Texas
// new Bridge()
// {
// Guid = Guid.NewGuid(),
// Height = null,
// LastUpdated = DateTime.UtcNow,
// NumTimesReported = 1,
// Address1 = "S Pleasant Vally Rd @ E Ceasar Chavez St",
// City = "Austin",
// PostalCode = "12345",
// StateId = 43,
// Latitude = 30.250127f,
// Longitude = -97.713454f
// },
// // Utah
// new Bridge()
// {
// Guid = Guid.NewGuid(),
// Height = null,
// LastUpdated = DateTime.UtcNow,
// NumTimesReported = 3,
// Address1 = "900 S Indiana Ave @ 2015 W St",
// City = "Lockport",
// PostalCode = "14094",
// StateId = 44,
// Latitude = 40.750405f,
// Longitude = -111.952765f
// },
// new Bridge()
// {
// Guid = Guid.NewGuid(),
// Height = null,
// LastUpdated = DateTime.UtcNow,
// NumTimesReported = 2,
// Address1 = "Grant St @ Amherst St",
// City = "Buffalo",
// PostalCode = "14120",
// StateId = 32,
// Latitude = 42.936865f,
// Longitude = -78.888992f
// },
// new Bridge()
// {
// Guid = Guid.NewGuid(),
// Height = null,
// LastUpdated = DateTime.UtcNow,
// NumTimesReported = 1,
// Address1 = "Elmwood Ave @ Scajaquada Expy",
// City = "Buffalo",
// PostalCode = "14120",
// StateId = 32,
// Latitude = 42.934681f,
// Longitude = -78.877662f
// },
// new Bridge()
// {
// Guid = Guid.NewGuid(),
// Height = null,
// LastUpdated = DateTime.UtcNow,
// NumTimesReported = 1,
// Address1 = "Deleware Ave @ Forest Ave",
// City = "Buffalo",
// PostalCode = "14120",
// StateId = 32,
// Latitude = 42.929230f,
// Longitude = -78.865517f
// },
// new Bridge()
// {
// Guid = Guid.NewGuid(),
// Height = null,
// LastUpdated = DateTime.UtcNow,
// NumTimesReported = 2,
// Address1 = "E Orem @ Webercrest",
// City = "Houston",
// PostalCode = "12345",
// StateId = 43,
// Latitude = 29.625505f,
// Longitude = -95.329292f
// },
// new Bridge()
// {
// Guid = Guid.NewGuid(),
// Height = null,
// LastUpdated = DateTime.UtcNow,
// NumTimesReported = 3,
// Address1 = "W Orem @ East of Almeda",
// City = "Houston",
// PostalCode = "12345",
// StateId = 43,
// Latitude = 29.627398f,
// Longitude = -95.407172f
// },
// new Bridge()
// {
// Guid = Guid.NewGuid(),
// Height = null,
// LastUpdated = DateTime.UtcNow,
// NumTimesReported = 5,
// Address1 = "Memorial Dr @ Sawer",
// City = "Houston",
// PostalCode = "12345",
// StateId = 43,
// Latitude = 29.762623f,
// Longitude = -95.381595f
// },
new Bridge()
{
Guid = Guid.NewGuid(),
Height = null,
LastUpdated = DateTime.UtcNow,
NumTimesReported = 5,
Address1 = "Youngstown Wilson Rd @ 3 mi east of Youngstown",
City = "Youngstown",
PostalCode = "14174",
StateId = 32,
Latitude = 43.271437f,
Longitude = -78.957582f
},
new Bridge()
{
Guid = Guid.NewGuid(),
Height = null,
LastUpdated = DateTime.UtcNow,
NumTimesReported = 5,
Address1 = "Willow Rd @ 0.1 mi SE of South Wilson",
City = "Wilson",
PostalCode = "14172",
StateId = 32,
Latitude = 43.231428f,
Longitude = -78.811626f
},
new Bridge()
{
Guid = Guid.NewGuid(),
Height = null,
LastUpdated = DateTime.UtcNow,
NumTimesReported = 5,
Address1 = "Canal Rd @ 1.8 mi E of Lockport",
City = "Lockport",
PostalCode = "14094",
StateId = 32,
Latitude = 43.193392f,
Longitude = -78.633129f
},
new Bridge()
{
Guid = Guid.NewGuid(),
Height = null,
LastUpdated = DateTime.UtcNow,
NumTimesReported = 5,
Address1 = "Day Rd @ 1.0 mi E of Lockport",
City = "Lockport",
PostalCode = "14094",
StateId = 32,
Latitude = 43.190049f,
Longitude = -78.650769f
},
new Bridge()
{
Guid = Guid.NewGuid(),
Height = null,
LastUpdated = DateTime.UtcNow,
NumTimesReported = 5,
Address1 = "Interstate 190 @ 0.5 mi N JCT I190 & SH198",
City = "Buffalo",
PostalCode = "14207",
StateId = 32,
Latitude = 42.931774f,
Longitude = -78.901448f
},
new Bridge()
{
Guid = Guid.NewGuid(),
Height = null,
LastUpdated = DateTime.UtcNow,
NumTimesReported = 5,
Address1 = "<NAME> @ 2.5 mi S JCT RTS I190<198",
City = "Buffalo",
PostalCode = "14213",
StateId = 43,
Latitude = 42.915199f,
Longitude = -78.901543f
}
);
}
private static void SeedWeight(CDLContext context)
{
context.Weight.AddOrUpdate(w => new { w.BridgeId, w.TruckType },
//new Weight() { BridgeId = 1, maxWeight = null, TruckType = Model.TruckType.Straight },
//new Weight() { BridgeId = 1, maxWeight = null, TruckType = Model.TruckType.Single },
//new Weight() { BridgeId = 1, maxWeight = null, TruckType = Model.TruckType.Double },
//new Weight() { BridgeId = 2, maxWeight = null, TruckType = Model.TruckType.Straight },
//new Weight() { BridgeId = 2, maxWeight = null, TruckType = Model.TruckType.Single },
//new Weight() { BridgeId = 2, maxWeight = null, TruckType = Model.TruckType.Double },
//new Weight() { BridgeId = 3, maxWeight = null, TruckType = Model.TruckType.Straight },
//new Weight() { BridgeId = 3, maxWeight = null, TruckType = Model.TruckType.Single },
//new Weight() { BridgeId = 3, maxWeight = null, TruckType = Model.TruckType.Double },
//new Weight() { BridgeId = 4, maxWeight = null, TruckType = Model.TruckType.Straight },
//new Weight() { BridgeId = 4, maxWeight = null, TruckType = Model.TruckType.Single },
//new Weight() { BridgeId = 4, maxWeight = null, TruckType = Model.TruckType.Double },
//new Weight() { BridgeId = 5, maxWeight = null, TruckType = Model.TruckType.Straight },
//new Weight() { BridgeId = 5, maxWeight = null, TruckType = Model.TruckType.Single },
//new Weight() { BridgeId = 5, maxWeight = null, TruckType = Model.TruckType.Double },
//new Weight() { BridgeId = 6, maxWeight = null, TruckType = Model.TruckType.Straight },
//new Weight() { BridgeId = 6, maxWeight = null, TruckType = Model.TruckType.Single },
//new Weight() { BridgeId = 6, maxWeight = null, TruckType = Model.TruckType.Double },
//new Weight() { BridgeId = 7, maxWeight = null, TruckType = Model.TruckType.Straight },
//new Weight() { BridgeId = 7, maxWeight = null, TruckType = Model.TruckType.Single },
//new Weight() { BridgeId = 7, maxWeight = null, TruckType = Model.TruckType.Double },
//new Weight() { BridgeId = 8, maxWeight = null, TruckType = Model.TruckType.Straight },
//new Weight() { BridgeId = 8, maxWeight = null, TruckType = Model.TruckType.Single },
//new Weight() { BridgeId = 8, maxWeight = null, TruckType = Model.TruckType.Double },
//new Weight() { BridgeId = 9, maxWeight = 15f, TruckType = Model.TruckType.Straight },
//new Weight() { BridgeId = 9, maxWeight = 22f, TruckType = Model.TruckType.Single },
//new Weight() { BridgeId = 9, maxWeight = 25f, TruckType = Model.TruckType.Double },
//new Weight() { BridgeId = 10, maxWeight = 15f, TruckType = Model.TruckType.Straight },
//new Weight() { BridgeId = 10, maxWeight = 15f, TruckType = Model.TruckType.Single },
//new Weight() { BridgeId = 10, maxWeight = 15f, TruckType = Model.TruckType.Double },
//new Weight() { BridgeId = 11, maxWeight = 12f, TruckType = Model.TruckType.Straight },
//new Weight() { BridgeId = 11, maxWeight = 12f, TruckType = Model.TruckType.Single },
//new Weight() { BridgeId = 11, maxWeight = 12f, TruckType = Model.TruckType.Double },
//new Weight() { BridgeId = 12, maxWeight = 50f, TruckType = Model.TruckType.Straight },
//new Weight() { BridgeId = 12, maxWeight = 50f, TruckType = Model.TruckType.Single },
//new Weight() { BridgeId = 12, maxWeight = 50f, TruckType = Model.TruckType.Double },
//new Weight() { BridgeId = 13, maxWeight = 35f, TruckType = Model.TruckType.Straight },
//new Weight() { BridgeId = 13, maxWeight = 35f, TruckType = Model.TruckType.Single },
//new Weight() { BridgeId = 13, maxWeight = 35f, TruckType = Model.TruckType.Double },
//new Weight() { BridgeId = 14, maxWeight = 22f, TruckType = Model.TruckType.Straight },
//new Weight() { BridgeId = 14, maxWeight = 22f, TruckType = Model.TruckType.Single },
//new Weight() { BridgeId = 14, maxWeight = 22f, TruckType = Model.TruckType.Double },
//new Weight() { BridgeId = 15, maxWeight = 11.5f, TruckType = Model.TruckType.Straight },
//new Weight() { BridgeId = 15, maxWeight = 11.5f, TruckType = Model.TruckType.Single },
//new Weight() { BridgeId = 15, maxWeight = 11.5f, TruckType = Model.TruckType.Double },
//new Weight() { BridgeId = 16, maxWeight = 20f, TruckType = Model.TruckType.Straight },
//new Weight() { BridgeId = 16, maxWeight = 30f, TruckType = Model.TruckType.Single },
//new Weight() { BridgeId = 16, maxWeight = 40f, TruckType = Model.TruckType.Double },
//new Weight() { BridgeId = 17, maxWeight = 20f, TruckType = Model.TruckType.Straight },
//new Weight() { BridgeId = 17, maxWeight = 25f, TruckType = Model.TruckType.Single },
//new Weight() { BridgeId = 17, maxWeight = 25f, TruckType = Model.TruckType.Double },
//new Weight() { BridgeId = 18, maxWeight = 10f, TruckType = Model.TruckType.Straight },
//new Weight() { BridgeId = 18, maxWeight = 15f, TruckType = Model.TruckType.Single },
//new Weight() { BridgeId = 18, maxWeight = 20f, TruckType = Model.TruckType.Double },
//new Weight() { BridgeId = 19, maxWeight = 20f, TruckType = Model.TruckType.Straight },
//new Weight() { BridgeId = 19, maxWeight = 20f, TruckType = Model.TruckType.Single },
//new Weight() { BridgeId = 19, maxWeight = 20f, TruckType = Model.TruckType.Double },
new Weight() { BridgeId = 1, maxWeight = 3f, TruckType = Model.TruckType.Straight },
new Weight() { BridgeId = 1, maxWeight = 3f, TruckType = Model.TruckType.Single },
new Weight() { BridgeId = 1, maxWeight = 3f, TruckType = Model.TruckType.Double },
new Weight() { BridgeId = 2, maxWeight = 15f, TruckType = Model.TruckType.Straight },
new Weight() { BridgeId = 2, maxWeight = 15f, TruckType = Model.TruckType.Single },
new Weight() { BridgeId = 2, maxWeight = 15f, TruckType = Model.TruckType.Double },
new Weight() { BridgeId = 3, maxWeight = 20f, TruckType = Model.TruckType.Straight },
new Weight() { BridgeId = 3, maxWeight = 20f, TruckType = Model.TruckType.Single },
new Weight() { BridgeId = 3, maxWeight = 20f, TruckType = Model.TruckType.Double },
new Weight() { BridgeId = 4, maxWeight = 20f, TruckType = Model.TruckType.Straight },
new Weight() { BridgeId = 4, maxWeight = 20f, TruckType = Model.TruckType.Single },
new Weight() { BridgeId = 4, maxWeight = 20f, TruckType = Model.TruckType.Double },
new Weight() { BridgeId = 5, maxWeight = 32f, TruckType = Model.TruckType.Straight },
new Weight() { BridgeId = 5, maxWeight = 32f, TruckType = Model.TruckType.Single },
new Weight() { BridgeId = 5, maxWeight = 32f, TruckType = Model.TruckType.Double },
new Weight() { BridgeId = 6, maxWeight = 15f, TruckType = Model.TruckType.Straight },
new Weight() { BridgeId = 6, maxWeight = 15f, TruckType = Model.TruckType.Single },
new Weight() { BridgeId = 6, maxWeight = 15f, TruckType = Model.TruckType.Double }
);
}
}
}
<file_sep>@model CDLRouteHelper.Models.RegisterModel
@{
ViewBag.Title = "Register";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<fieldset>
<legend>Registration Form</legend>
<div class="col-md-6 row" style="background-color: #f9f9f9; border: solid; border-color: #f3f3f3">
<div class="page-header">
<h1>Register <small>Create a new account. </small></h1>
</div>
<div style="margin-top: 20px" class="well">
<div>
@Html.ValidationMessageFor(m => m.UserName)
</div>
<div>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
</div>
</div>
<div class="well">
<div>
@Html.ValidationMessageFor(m => m.Password)
</div>
<div>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
</div>
</div>
<div class="well">
<div>
@Html.ValidationMessageFor(m => m.ConfirmPassword)
</div>
<div>
@Html.LabelFor(m => m.ConfirmPassword)
@Html.PasswordFor(m => m.ConfirmPassword)
</div>
</div>
<div style="margin-bottom: 20px; text-align: center">
<button class='zocial lkdto' type="submit" value="Register" title="Register a new account">Register </button>
</div>
</div>
</fieldset>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CDLRouteHelper.Models
{
public class LocationViewModel
{
public float Latitude { get; set; }
public float Longitude { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CDLRouteHelper.Adapters.Interface
{
interface IUserAdapter
{
UserData GetUserDataFromUserId(int userId);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Device.Location;
namespace CDLRouteHelper.Data.Model
{
public class Bridge
{
[Key]
public int BridgeId { get; set; }
public Guid Guid { get; set; }
// Height and Weight Info
public float? Height { get; set; }
// A bridge can have many weights -- Straight Truck, Single Trailer, Double Trailer
//public float Weight { get; set; } Use Weight table
// Additional Info
public DateTime LastUpdated { get; set; }
public int NumTimesReported { get; set; }
public string Comment { get; set; }
// Location
// public GeoCoordinate GeoCoordinate { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public string Address1 { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public int StateId { get; set; }
public virtual State State { get; set; }
public virtual List<Weight> Weights { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace CDLRouteHelper.Services
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "BridgeService" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select BridgeService.svc or BridgeService.svc.cs at the Solution Explorer and start debugging.
public class BridgeService : IBridgeService
{
public List<Models.Service.BridgeServiceModel> List()
{
List<Models.Service.BridgeServiceModel> bsml = new List<Models.Service.BridgeServiceModel>();
//bsml.Add(new Models.Service.BridgeServiceModel() {Latitude=39.12211f, Longitude = -105.22f, heightRestriction =13.5f,
// weightStraightTruck =25, weightSingleTrailer=28, weightDoubleTrailer=30} );
Adapters.Service.ServiceBridge adapter = new Adapters.Service.ServiceBridge();
return bsml = adapter.GetListBridgeServiceModel();
}
public List<Models.Service.BridgeServiceModel> ListByDistanceFrom(double latitude, double longitude, float distance)
{
List<Models.Service.BridgeServiceModel> bsml = new List<Models.Service.BridgeServiceModel>();
Adapters.Service.ServiceBridge adapter = new Adapters.Service.ServiceBridge();
return adapter.GetListByDistanceFrom(latitude, longitude, distance);
}
}
}
<file_sep>@{
ViewBag.Title = "OpenRoad Route Planner";
}
@section featured {
<section>
<div class="content-wrapper" style="border-radius: 10px">
<div style="padding-top: 20px; margin-top: 20px">
<br />
<h1>@ViewBag.Title.</h1>
<h3>The site features <mark>routing information, maps, and forums</mark> to help you avoid routes with weight and/or height restrictions.
If you have any questions please check
<a href="http://forums.asp.net/1146.aspx/1?MVC" title="CDL Route Planner Forums">our forums</a>.
<br />
</h3>
</div>
<div style="background-color: white; text-align: center">
<h2 style="text-align: center">Plan Your Route </h2>
</div>
</div>
</section>
<div class="row" style="margin-left: 40px; margin-top: 40px">
<div class="col-md-8">
<div class="row">
<div class="col-md-4">
<div class="thumbnail">
<img src="~/Images/bridge_posted_weight.jpg" style="width: 150px; height: 150px; margin-top: 20px" alt="...">
<div class="caption">
<h3 style="text-align: center">Bridges by City </h3>
<h5 style="text-align: center">Using Truck Information</h5>
<div style="text-align: center"><a href='@Url.Action("Index", "Restricted")' class="btn btn-danger">Find</a></div>
</div>
</div>
</div>
<div class="col-md-4" style="border-radius: 10px;">
<div class="thumbnail">
<img src="~/Images/bridge_low_clearance.jpg" style="width: 150px; height: 150px; margin-top: 20px" />
<div class="caption">
<h3 style="text-align: center">Bridges Nearby</h3>
<h5 style="text-align: center">Locate All Bridges Close By</h5>
<div style="text-align: center"><a href='@Url.Action("Nearby", "Restricted")' class="btn btn-danger">Find</a></div>
</div>
</div>
</div>
<div class="col-md-4" style="border-radius: 10px;">
<div class="thumbnail">
<img src="~/Images/HuronRiverBridge.jpg" style="width: 150px; height: 150px; margin-top: 20px" />
<div class="caption">
<h3 style="text-align: center">Add Bridge</h3>
<h5 style="text-align: center">Enter Bridge Information</h5>
<div style="text-align: center"><a href='@Url.Action("Create", "Restricted")' class="btn btn-danger">Submit</a></div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="content-wrapper well" style="border-radius: 10px; margin-right: 40px">
<h3>Getting Started:</h3>
<ol class="round">
<li class="one">
<h5>OpenRoad Route Planner lets you search for posted bridges with height and weight restrictions that other commercial vehicle
drivers have encountered in the past. Please create a new (free) user account in order to start using the site.
</h5>
</li>
</ol>
</div>
</div>
</div>
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CDLRouteHelper.Adapters.Interface;
using CDLRouteHelper.Data;
using CDLRouteHelper.Adapters.Data;
namespace CDLRouteHelper.Adapters.Data
{
public class UserAdapter : IUserAdapter
{
public UserData GetUserDataFromUserId(int userId)
{
CDLContext db = new CDLContext();
var user = db.User
.First(u => u.UserId == userId);
UserData result = new UserData();
result.Email = user.Email;
result.FirstName = user.FirstName;
result.LastName = user.LastName;
result.UserId = user.UserId;
result.Username = user.Username;
result.Roles = db.UserRole
.Where(userRole => userRole.UserId == userId)
.Select(userRole => userRole.Role.Name)
.ToArray();
return result;
}
}
}
|
eb93b7ebaed6d6aa9076afa013b85402281c0ff5
|
[
"HTML+Razor",
"C#"
] | 41 |
HTML+Razor
|
jdsv650/RouteHelper
|
542c78a2f5befcf9c9f39b8d3aa54380402604b6
|
941ba8aea508725238cb235b43ecc573577d50ab
|
refs/heads/main
|
<repo_name>hossam-khalaf/Testing<file_sep>/app.js
document.createElement('div', 'heeeeeeeey');
|
d80c9b69d0a5c96708db245146b6ba4d11a07ec1
|
[
"JavaScript"
] | 1 |
JavaScript
|
hossam-khalaf/Testing
|
d715d589a12c8014c29e0b4ded0386d1724e6949
|
5274865982e87d058545fd3872d3dce4a415aab0
|
refs/heads/master
|
<repo_name>xwlee9/Face_recognition<file_sep>/Exercises/GettingStrated/readme.txt
This folder contains documents describing how to install and use python. For users of R there is a file
containing a link to online resources.
Note: the documents have been copied from other courses. Data sets mentioned in the documents are not related to the exercises of this course.<file_sep>/Exercises/GettingStrated/test_reader.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 28 22:39:40 2018
@author: mika
This is a simple example where we read the images as a DataFrame using
get_croppedyale_as_df() and then select some rows of the DataFrame based
on person 'names' or lighting conditions.
"""
import read_yale
images, resolution = read_yale.get_croppedyale_as_df()
# The data frame uses a MultiIndex to store the person 'names' and lighting
# conditions. Here we briefly demonstrate using the data frame.
# Get the names of the persons
row_persons = images.index.get_level_values('person')
# Get all images of 'yaleB10'
rows_include = (row_persons == 'yaleB10')
pics_B10 = images[rows_include]
print(pics_B10) # there are over 30 000 columns so results are not pretty..
# Get all images under conditions "P00A-130E+20"
row_conds = images.index.get_level_values('pic_name')
rows_include = (row_conds == 'P00A-130E+20')
pics_2 = images[rows_include]
print(pics_2)
<file_sep>/keras_CNN.py
import cv2
import numpy as np
import logging
import os
import shutil
from matplotlib import cm
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense, Activation, Convolution2D, MaxPooling2D, Flatten, Dropout
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, History, Callback
from keras.utils import np_utils
import pandas as pd
#from ggplot import *
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
class History(Callback):
def on_train_begin(self, logs={}):
self.losses = {'batch':[], 'epoch':[]}
self.accuracy = {'batch':[], 'epoch':[]}
self.val_loss = {'batch':[], 'epoch':[]}
self.val_acc = {'batch':[], 'epoch':[]}
def on_batch_end(self, batch, logs={}):
self.losses['batch'].append(logs.get('loss'))
self.accuracy['batch'].append(logs.get('acc'))
self.val_loss['batch'].append(logs.get('val_loss'))
self.val_acc['batch'].append(logs.get('val_acc'))
def on_epoch_end(self, batch, logs={}):
self.losses['epoch'].append(logs.get('loss'))
self.accuracy['epoch'].append(logs.get('acc'))
self.val_loss['epoch'].append(logs.get('val_loss'))
self.val_acc['epoch'].append(logs.get('val_acc'))
def loss_plot(self, loss_type):
iters = range(len(self.losses[loss_type]))
plt.figure(1)
plt.subplot(211)
# loss
plt.plot(iters, self.losses[loss_type], 'g', label='Training loss')
# if loss_type == 'epoch':
# # val_acc
# plt.plot(iters, self.val_acc[loss_type], 'b', label='val acc')
# # val_loss
plt.plot(iters, self.val_loss[loss_type], 'k', label='Test loss')
plt.xlabel(loss_type)
plt.ylabel('Loss')
plt.legend(loc="upper right")
plt.subplot(212)
# acc
plt.plot(iters, self.accuracy[loss_type], 'r', label='Training: Acc')
plt.plot(iters, self.val_acc[loss_type], 'b', label='Test acc')
plt.xlabel(loss_type)
plt.ylabel('Accuracy %')
plt.grid(True)
plt.legend(loc="upper right")
plt.show()
def read_images_from_single_face_profile(face_profile, face_profile_name_index, dim = (48, 48)):
# face_profile: ../face_profiles/yaleBnn
"""
Reads all the images from one specified face profile into ndarrays
Parameters
----------
face_profile: string
The directory path of a specified face profile
face_profile_name_index: int
The name corresponding to the face profile is encoded in its index
dim: tuple = (int, int)
The new dimensions of the images to resize to
Returns
-------
X_data : numpy array, shape = (number_of_faces_in_one_face_profile, face_pixel_width * face_pixel_height)
A face data array contains the face image pixel rgb values of all the images in the specified face profile
Y_data : numpy array, shape = (number_of_images_in_face_profiles, 1)
A face_profile_index data array contains the index of the face profile name of the specified face profile directory
"""
X_data = np.array([])
index = 0
for the_file in os.listdir(face_profile): #face_profile: ../face_profiles/yaleBnn
file_path = os.path.join(face_profile, the_file)
if file_path.endswith(".png") or file_path.endswith(".jpg") or file_path.endswith(".jpeg") or file_path.endswith(".pgm"):
img = cv2.imread(file_path, 0)
img = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
img_data = img.ravel()
X_data = img_data if not X_data.shape[0] else np.vstack((X_data, img_data))
index += 1
if index == 0 :
shutil.rmtree(face_profile)
logging.error("\nThere exists face profiles without images")
Y_data = np.empty(index, dtype = int) #number of pictures in one yaleB file
Y_data.fill(face_profile_name_index) # Y_data: [face_profile_name_index,......,face_profile_name_index ]
# [i,i,i,i,..........................................i,i,i]
return X_data, Y_data # X_data: array shape=(number of pictures, pixels of picture)
def load_training_data(face_profile_directory): #face_profile_directory ../face_profiles/
"""
Loads all the images from the face profile directory into ndarrays
Parameters
----------
face_profile_directory: string
The directory path of the specified face profile directory
face_profile_names: list
The index corresponding to the names corresponding to the face profile directory
Returns
-------
X_data : numpy array, shape = (number_of_faces_in_face_profiles, face_pixel_width * face_pixel_height)
A face data array contains the face image pixel rgb values of all face_profiles
Y_data : numpy array, shape = (number_of_face_profiles, 1)
A face_profile_index data array contains the indexs of all the face profile names
"""
# Get a the list of folder names in face_profile as the profile names
face_profile_names = [d for d in os.listdir(face_profile_directory) if "." not in str(d)]
# face_profile_names :yaleB01,yaleB02......
if len(face_profile_names) < 2:
logging.error("\nFace profile contains too little profiles (At least 2 profiles are needed)")
exit()
first_data = str(face_profile_names[0])
first_data_path = os.path.join(face_profile_directory, first_data) # first_data_path:../face_profiles/yaleB01
X1, y1 = read_images_from_single_face_profile(first_data_path, 0)
X_data = X1
Y_data = y1
print ("Loading Database: ")
print (0, " ",X1.shape[0]," images are loaded from:", first_data_path)
for i in range(1, len(face_profile_names)):
directory_name = str(face_profile_names[i])
directory_path = os.path.join(face_profile_directory, directory_name)
tempX, tempY = read_images_from_single_face_profile(directory_path, i)
X_data = np.concatenate((X_data, tempX), axis=0)
Y_data = np.append(Y_data, tempY)
print (i, " ",tempX.shape[0]," images are loaded from:", directory_path)
return X_data, Y_data, face_profile_names # X_data: (2452,2500), Y_data: (2452,)
# Load training data from face_profiles/
face_profile_data , face_profile_name_index , face_profile_names = load_training_data("./face_profiles/")
print("\n", face_profile_name_index.shape[0], " samples from ", len(face_profile_names), " people are loaded")
x = face_profile_data
y = face_profile_name_index
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
print(x_train.shape,x_test.shape, y_train.shape, y_test.shape)
#(1961, 2304) (491, 2304) (1961,) (491,)
# x_train=x_train.astype('float32')
# x_test=x_test.astype('float32')
# x_train //= 1.
# x_test //= 1.
# x_train= x_train.reshape(x_train.shape[0], 1, cmath.sqrt(x_train.shape[1]), cmath.sqrt(x_train.shape[1]))
# x_test=x_test.reshape(x_test.shape[0], 1, cmath.sqrt(x_test.shape[1], cmath.sqrt(x_test.shape[1])))
# x_train= x_train.reshape(x_train.shape[0], 1, 48, 48)/255
# x_test=x_test.reshape(x_test.shape[0], 1, 48, 48)/255
x_train= x_train.reshape(x_train.shape[0], 48, 48, 1)/255
x_test=x_test.reshape(x_test.shape[0], 48, 48, 1)/255
# y_train = np_utils.to_categorical(y_train,)
# y_test = np_utils.to_categorical(y_test,)
print(x_train.shape, x_test.shape, y_train.shape, y_test.shape)
# (1961, 1, 48, 48) (491, 1, 48, 48)
#将标签转为one_hot类型
# def label_to_one_hot(labels_dense, num_classes=38):
# num_labels = labels_dense.shape[0]
# index_offset = np.arange(num_labels) * num_classes
# labels_one_hot = np.zeros((num_labels, num_classes))
# labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
# return labels_one_hot
#
# y_train=label_to_one_hot(y_train,38)
# y_test=label_to_one_hot(y_test,38)
batch_size = 128
epochs = 12
nb_classes = 38
input_shape=(48, 48, 1)
# input image dimensions
img_rows, img_cols = 48, 48
# number of convolutional filters to use
nb_filters1 = 16
nb_filters2 = 36
# size of pooling area for max pooling
pool_size = (2, 2)
strides=(2, 2)
# convolution kernel size
kernel_size = (5, 5)
model=Sequential()
model.add(Convolution2D(nb_filters1, (kernel_size[0], kernel_size[1]),
padding='same',
input_shape=(48, 48, 1))) # 卷积层1 output(16,48,48)
model.add(Activation('relu')) # 激活层
model.add(MaxPooling2D(pool_size=pool_size, strides=strides, padding='same')) # pool 1 output(16,24,24)
model.add(Convolution2D(nb_filters2, (kernel_size[0], kernel_size[1]), padding='same')) # 卷积层2 output(36, 24, 24)
model.add(Activation('relu')) # 激活层
model.add(MaxPooling2D(pool_size=pool_size,strides=strides, padding='same')) # pool 2 output(36,12,12)
model.add(Dropout(0.5)) # 神经元随机失活
model.add(Flatten()) # 拉成一维数据 36*12*12=5184
model.add(Dense(512)) # 全连接层1
model.add(Activation('relu')) # 激活层
model.add(Dense(nb_classes)) # 全连接层2
model.add(Activation('softmax')) # Softmax评分
# Another way to define your optimizer
adam = Adam(lr=1e-4)
# We add metrics to get more results you want to see
model.compile(optimizer=adam,
#loss='categorical_crossentropy',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
print('Training ------------')
model.summary()
# Another way to train the model
#model.fit(x_train, y_train, epochs=38, batch_size=400)
history = History()
#model.optimizer.lr.set_value(0.0005)
model.fit(x_train, y_train, batch_size=300, epochs=100, validation_data=(x_test, y_test), callbacks=[history])
print('\nTesting ------------')
# Evaluate the model with the metrics we defined earlier
loss, accuracy = model.evaluate(x_test, y_test,)
print('\ntest loss: ', loss)
print('\ntest accuracy: ', accuracy)
#y_pred=model.predict(x_test)
y_pred=model.predict_classes(x_test)
confusion_mat = confusion_matrix(y_test, y_pred)
print("\nconfusion matrix=")
print(confusion_mat)
print("\n confusion matrix shape=")
print(confusion_mat.shape)
norm_conf = []
for i in confusion_mat:
a=0
tmp_arr= []
a=sum(i, 0)
for j in i:
tmp_arr.append(float(j)/float(a))
norm_conf.append(tmp_arr)
plt.clf()
fig=plt.figure()
ax=fig.add_subplot(111)
res = ax.imshow(np.array(norm_conf), cmap=cm.jet, interpolation='nearest')
for i, cas in enumerate(confusion_mat):
for j, c in enumerate(cas):
if c > 0:
plt.text(j - .5, i + .5, c, fontsize=6)
# df = pd.DataFrame(history.history)
# df.ix[:, 'Epoch'] = np.arange(1, len(history.history['acc'])+1, 1)
# p=pd.melt(df.ix[0:100, ['Iter','acc', 'val_acc']], id_vars='Iter')
# # value_name=('Iter', 'value', color='variable')
# print(p)
history.loss_plot('epoch')
|
a78860344ccdb97552d397c599ab328054705cfd
|
[
"Text",
"Python"
] | 3 |
Text
|
xwlee9/Face_recognition
|
5f04af79c92167a49e7125a1b531743c109f0306
|
a00acc39dc15db4cd2dd43d74ea1d6dcfe82779c
|
refs/heads/master
|
<file_sep>const express = require('express')
const app = express()
app.get('/hi', (req, res) => {
res.send('hello from happy-land!\nyou said: ' + req.query.command.split(' ').pop())
})
app.listen(process.env.PORT || 80)
|
6982265eb747e847fd7972fc4fb976051a92e43e
|
[
"JavaScript"
] | 1 |
JavaScript
|
platy11/slack-commands
|
f69c540c2f7cd0f66482e8ee4b408e0db7ff0f9a
|
3f8629db4018b6eb4f9360bf3a2545c25b5c1e2f
|
refs/heads/master
|
<repo_name>5u4/nginx-docker-deployment<file_sep>/README.md
# Nginx Docker Deployment
## Description
Manage multiple docker applications using nginx reverse proxy in one server.
## Set up a fake server
```bash
docker build -t fake-server .
docker run --privileged -it --name fake-server -p 80:80 -p 443:443 -d fake-server
```
An example node microservice and nginx config are copied to `/opt` in the container.
## Create nginx and microservices
1. Shell into fake server
```bash
docker exec -it fake-server bash
```
**NOTE:** The command in fake server are prefixed `$` for clearity.
2. Start docker
```bash
$ service docker start
```
3. Start nginx
```bash
$ docker run -it --name nginx -p 80:80 -d \
-v /opt/nginx/conf.d:/etc/nginx/conf.d \
nginx:alpine
```
The nginx configs are mounted at `/opt/nginx/conf.d`
**NOTE:** Nginx fails now since there is no `status` upstream.
4. Build and start the status microservice
```bash
$ docker build -t status /opt/microservices/status
$ docker run --name status -d status
```
5. Connect nginx and status microservice
```bash
$ docker network create nginx_status
$ docker network connect nginx_status nginx
$ docker network connect nginx_status status
```
6. Restart nginx
```bash
$ docker restart nginx
```
## Test
Ping the fake server outside the container
```bash
./ping.sh "fake-server"
./ping.sh "status.fake-server"
```
It does not work when using a browser since the fake server is hosted locally.
But you can add lines to `/etc/hosts` to tell browser `fake-server` is in local.
```
127.0.0.1 fake-server
127.0.0.1 status.fake-server
```
## Create self signed certificate
1. Create SSL certficate
```bash
$ openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout /etc/ssl/private/fake-server.key \
-out /etc/ssl/certs/fake-server.crt
```
2. Create the self signed nginx
```bash
$ docker rm nginx -f
$ docker run -it --name nginx -p 80:80 -p 443:443 -d \
--network nginx_status \
-v /opt/self-signed-nginx/conf.d:/etc/nginx/conf.d \
-v /etc/ssl/certs/fake-server.crt:/etc/ssl/certs/fake-server.crt \
-v /etc/ssl/private/fake-server.key:/etc/ssl/private/fake-server.key \
nginx:alpine
```
Now all the http requests will be redirect to https.
To create a verified certificate, see [nginx-certbot](https://github.com/senhungwong/nginx-certbot).
<file_sep>/microservices/status/Dockerfile
FROM node:alpine
WORKDIR /opt/server
COPY server.js /opt/server
CMD node server.js
<file_sep>/ping.sh
server=${1:-"fake-server"}
curl -H "Host: $server" localhost
<file_sep>/Dockerfile
FROM ubuntu
WORKDIR /opt
COPY ./microservices /opt/microservices
COPY ./nginx /opt/nginx
COPY ./self-signed-nginx /opt/self-signed-nginx
RUN apt-get update
RUN apt-get install -y \
apt-transport-https \
ca-certificates \
curl \
gnupg2 \
software-properties-common
RUN curl -fsSL https://download.docker.com/linux/debian/gpg | apt-key add -
RUN add-apt-repository \
"deb [arch=amd64] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) \
stable"
RUN apt-get update && apt-get install -y docker-ce docker-ce-cli containerd.io
|
051b465445e34c3a58161fd1c1deab3032fdacc8
|
[
"Markdown",
"Shell",
"Dockerfile"
] | 4 |
Markdown
|
5u4/nginx-docker-deployment
|
9df485f786bd703502646b22a15d8cee2b4906bb
|
fd094197c9392b257a548a2e98412833eaac76c6
|
refs/heads/main
|
<repo_name>SimpleCoding5663/Responsive-Card-Section<file_sep>/css_card/script.js
Array.from(document.querySelectorAll(".navigation-button")).forEach(item => {
item.onclick = () => {
item.parentElement.parentElement.classList.toggle("active");
};
})<file_sep>/README.md
# Responsive-Card-Section
|
b12bdb86ceb6a091aa54b84ee967f5acf3d8d7d3
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
SimpleCoding5663/Responsive-Card-Section
|
64a774d10c7ef147c3f5bacd32b1bf768ad473c1
|
d5a1696b60a39e97a5eb266f808522ace923eaec
|
refs/heads/master
|
<repo_name>jimnanney/onstar-client<file_sep>/spec/onstar/client_spec.rb
require 'spec_helper'
describe Onstar do
it 'should have a version number' do
Onstar::VERSION.should_not be_nil
end
context "with oauth endpoint and valid credentials", :vcr do
let(:api_key) { ENV['GM_API_KEY'] }
let(:api_secret) { ENV['GM_SECRET_KEY'] }
let(:client) { Onstar::Client.new(api_key, api_secret) }
it "should recieve oauth token" do
client.connect
expect(client.token).not_to be_nil
end
it "should throw no errors"
it "should be able to access data from endpoint?"
context "with subscriber account" do
it "should retrieve telemetry data"
end
end
end
<file_sep>/spec/spec_helper.rb
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'onstar'
require 'onstar/version'
#Dir[File.expand_path('../support/*/.rb', __FILE__)].each{|f| require f}
require 'rspec'
require 'vcr'
require 'webmock/rspec'
WebMock.disable_net_connect!
VCR.configure do |config|
config.hook_into :webmock
config.cassette_library_dir = 'spec/fixtures/vcr_cassettes'
config.configure_rspec_metadata!
config.preserve_exact_body_bytes { true }
config.default_cassette_options = {
:re_record_interval => 60*60*24*180
}
config.allow_http_connections_when_no_cassette = false
end
RSpec.configure do |config|
config.treat_symbols_as_metadata_keys_with_true_values = true
end
<file_sep>/notes.txt
The token end point URL is https://developer.gm.com/oauth/access_token
The client application needs to request and obtain the token from this
endpoint by adding the following parameters using the
“application/x-www-form-urlencoded” format in the HTTP request body:
grant_type – REQUIRED, must be set to “client_credentials”
Confidential clients or other clients issued client credentials MUST
authenticate with the authorization server. Clients in possession of a client
password must use the HTTP Basic authentication scheme as defined in [RFC2617]
to authenticate with the authorization server. The client identifier is used
as the username, and the client password is used as the password.
i.e. Authorization:BasicczZCaGRSa3F0MzpnWDFmQmF0M2JW
The client can choose to receive the response in either JSON, or XML by
specifying the Accept HTTP
header.
https://github.com/intridea/oauth2
oauth2 requires headers to be set in the client.connection.headers hash
<file_sep>/Gemfile
source 'https://rubygems.org'
# Specify your gem's dependencies in onstar-client.gemspec
gemspec
<file_sep>/spec/support/vcr.rb
require 'vcr'
require 'webmock/rspec'
VCR.configure do |config|
config.hook_into :webmock
config.cassette_library_dir = 'spec/fixtures/vcr_cassettes'
config.configure_rspec_metadata!
config.preserve_exact_body_bytes { true }
config.default_cassette_options = {
:re_record_interval => 6.months
}
config.allow_http_connections_when_no_cassette = false
end
<file_sep>/lib/onstar/client.rb
require 'onstar/version'
require 'oauth2'
require 'rest-client'
module Onstar
class Client
attr_accessor :secret, :api_key, :token
def initialize(api_key, secret)
@secret = secret
@api_key = api_key
end
def connect
client = OAuth2::Client.new(@api_key, @secret,
:site => "https://developer.gm.com/",
:token_url => '/api/v1/oauth/access_token')
client.connection.headers['Accept'] = 'application/json'
@token = client.client_credentials.get_token(:headers => {'Accept' => 'application/json'})
end
def get_telemtry(vehicle_id)
# /api/v1/account/vehicles/{vin}/telemetry
# https://developer.gm.com/api/v1/account/vehicles/1G6DH5E53C0000003/telemetry?begintimestamp= 2012-06-20T14:11:11&endtimestamp=2012-06-20T15:11:11&offset=0&limit=2
end
end
end
<file_sep>/lib/onstar.rb
require 'onstar/client'
<file_sep>/README.md
# Onstar::Client
Onstar Client is a client implementation of the GM remote API. In order to use it you will need an Application API Key and Secret Key.
## Installation
Add this line to your application's Gemfile:
gem 'onstar-client'
And then execute:
$ bundle
Or install it yourself as:
$ gem install onstar-client
## Usage
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
|
90f8082d1d548db2f5b74e33212177739a856724
|
[
"Markdown",
"Text",
"Ruby"
] | 8 |
Markdown
|
jimnanney/onstar-client
|
234a9d3f59b6032db053c176b3f842a14a6ff13c
|
2357f7cfed296964060c0333adfb8fd6f7236373
|
refs/heads/master
|
<file_sep>LogicBot
========
A IRC bot that knows logic!
## Install
* Clone it `git clone https://github.com/cameronbwhite/LogicBot.git`
* Install ConcurBot https://github.com/MrRacoon/ConcurBot
* Install it `cabal install --user`
* run it `LogicBot` assuming `~/.cabal/bin/` is in your `PATH`
## Run it
The bot comes with a handly command line which will configure it to do whatever you need.
```
Usage: [OPTION...]
-n NICK --nick=NICK Nick of the Bot
-o OWNER --owner=OWNER Nick of the owner of the bot
-s SERVER --server=SERVER The server the bot should connect too
-p PORT --port=PORT The port the bot should connect too
-c CHANNELS --channels=CHANNELS The Channels the bot should connect too
```
### Example
```sh
LogicBot -n LogicBot -o cam -s irc.cat.pdx.edu -p 6667 -c '#botville #cschat #RacoonCity'
```
## Credits
Much thanks to <NAME> (aka @MrRacoon) for his awesome IRC framework.
<file_sep>> module Main where
> import ConcurBot.BotMaker
> import ConcurBot.Messaging
> import System.Environment (getArgs, getProgName)
> import System.Console.GetOpt
> import System.Cron
> import WeberLogic.Parser
> import WeberLogic.Actions
> main :: IO ((), BotState)
> main = do
> options <- parseArgs
> makeBot $ BotConfig {
> bot_nick = opt_nick options
> , bot_owner = opt_owner options
> , bot_server = opt_server options
> , bot_port = opt_port options
> , bot_chans = opt_chans options
> , bot_listeners = (3, ircParser)
> , bot_socks = []
> , bot_pipes = []
> , bot_schedules = []}
> >>= startBot
> data Options = Options {
> opt_nick :: String
> , opt_owner :: String
> , opt_server :: String
> , opt_port :: Integer
> , opt_chans :: [String]
> } deriving Show
> defaultOptions = Options {
> opt_nick = "LogicBot"
> , opt_owner = ""
> , opt_server = ""
> , opt_port = 6667
> , opt_chans = []
> }
> options :: [OptDescr (Options -> Options)]
> options =
> [ Option ['n'] ["nick"]
> (ReqArg (\x opts -> opts { opt_nick = x }) "NICK")
> "Nick of the Bot"
> , Option ['o'] ["owner"]
> (ReqArg (\x opts -> opts { opt_owner = x }) "OWNER")
> "Nick of the owner of the bot"
> , Option ['s'] ["server"]
> (ReqArg (\x opts -> opts { opt_server = x }) "SERVER")
> "The server the bot should connect too"
> , Option ['p'] ["port"]
> (ReqArg (\x opts -> opts { opt_port = (read x) }) "PORT")
> "The port the bot should connect too"
> , Option ['c'] ["channels"]
> (ReqArg (\x opts -> opts { opt_chans = (words x) }) "CHANNELS")
> "The Channels the bot should connect too"
> ]
> parseArgs :: IO Options
> parseArgs = do
> argv <- getArgs
> progName <- getProgName
> case getOpt RequireOrder options argv of
> (opts, [], []) -> return (foldl (flip id) defaultOptions opts)
> (_, _, errs) -> ioError (userError (concat errs ++ helpMessage))
> where
> header = "Usage: " ++ "" ++ " [OPTION...]"
> helpMessage = usageInfo header options
> ircParser :: [Char] -> [Action]
> ircParser line = let p = parse line
> in case p of
> (PRIVMSG n u _ c m) ->
> if n == "cam" && u == "cawhite"
> then adminParser m c
> else commandParser m c
> (PING s) -> [PongBack s]
> l -> [Line $ show l]
> adminParser :: String -> String -> [Action]
> adminParser str c = case words str of
> ("PING":serv) -> [PongBack $ unwords serv, Line "Returned a PING Response"]
> ("nick":nick:[]) -> [ChangeNick nick, Line ("Changing Nic to " ++ nick)]
> ("join":chan:[]) -> [JoinChannel chan, Line ("Joining Channel " ++ chan)]
> ("join":chan:xs) -> [JoinPrivateChannel (head xs) chan, Line ("Joining Private channel "++ chan)]
> ("die":"poopShoe":_) -> [Line "Returned a PING Response", TERMINATE]
> _ -> commandParser str c
> commandParser :: String -> String -> [Action]
> commandParser str chan = case words str of
> ("LogicBot:":"truthtable":rest) ->
> case readExp $ unwords rest of
> Right val -> map (\x -> MessageIRC chan x) $ truthTableStrs val
> Left val -> []
> ("LogicBot:":"toNand":rest) ->
> case readExp $ unwords rest of
> Right val -> [MessageIRC chan $ show $ toNand val]
> Left val -> []
> ("LogicBot:":"toNor":rest) ->
> case readExp $ unwords rest of
> Right val -> [MessageIRC chan $ show $ toNor val]
> Left val -> []
> ("LogicBot:":"isArgValid":rest) ->
> case readArg $ unwords rest of
> Right exps ->
> let exps' = take (length exps - 1) exps ++ [Not $ last exps]
> in [MessageIRC chan $ show $ not $ isConsistent exps']
> Left val -> []
> ("LogicBot:":"help":"commands":rest) ->
> map (MessageIRC chan) helpMessageCommands
> ("LogicBot:":"help":"expressions":rest) ->
> map (MessageIRC chan) helpMessageExpessions
> ("LogicBot:":"help":"arguments":rest) ->
> map (MessageIRC chan) helpMessageArguments
> ("LogicBot:":"help":rest) ->
> map (MessageIRC chan) helpMessage
> _ -> []
> helpMessage = [
> "Type one of the following to get more help"
> ,"help commands"
> ,"help expressions"
> ,"help arguments"]
> helpMessageCommands = [
> "truthTable <Logical Expression>"
> ,"toNand <Logical Expression>"
> ,"toNor <Logical Expression>"
> ,"isArgValid <Logical Argument>"]
> helpMessageExpessions = [
> "Logical Expressions are composed of Predicates and connectives"
> ,"Predicates: Upper case letters followed by one or more Name or Variable"
> ,"Names: Any lower case character [a-t]"
> ,"Varible: Any lower case character [u-z]"
> ,"Connectives: ~,&,+,->,<->,|,/ = Not,And,Or,Implies,Iff,Nand,Nor"
> ,"Example: Pxa&A->~Qa+Bab"]
> helpMessageArguments = [
> "Logical Arguments are a series of logical expressions seperated by ',' and '|-'"
> ,"There must be exactly one '|-' in the argument and it must come before the last expression"
> ,"Example: |- A&B"
> ,"Example: C->D |- A&B"
> ,"Example: ~Aa&Bx, C&D, Aay->~Bya |- A&B"]
|
eb9ac27292d553e8887617566e252c49063cee4b
|
[
"Markdown",
"Literate Haskell"
] | 2 |
Markdown
|
cameronbwhite/LogicBot
|
63e47595f95ef5334b71f103a8a94d2df15f1c21
|
479b95666c92ddd87534ec9c9bb9c80c8f8dba85
|
refs/heads/master
|
<repo_name>ParvinSha/Assignment2<file_sep>/Program.cs
using System;
using System.Collections.Generic;
namespace Assignment2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, you see the main menu, by selecting below numbers you will navigate to related functions:");
do
{
int userInput = Util.AskForInt("\n 0: Exit the program"
+ "\n 1: Get ticket price"
+ "\n 2: Print your entered word 10 times"
+ "\n 3: Print the third word in your entered sentence");
switch (userInput)
{
case 0:
Environment.Exit(0);
break;
case 1:
userInput = Util.AskForInt("\n 0: return to main menu"
+ "\n 1:Individual Price"
+ "\n 2: Company Price");
switch (userInput)
{
case 0:
break;
case 1:
userInput = Util.AskForInt("Enter your age:");
calculateIndividualPrice(userInput);
break;
case 2:
userInput = Util.AskForInt("Enter numbers of personls:");
Console.WriteLine($"\n\nTotal Ticket Price for {userInput} Personals is: {calculatePersonalsPrice(userInput)}kr");
break;
default:
break;
}
break;
case 2:
var arbitraryText = Util.AskForString("Enter an arbitray text, so it will be printed 10 times:");
RepeatTenTimes(arbitraryText);
break;
case 3:
var sentence = Util.AskForString("Enter a statement with at least 3 words:");
splitSentence(sentence);
break;
default:
break;
}
}
while (true); //Endless loop
}
private static void splitSentence(string sentence)
{
string[] sentenceList = sentence.Split(" ");
if(sentenceList.Length > 2)
Console.WriteLine($"\n The third word in the sentence you have entered is: {sentenceList[2]}");
else
Console.WriteLine("The sentence should have at least 3 words");
}
private static void RepeatTenTimes(string arbitraryText)
{
for (int i = 0; i < 10; i++)
Console.Write($"{i +1}. {arbitraryText} ");
Console.WriteLine();
}
private static int calculatePersonalsPrice(int personalNumbers)
{
// List<int> personalsTicketPrice = new List<int>();
int personalsTicketPrice = 0;
int age;
for (int i=0; i< personalNumbers; i++)
{
age = Util.AskForInt($"\n Enter Personal{i + 1} age:");
personalsTicketPrice += calculateIndividualPrice(age);
}
return personalsTicketPrice;
}
private static int calculateIndividualPrice(int age)
{
int price = -1;
if (age < 20)
{
price = 80;
Console.WriteLine("Teenagers Price: 80kr");
}
else if (age > 64)
{
price = 90;
Console.WriteLine("Pensions Price: 90kr");
}
else
{
price = 120;
Console.WriteLine("Standars Price: 120kr");
}
return price;
}
}
}
|
a99b4853a4de1b33565b9170f44fcd9478ab92c1
|
[
"C#"
] | 1 |
C#
|
ParvinSha/Assignment2
|
ffd88854268c3baf47b380ab774b8653ca6367f1
|
6359c78811a20a2d5159c64a3e88810424f6f3f8
|
refs/heads/master
|
<file_sep>#include "Shifter.h"
Shifter::Shifter(uint8_t mod,uint32_t chanF,uint32_t chanR)
{
shifter=new DoubleSolenoid(mod,chanF,chanR);
//TODO
}
Shifter::~Shifter()
{
delete shifter;
//TODO
}
void Shifter::shiftGear()
{
if(gear == low)
{
setHigh();
}
else if(gear == high)
{
setLow();
}
}
void Shifter::setHigh()
{
gear=high;
pneumatics->setVectorValues(TIME, shifter, DoubleSolenoid::kForward);
}
void Shifter::setLow()
{
gear=low;
pneumatics->setVectorValues(TIME, shifter, DoubleSolenoid::kReverse);
}
<file_sep>#include "main.h"
#include "EncodeDistance.h"
EncodeDistance::EncodeDistance(Encoder* obj)
{
myEncoder = obj;
}
EncodeDistance::~EncodeDistance()
{
}
double convertTickToDist(double distance)
{
//TODO
/* will determine the conversion through testing and taking measurements */
return 0;
}
float convertDistToTick(float distance)
{
// TODO
/* will determine the conversion through testing and taking measurements */
return 0;
}
void Start()
{
// TODO
/* will determine the conversion through testing and taking measurements */
}
double GetDistance()
{
// TODO
/* will determine the conversion through testing and taking measurements */
return 0;
}
<file_sep>#ifndef DRIVETRAIN_H
#define DRIVETRAIN_H
#include <RobotDrive.h>
class DriveTrain : public RobotDrive
{
public:
DriveTrain(uint8_t modFL,uint32_t chanFL,uint8_t modRL,uint32_t chanRL,uint8_t modFR,uint32_t chanFR,uint8_t modRR,uint32_t chanRR);
~DriveTrain();
void autoDrive(float distance);
void autoTurn(float degrees);
void stop();
};
#endif // DRIVETRAIN_H
<file_sep>#include "main.h"
#include <DigitalInput.h>
#include <Relay.h>
#include <Joystick.h>
main_robot::main_robot()
{
}
main_robot::~main_robot()
{
}
void main_robot::RobotInit()
{
driverJoy = new Joystick(1);
gunnerJoy = new Joystick(2);
pnum = new Pneumatics(1,8,1,8); // TODO Placeholder for the ports
shift = new Shifter(1,7,8);
shift->setHigh();
}
void main_robot::TeleopInit()
{
}
void main_robot::AutonomousInit()
{
}
void main_robot::TestInit()
{
}
void main_robot::DisabledInit()
{
}
void main_robot::TeleopPeriodic()
{
//float left = driverJoy->GetRawAxis(2);
//float right = driverJoy->GetRawAxis(5);
// drive->TankDrive(left, right);
}
void main_robot::AutonomousPeriodic()
{
}
void main_robot::DisabledPeriodic()
{
}
void main_robot::TestPeriodic()
{
pnum->checkPressure();
pnum->updateSolenoid();
if(gunnerJoy->GetRawButton(5))
{
if(shift->gear!=Shifter::low)
{
shift->setLow();
}
}
else if(gunnerJoy->GetRawButton(6))
{
if(shift->gear!=Shifter::high)
{
shift->setHigh();
}
}
}
START_ROBOT_CLASS(main_robot)<file_sep>#ifndef ENCODEDISTANCE_H
#define ENCODEDISTANCE_H
#include <Encoder.h>
class EncodeDistance
{
public:
EncodeDistance::EncodeDistance(Encoder*);
~EncodeDistance();
double convertTickToDist(double distance);
float convertDistToTick(float distance);
void Start();
double GetDistance();
private:
Encoder* myEncoder;
};
#endif // ENCODEDISTANCE_H
<file_sep>#include "DriveTrain.h"
#include <RobotDrive.h>
#include <Talon.h>
DriveTrain::DriveTrain(uint8_t modFL,uint32_t chanFL,
uint8_t modRL,uint32_t chanRL,
uint8_t modFR,uint32_t chanFR,
uint8_t modRR,uint32_t chanRR)
:RobotDrive(new Talon(modFL,chanFL),
new Talon(modRL,chanRL),
new Talon(modFR,chanFR),
new Talon(modRR,chanRR))
{
//TODO
}
DriveTrain::~DriveTrain()
{
}
void DriveTrain::autoDrive(float distance)
{
//TODO
}
void DriveTrain::autoTurn(float degrees)
{
//TODO
}
void DriveTrain::stop()
{
//TODO
}
<file_sep>#ifndef PORTS_H
#define PORTS_H
#include <stdint.h>
const uint32_t DRIVER_JOY_PORT = 1;
const uint32_t GUNNER_JOY_PORT = 2;
#endif
|
d459072d2931b2e6550d68168e879052058ed287
|
[
"C",
"C++"
] | 7 |
C
|
KyleTran/612-2014
|
29e89d3a60cbb807274a3ec431894dad9b04afe4
|
7beb0729c2972a2478f0da4787aaa32f28e70408
|
refs/heads/master
|
<file_sep>#!/bin/bash
echo "Hello, let me introduce myself"
NAME=Jesse
HOMETOWN=Fairbanks
MAJOR=CS
FAVORITE_HOBBY=learn
echo "My name is $NAME. I am originally from $HOMETOWN. My major is $MAJOR and in my free time I like to $FAVORITE_HOBBY"
|
888de83990bef5baa056574f7f727f3d99763f66
|
[
"Shell"
] | 1 |
Shell
|
jkells29/Cpts_224
|
cc5030415d0b8b3bfc401fefde83d360e98c7e2d
|
62de44bb8bab19d5b51c84588bcd7b47a9c4bec5
|
refs/heads/master
|
<file_sep># lighthouse-server-edition
A server wrapper around lighthouse that uses chart.js to plot site performance overtime.
<file_sep>
const lighthouse = require('lighthouse')
const chromeLauncher = require('chrome-launcher')
function launchChromeAndRunLighthouse(url, opts, config = null) {
return chromeLauncher.launch({chromeFlags: opts.chromeFlags}).then(chrome => {
opts.port = chrome.port;
return lighthouse(url, opts, config).then(results => {
// use results.lhr for the JS-consumeable output
// https://github.com/GoogleChrome/lighthouse/blob/master/typings/lhr.d.ts
// use results.report for the HTML/JSON/CSV output as a string
// use results.artifacts for the trace/screenshots/other specific case you need (rarer)
return chrome.kill().then(() => results.lhr)
})
})
}
const opts = {
chromeFlags: ['--show-paint-rects']
}
// Usage:
launchChromeAndRunLighthouse('https://www.google.com', opts).then(results => {
// Use results!
console.log('results', results)
})
|
e6fad11921656089839302f9e19ab4df4afa11a7
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
wookets/lighthouse-server-edition
|
5afff74bf060b2d2af8204be5756ba5c6cd5a8a3
|
673b7bb638c387f21ad0bca101958a73e6f08bee
|
refs/heads/master
|
<repo_name>mvanderkamp/WAMS-API<file_sep>/src/server/Connection.js
/*
* WAMS - An API for Multi-Surface Environments
*
* Author: <NAME>
* |-> Date: July/August 2018
*
* Original author: <NAME>
* Other revisions and supervision: <NAME>
*
* A Connection maintains a socket.io connection between a client and the
* server. It tracks a view associated with the client, as well as the
* associated workspace.
*/
'use strict';
const { FullStateReporter, Message, NOP } = require('../shared.js');
const symbols = Object.freeze({
attachListeners: Symbol('attachListeners'),
fullStateReport: Symbol('fullStateReport'),
});
class Connection {
constructor(index, socket, workspace) {
this.index = index;
this.socket = socket;
this.workspace = workspace;
this.view = this.workspace.spawnView();
this[symbols.attachListeners]();
this[symbols.fullStateReport]();
}
[symbols.attachListeners]() {
const listeners = {
// For the server to inform about changes to the model
[Message.ADD_ITEM]: NOP,
[Message.ADD_SHADOW]: NOP,
[Message.RM_ITEM]: NOP,
[Message.RM_SHADOW]: NOP,
[Message.UD_ITEM]: NOP,
[Message.UD_SHADOW]: NOP,
[Message.UD_VIEW]: NOP,
// Connection establishment related (disconnect, initial setup)
[Message.INITIALIZE]: NOP,
[Message.LAYOUT]: (...args) => this.layout(...args),
// User event related
[Message.CLICK]: (...args) => this.handle('click', ...args),
[Message.DRAG]: (...args) => this.handle('drag', ...args),
[Message.RESIZE]: (...args) => this.resize(...args),
[Message.ROTATE]: (...args) => this.handle('rotate', ...args),
[Message.SCALE]: (...args) => this.handle('scale', ...args),
[Message.SWIPE]: (...args) => this.handle('swipe', ...args),
};
Object.entries(listeners).forEach( ([p,v]) => this.socket.on(p, v) );
}
[symbols.fullStateReport]() {
const fsreport = new FullStateReporter({
views: this.workspace.reportViews(),
items: this.workspace.reportItems(),
color: this.workspace.settings.color,
id: this.view.id,
});
new Message(Message.INITIALIZE, fsreport).emitWith(this.socket);
}
disconnect() {
if (this.workspace.removeView(this.view)) {
this.socket.disconnect(true);
return true;
}
return false;
}
handle(message, ...args) {
this.workspace.handle(message, this.view, ...args);
}
layout(data) {
this.view.assign(data);
new Message(Message.ADD_SHADOW, this.view).emitWith(this.socket.broadcast);
this.workspace.handle('layout', this.view, this.index);
}
resize(data) {
this.view.assign(data);
new Message(Message.UD_SHADOW, this.view).emitWith(this.socket.broadcast);
}
}
module.exports = Connection;
<file_sep>/src/server/ServerView.js
/*
* WAMS - An API for Multi-Surface Environments
*
* Author: <NAME>
* |-> Date: July/August 2018
*
* Original author: <NAME>
* Other revisions and supervision: <NAME>
*
* The ServerView provides operations for the server to locate, move,
* and rescale views.
*/
'use strict';
const { getInitialValues, IdStamper, View } = require('../shared.js');
const DEFAULTS = {
x: 0,
y: 0,
width: 1600,
height: 900,
type: 'view/background',
scale: 1,
rotation: 0,
bounds: {
x: 10000,
y: 10000,
},
};
const STAMPER = new IdStamper();
class ServerView extends View {
/*
* XXX: At some point, the effective width and height should be made to be
* updated whenever either the width, height, or scale of the
* view get updated. This could be achieve with getters and
* setters on those three values. Might need to think through all the
* possible complications though.
*
* The same thing could maybe be done with the 'center' getter, so
* that it refers to an actual stored value that gets updated whenever
* the effective width or height gets updated, or when the x or y
* values get updated. This would prevent having to recompute every
* time the value is accessed, which is the way things are working
* currently.
*
* Perhaps one technique would be to find a way of storing the actual
* x, y, width, height, effectiveWidth, effectiveHeight, and scale
* using some private data technique with alternative names for the
* variables (or some other storage method) and have the original
* names be used for the getters and setters. Might want to have a
* look at the shared Reporter factory definition to see if this can
* be handled at a more general level.
*/
constructor(values = {}) {
super(getInitialValues(DEFAULTS, values));
this.bounds = values.bounds || DEFAULTS.bounds;
this.effectiveWidth = this.width / this.scale;
this.effectiveHeight = this.height / this.scale;
STAMPER.stampNewId(this);
}
get bottom() { return this.y + this.effectiveHeight; }
get left() { return this.x; }
get right() { return this.x + this.effectiveWidth; }
get top() { return this.y; }
canBeScaledTo(width = this.width, height = this.height) {
return (width > 0) &&
(height > 0) &&
(this.x + width <= this.bounds.x) &&
(this.y + height <= this.bounds.y);
}
/*
* The canMoveTo[XY] functions are split up in order to allow for the x and
* y dimensions to be independently moved. In other words, if a move fails
* in the x direction, it can still succeed in the y direction. This makes
* it easier to push the view into the boundaries.
*
* XXX: Can they be unified simply while still allowing this kind of
* separation?
*/
canMoveToX(x = this.x) {
return (x >= 0) && (x + this.effectiveWidth <= this.bounds.x);
}
canMoveToY(y = this.y) {
return (y >= 0) && (y + this.effectiveHeight <= this.bounds.y);
}
moveBy(dx = 0, dy = 0) {
this.moveTo(this.x + dx, this.y + dy);
}
/*
* Views are constrained to stay within the boundaries of the workspace.
*/
moveTo(x = this.x, y = this.y) {
const coordinates = { x: this.x, y: this.y };
if (this.canMoveToX(x)) coordinates.x = x;
if (this.canMoveToY(y)) coordinates.y = y;
this.assign(coordinates);
}
rotateBy(radians = 0) {
this.rotateTo(this.rotation + radians);
}
rotateTo(rotation = this.rotation) {
this.assign({ rotation });
}
/*
* Transforms pointer coordinates and movement from a client into the
* corresponding coordinates and movement for the server's model.
*/
refineMouseCoordinates(x, y, dx, dy) {
const data = { x, y, dx, dy };
/*
* WARNING: It is crucially important that the instructions below occur
* in *precisely* this order!
*/
applyScale(data, this.scale);
applyRotation(data, (2 * Math.PI) - this.rotation);
applyTranslation(data, this.x, this.y);
return data;
function applyScale(data, scale) {
data.x /= scale;
data.y /= scale;
data.dx /= scale;
data.dy /= scale;
}
function applyTranslation(data, x, y) {
data.x += x;
data.y += y;
}
function applyRotation(data, theta) {
const cos_theta = Math.cos(theta);
const sin_theta = Math.sin(theta);
const x = data.x;
const y = data.y;
const dx = data.dx;
const dy = data.dy;
data.x = rotateX(x, y, cos_theta, sin_theta);
data.y = rotateY(x, y, cos_theta, sin_theta);
data.dx = rotateX(dx, dy, cos_theta, sin_theta);
data.dy = rotateY(dx, dy, cos_theta, sin_theta);
function rotateX(x, y, cos_theta, sin_theta) {
return x * cos_theta - y * sin_theta;
}
function rotateY(x, y, cos_theta, sin_theta) {
return x * sin_theta + y * cos_theta;
}
}
}
/*
* The scaled width and height (stored permanently as effective width and
* height) are determined by dividing the width or height by the scale.
* This might seem odd at first, as that seems to be the opposite of what
* should be done. But what these variables are actually representing is the
* amount of the underlying workspace that can be displayed inside the
* view. So a larger scale means that each portion of the workspace takes
* up more of the view, therefore _less_ of the workspace is visible.
* Hence, division.
*
* XXX: One thing that could be done in this function is to try anchoring
* on the right / bottom if anchoring on the left / top produces a
* failure. (By anchoring, I mean that the given position remains
* constant while the scaling is occurring).
*/
scaleTo(scale = this.scale) {
const effectiveWidth = this.width / scale;
const effectiveHeight = this.height / scale;
if (this.canBeScaledTo(effectiveWidth, effectiveHeight)) {
this.assign({ scale, effectiveWidth, effectiveHeight });
return true;
}
return false;
}
}
module.exports = ServerView;
<file_sep>/src/client/ClientItem.js
/*
* WAMS code to be executed in the client browser.
*
* Author: <NAME>
* |-> Date: July/August 2018
*
* Original author: <NAME>
* Other revisions and supervision: <NAME>
*
* The ClientItem class exposes the draw() funcitonality of wams items.
*/
'use strict';
const { IdStamper, Item, Message } = require('../shared.js');
const { CanvasBlueprint } = require('canvas-sequencer');
/*
* I'm not defining a 'defaults' object here, because the data going into
* the creation of items should always come from the server, where it has
* already gone through an initialization against a defaults object.
*/
const STAMPER = new IdStamper();
function createImage(src) {
if (src) {
const img = new Image();
img.src = src;
img.loaded = false;
img.addEventListener(
'load',
() => {
img.loaded = true;
document.dispatchEvent(new CustomEvent(Message.IMG_LOAD));
},
{ once: true }
);
return img;
}
return null;
}
class ClientItem extends Item {
constructor(data) {
super(data);
STAMPER.cloneId(this, data.id);
}
assign(data) {
const updateImage = data.imgsrc !== this.imgsrc;
const updateBlueprint = Boolean(data.blueprint);
super.assign(data);
if (updateImage) this.img = createImage(this.imgsrc);
if (updateBlueprint) this.blueprint = new CanvasBlueprint(this.blueprint);
// Rather than doing a bunch of checks, let's just always rebuild the
// sequence when updating any data in the item. Doing the checks to see if
// this is necessary would probably take as much or more time as just
// going ahead and rebuilding like this anyway.
if (this.blueprint) {
this.sequence = this.blueprint.build(this.report());
}
}
draw(context) {
const width = this.width || this.img.width;
const height = this.height || this.img.height;
if (this.sequence) {
this.sequence.execute(context);
} else if (this.img && this.img.loaded) {
context.drawImage(this.img, this.x, this.y, width, height);
} else {
// Draw placeholder rectangle.
context.save();
context.fillStyle = '#252525';
context.fillRect(this.x, this.y, width, height);
context.restore();
}
}
}
module.exports = ClientItem;
<file_sep>/TODO.md
# TODO
- [ ] Update canvas to work more like this for drawings:
<https://simonsarris.com/making-html5-canvas-useful/>
- [ ] Stretch goal is to incorporate a canvas library:
<http://danielsternlicht.com/playground/html5-canvas-libraries-comparison-table/>
- [ ] Implement subcanvases.
- [ ] Allow subcanvas to be drawn on top:
<https://stackoverflow.com/questions/3008635/html5-canvas-element-multiple-layers>
- [ ] Switch to HTTPS
- [ ] Regulate 'effective' width and height of views (calculate automatically)
- [ ] Allow scaling of views to use any viable corner as an anchor.
- [ ] Look into making the request handler more modular.
- [ ] Improve the end-user API by making it so that users do not have to
manually inform the wams app of any updates that have been made to the
items or views.
+ [ ] As part of this, try to regulate updates such that they are processed at
a regular rate, and not faster. This should help regulate situations
when multiple handlers are acting on the model in rapid succession.
- [ ] Write a distributed video player example.
- [ ] Lock drags to a single object (instead of always operating on the first
object it finds that's currently under the cursor).
- [ ] Look into using device orientation for rotation instead of touchscreen
inputs.
- [X] Reorganize code, such that each 'class module' is located inside its own
file. This will help considerably if the code continues to expand, and
will also help with more fine-grained testing.
- [ ] Add option for users to define whether an item is interactable, and then
only allow interaction with objects marked as interactable.
- [ ] Allow ordering of items on z-axis. (i.e. their position in the item queue)
- [ ] Update API doc.
- [X] Write design doc (properly).
- [ ] Implement item rotation.
+ [ ] Allow a 'rotate' interaction with objects.
- [ ] Implement 'rotate' for desktop users.
- [X] Separate the Server from the API endpoint.
+ [ ] Done, but can it be done better? Are there some even better abstractions
available that will make this code even easier to reason about?
---
# COMPLETED
_As of: Fri Aug 17 09:35:12 CST 2018_
- [X] Fix refinement of mouse coordinates when rotated.
May require simultaneous fixing of how the draw sequence is performed.
I suspect that with a bit of trig, those switch statements on the rotation
can be eliminated and replaced with a single universal calculation.
- [X] Implement a BlueprintCanvasSequence class that uses string tags in the
arguments of its atoms. It should have a `build()` method which, when
called with a `values` or likewise named object, will generate an
up-to-date sequence with the tags replaced with the values from the
passed-in object.
- [X] Use this blueprint sequence class for items:
+ [X] Expose it on the WamsServer class as `Sequence`.
+ [X] Set updates that affect x, y, width, or height values of items to build
a new version of the sequence that will be used for actual rendering.
- [X] Figure out a way of testing the client-side code without having to adjust
the code before and after by commenting out the `require()` statements.
- [X] Remove `hasOwnProperty()` checks before cloning Ids, as this is now
redundant.
- [X] Fix the client `draw()` sequence.
- [X] Fix scaling for desktop users. (Allow slow & fast scaling)
- [X] Fix bugs that occur when users join approximately simultaneously.
+ [X] Examine possibility of using mutexes around updates. What kind of API
for this sort of purpose does node.js provide?
+ [X] Node.js is single-threaded, so mutexes are probably unnecessary except
under very specific circumstances. Therefore, the bug is more likely to
have something to do with the way users are registered, and the way
layouts are handled. Look at adjusting the way connections are tracked
such that they fill the first available 'user' slot, and then layouts
get passed this slot number. This assignment should happen immediately
on connection establishment.
This would also fix the bug wherein if an early user leaves, their
layout callback might not get retriggered (because layout currently uses
the number of users, not a user identifier of some sort). Therefore
worth doing regardless of whether it fixes this particular bug.
- [X] Clean up how the canvas context gets passed around between view and
controller on the client side. Basically examine and revise `setup()` and
`layout()`
- [X] Extract an `Interactions` class from the client controller. ZingTouch is
working quite well, but it looks like it might not be the most well
maintained of libraries. By abstracting the interactions out like this, it
should become easier to swap out ZingTouch with another library, should
this prove necessary. It may even make it easier to implement new forms of
interactions, which would be a bonus!
- [X] Generally clean up the interactions.
- [X] Swap the render order around so that the object that will be dragged is
the one that appears on top on the canvas. (same for clicked...)
<file_sep>/examples/jumbotron.js
/*
* This example is intended to demonstrate having multiple users move their
* view around in a shared space.
*/
'use strict';
const Wams = require('../src/server');
const ws = new Wams({
bounds: { x: 4000, y: 4000 },
clientLimit: 4,
});
ws.spawnItem({
x: 0,
y: 0,
width: 4000,
height: 4000,
type: 'mona',
imgsrc: 'img/monaLisa.png'
});
// Takes in the target that was dragged on and who caused the drag event
const handleDrag = function(view, target, x, y, dx, dy) {
view.moveBy(-dx, -dy);
ws.update(view);
}
// Example Layout function that takes in the newly added client and which
// ws they joined.
// Lays out views in a decending staircase pattern
const handleLayout = (function makeLayoutHandler() {
function getMove(view, index) {
const olap = 30;
let move;
switch (index % 3) {
case 0: move = { x: view.right - olap, y: view.top }; break;
case 1: move = { x: view.left, y: view.bottom - olap }; break;
case 2: move = { x: view.right - olap, y: view.bottom - olap }; break;
}
return move;
}
function handleLayout(view, position) {
if (position > 0) {
const move = getMove(view, position);
view.moveTo(move.x, move.y);
ws.update(view);
}
}
return handleLayout;
})();
// Handle Scale, uses the built in view method scaleTo
const handleScale = function(view, newScale) {
view.scaleTo(newScale);
ws.update(view);
}
ws.on('drag', handleDrag);
ws.on('layout', handleLayout);
ws.on('scale', handleScale);
ws.listen(9000);
<file_sep>/examples/rotate-drawing.js
/*
* This is a simple example showing how users can interact with a shared set
* of items.
*/
'use strict';
const Wams = require('../src/server');
const ws = new Wams();
// Executed every time a user taps or clicks a screen
const handleClick = (function makeClickHandler(ws) {
const colours = [
'blue',
'red',
'green',
'pink',
'cyan',
'yellow',
];
function rectSeq(index) {
const seq = new Wams.Sequence();
seq.fillStyle = colours[index];
seq.fillRect('{x}', '{y}', '{width}', '{height}');
return seq;
}
function square(ix, iy, index) {
const x = ix - 64;
const y = iy - 64;
const width = 128;
const height = 128;
const type = 'colour';
const blueprint = rectSeq(index);
return {x, y, width, height, type, blueprint};
}
function handleClick(view, target, x, y) {
if (target.type === 'colour') {
ws.removeItem(target);
} else {
ws.spawnItem(square(x, y, view.id % 6));
}
}
return handleClick;
})(ws);
// Executed every time a drag occurs on a device
function handleDrag(view, target, x, y, dx, dy) {
if (target.type === 'colour') {
target.moveBy(dx, dy);
} else if (target.type === 'view/background') {
target.moveBy(-dx, -dy);
}
ws.update(target);
}
// Executed when a user rotates two fingers around the screen.
function handleRotate(view, radians) {
view.rotateBy(radians);
ws.update(view);
}
// Executed once per user, when they join.
function handleLayout(view, position) {
view.moveTo(4000,4000);
ws.update(view);
}
// Attaches the defferent function handlers
ws.on('click', handleClick);
ws.on('drag', handleDrag);
ws.on('layout', handleLayout);
ws.on('rotate', handleRotate);
ws.listen(9004);
<file_sep>/tests/shared/util.test.js
/*
* Test suite for util.js
*/
'use strict';
const {
defineOwnImmutableEnumerableProperty,
findLast,
getInitialValues,
makeOwnPropertyImmutable,
removeById,
safeRemoveById,
} = require('../../src/shared/util.js');
describe('defineOwnImmutableEnumerableProperty(obj, prop, val)', () => {
const x = {};
test('throws if obj is not a valid object', () => {
expect(() => defineOwnImmutableEnumerableProperty(undefined, 'a', 1))
.toThrow();
});
test('Does not throw if obj is valid', () => {
expect(() => defineOwnImmutableEnumerableProperty(x, 'a', 1))
.not.toThrow();
});
test('defines an immutable property on an object', () => {
expect(x).toHaveImmutableProperty('a');
});
test('defines an enumerable property on an object', () => {
expect(Object.keys(x)).toContain('a');
});
});
describe('findLast(array, callback, fromIndex, thisArg)', () => {
const arr = [1,'b',2,3,'a',4];
const self = {
x: 3,
c: 'a',
};
test('Finds the last item in the array that satisfies the callback', () => {
expect(findLast(arr, e => e % 2 === 0)).toBe(4);
expect(findLast(arr, e => typeof e === 'string')).toBe('a');
expect(findLast(arr, e => e % 2 === 1)).toBe(3);
expect(findLast(arr, e => e < 3)).toBe(2);
});
test('Starts from fromIndex, if provided', () => {
expect(findLast(arr, e => e % 2 === 0, 3)).toBe(2);
expect(findLast(arr, e => typeof e === 'string', 3)).toBe('b');
expect(findLast(arr, e => e % 2 === 1, 2)).toBe(1);
expect(findLast(arr, e => e < 3, 1)).toBe(1);
});
test('Uses thisArg, if provided', () => {
function cbx(e) { return this.x === e; };
function cba(e) { return this.c === e; };
expect(findLast(arr, cbx, undefined, self)).toBe(3);
expect(findLast(arr, cba, undefined, self)).toBe('a');
});
test('Passes all the expected values to the callback', () => {
const cb = jest.fn();
cb.mockReturnValue(true);
expect(() => findLast(arr, cb)).not.toThrow();
expect(cb).toHaveBeenCalledTimes(1);
expect(cb).toHaveBeenLastCalledWith(4,5,arr);
const cc = jest.fn();
cc.mockReturnValue(false);
expect(() => findLast(arr, cc)).not.toThrow();
expect(cc).toHaveBeenCalledTimes(6);
expect(cc).toHaveBeenLastCalledWith(1,0, arr);
});
});
describe('getInitialValues(default, data)', () => {
test('does not throw exceptions on empty objects', () => {
expect(getInitialValues()).toEqual({});
});
test('returns empty if defaults is empty, regardless of data', () => {
expect(getInitialValues({},{})).toEqual({});
expect(getInitialValues({})).toEqual({});
expect(getInitialValues({},{a:1})).toEqual({});
expect(getInitialValues({},1)).toEqual({});
});
test('Uses defaults if data is empty.', () => {
expect(getInitialValues({a:1})).toEqual({a:1});
expect(getInitialValues({a:1},{})).toEqual({a:1});
});
test('Overrides default property if data has property with same name', () => {
expect(getInitialValues({a:1}, {a:2})).toEqual({a:2});
});
});
describe('makeOwnPropertyImmutable(obj, prop)', () => {
test('makes own enumerable, configurable property immutable', () => {
const x = {id: 1};
expect(x).not.toHaveImmutableProperty('id');
expect(makeOwnPropertyImmutable(x, 'id')).toBe(x);
expect(() => delete x.id).toThrow();
expect(
() => Object.defineProperty(x, 'id', {configurable: true})
).toThrow();
expect(x).toHaveImmutableProperty('id');
});
test('does not affect non-configurable properties', () => {
const y = {};
Object.defineProperty(y, 'id', {
value:1,
configurable: false,
writable: true,
enumerable: true,
});
expect(y.id).toBe(1);
makeOwnPropertyImmutable(y, 'id');
expect(y).not.toHaveImmutableProperty('id');
y.id = 2;
expect(y.id).toBe(2);
});
test('does not affect non-own properties', () => {
const p = {a: 1};
const q = Object.create(p);
expect(q.a).toBe(1);
expect(q).not.toHaveImmutableProperty('a');
expect(p).not.toHaveImmutableProperty('a');
makeOwnPropertyImmutable(q, 'a');
expect(q).not.toHaveImmutableProperty('a');
expect(p).not.toHaveImmutableProperty('a');
p.a = 2;
expect(q.a).toBe(2);
});
test('does affect non-enumerable properties', () => {
const x = {};
Object.defineProperty(x, 'a', {
value: 1,
enumerable: false,
writable: true,
configurable: true
});
expect(x.a).toBe(1);
expect(x).not.toHaveImmutableProperty('a');
makeOwnPropertyImmutable(x, 'a');
expect(x).toHaveImmutableProperty('a');
});
});
describe('removeById(array, item)', () => {
function A(id) {
this.id = id;
}
let arr = [];
beforeEach(() => {
arr.splice(0, arr.length);
arr.push(new A(1));
arr.push(new A(2));
arr.push(new A(3));
});
test('Throws exception if not passed an array.', () => {
expect(() => removeById()).toThrow();
expect(() => removeById({})).toThrow();
});
test('Removes the item with the corresponding Id, if present', () => {
const a1 = new A(1);
const a2 = new A(2);
const a3 = new A(3);
expect(arr.length).toBe(3);
expect(() => removeById(arr,a1)).not.toThrow();
expect(arr.find(a => a.id === 1)).toBeUndefined();
expect(() => removeById(arr,a2)).not.toThrow();
expect(arr.find(a => a.id === 2)).toBeUndefined();
expect(() => removeById(arr,a3)).not.toThrow();
expect(arr.find(a => a.id === 3)).toBeUndefined();
expect(arr.length).toBe(0);
});
test('Does not remove any item if no item with Id present.', () => {
const a4 = new A(4);
expect(arr.length).toBe(3);
expect(() => removeById(arr,a4)).not.toThrow();
expect(arr.length).toBe(3);
});
});
describe('safeRemoveById(array, item, class_fn)', () => {
function A(id) {
this.id = id;
}
let arr = [];
beforeEach(() => {
arr.splice(0, arr.length);
arr.push(new A(1));
arr.push(new A(2));
arr.push(new A(3));
});
test('Removes the item with the corresponding Id, if present', () => {
const a1 = new A(1);
const a2 = new A(2);
const a3 = new A(3);
expect(arr.length).toBe(3);
expect(() => safeRemoveById(arr,a1, A)).not.toThrow();
expect(arr.find(a => a.id === 1)).toBeUndefined();
expect(() => safeRemoveById(arr,a2, A)).not.toThrow();
expect(arr.find(a => a.id === 2)).toBeUndefined();
expect(() => safeRemoveById(arr,a3, A)).not.toThrow();
expect(arr.find(a => a.id === 3)).toBeUndefined();
expect(arr.length).toBe(0);
});
test('Does not remove any item if no item with Id present.', () => {
const a4 = new A(4);
expect(arr.length).toBe(3);
expect(() => safeRemoveById(arr,a4, A)).not.toThrow();
expect(arr.length).toBe(3);
});
test('Throws an exception if item is not the proper type', () => {
const x = {id:3};
expect(arr.length).toBe(3);
expect(() => safeRemoveById(arr,x, A)).toThrow();
expect(arr.length).toBe(3);
});
});
<file_sep>/src/shared/ReporterFactory.js
/*
* Builds Reporter classes for the WAMS application.
*
* Author: <NAME>
* Date: July / August 2018
*/
'use strict';
const IdStamper = require('./IdStamper.js');
const {
defineOwnImmutableEnumerableProperty,
getInitialValues,
} = require('./util.js');
const STAMPER = new IdStamper();
/*
* This factory can generate the basic classes that need to communicate
* property values between the client and server.
*/
function ReporterFactory(coreProperties) {
const KEYS = Object.freeze(Array.from(coreProperties));
const INITIALIZER = {};
coreProperties.forEach( p => {
defineOwnImmutableEnumerableProperty(INITIALIZER, p, null);
});
Object.freeze(INITIALIZER);
class Reporter {
constructor(data) {
return this.assign(getInitialValues(INITIALIZER, data));
}
assign(data = {}) {
KEYS.forEach( p => {
if (data.hasOwnProperty(p)) this[p] = data[p];
});
}
report() {
const data = {};
KEYS.forEach( p => data[p] = this[p] );
STAMPER.cloneId(data, this.id);
return data;
}
}
return Reporter;
}
module.exports = ReporterFactory;
<file_sep>/tests/server/WorkSpace.test.js
/*
* Test suite for src/server.js
*
* Author: <NAME>
* Date: July/August 2018
*/
'use strict';
const { NOP } = require('../../src/shared.js');
const WorkSpace = require('../../src/server/WorkSpace.js');
const ServerItem = require('../../src/server/ServerItem.js');
const ServerView = require('../../src/server/ServerView.js');
describe('WorkSpace', () => {
const DEFAULTS = Object.freeze({
bounds: {
x: 10000,
y: 10000,
},
color: '#aaaaaa',
});
describe('constructor(port, settings)', () => {
test('constructs correct type of object', () => {
expect(new WorkSpace()).toBeInstanceOf(WorkSpace);
});
test('Stamps an immutable Id', () => {
const ws = new WorkSpace();
expect(ws).toHaveImmutableProperty('id');
});
test('Uses default settings if none provided', () => {
expect(new WorkSpace().settings).toMatchObject(DEFAULTS);
});
test('Uses user-defined settings, if provided', () => {
const custom = {
color: 'rgb(155,72, 84)',
bounds: {
x: 1080,
y: 1920,
},
};
expect(new WorkSpace(custom).settings).toMatchObject(custom);
const ws = new WorkSpace({color: 'a'});
expect(ws.settings).not.toEqual(DEFAULTS);
expect(ws.settings.bounds).toEqual(DEFAULTS.bounds);
expect(ws.settings.color).toEqual('a');
});
});
describe('getters and setters', () => {
const bounded = {bounds: {x: 700, y: 800} };
const ws = new WorkSpace(bounded);
test('can get width', () => {
expect(ws.width).toBe(bounded.bounds.x);
});
test('can get height', () => {
expect(ws.height).toBe(bounded.bounds.y);
});
test('can set width', () => {
ws.width = 42;
expect(ws.width).toBe(42);
});
test('can set height', () => {
ws.height = 43;
expect(ws.height).toBe(43);
});
});
describe('spawnItem(values)', () => {
const ws = new WorkSpace();
const DEFAULTS = Object.freeze({
x: 0,
y: 0,
width: 128,
height: 128,
type: 'item/foreground',
imgsrc: '',
blueprint: null,
});
test('Returns a ServerItem', () => {
expect(ws.spawnItem()).toBeInstanceOf(ServerItem);
});
test('Uses default Item values if none provided', () => {
expect(ws.spawnItem()).toMatchObject(DEFAULTS);
});
test('Uses user-defined Item values, if provided', () => {
const i = ws.spawnItem({x:70,y:40});
expect(i.x).toBe(70);
expect(i.y).toBe(40);
expect(i.width).toBe(DEFAULTS.width);
expect(i.height).toBe(DEFAULTS.height);
});
test('Keeps track of the item', () => {
const i = ws.spawnItem({x:155,y:155});
expect(ws.items).toContain(i);
});
});
describe('reportItems()', () => {
let ws;
const expectedProperties = [
'x',
'y',
'width',
'height',
'type',
'imgsrc',
'blueprint',
'id',
];
beforeAll(() => {
ws = new WorkSpace();
ws.spawnItem();
ws.spawnItem({x:20,y:40});
ws.spawnItem({x:220,y:240,width:50,height:50});
});
test('Returns an array', () => {
expect(ws.reportItems()).toBeInstanceOf(Array);
});
test('Does not return the actual items, but simple Objects', () => {
const r = ws.reportItems();
r.forEach( i => {
expect(i).not.toBeInstanceOf(ServerItem);
expect(i).toBeInstanceOf(Object);
});
});
test('Objects returned contain only the expected data', () => {
const r = ws.reportItems();
r.forEach( i => {
expect(Object.getOwnPropertyNames(i)).toEqual(expectedProperties);
});
});
test('Returns data for each item that exists in the workspace', () => {
expect(ws.reportItems().length).toBe(ws.items.length);
});
});
describe('findItemByCoordinates(x,y)', () => {
let ws;
beforeAll(() => {
ws = new WorkSpace();
ws.spawnItem({x:0,y:0,width:100,height:100});
ws.spawnItem({x:20,y:40,width:100,height:100});
ws.spawnItem({x:220,y:240,width:50,height:50});
});
test('Finds an item at the given coordinates, if one exists', () => {
let i = ws.findItemByCoordinates(0,0);
expect(i).toBeDefined();
expect(i).toBeInstanceOf(ServerItem);
expect(i).toBe(ws.items[0]);
i = ws.findItemByCoordinates(110,110);
expect(i).toBeDefined();
expect(i).toBeInstanceOf(ServerItem);
expect(i).toBe(ws.items[1]);
i = ws.findItemByCoordinates(250,250);
expect(i).toBeDefined();
expect(i).toBeInstanceOf(ServerItem);
expect(i).toBe(ws.items[2]);
});
test('Finds the first item at the given coordinates', () => {
const i = ws.findItemByCoordinates(25,45);
expect(i).toBeDefined();
expect(i).toBeInstanceOf(ServerItem);
expect(i).toBe(ws.items[1]);
});
test('Returns falsy if no item at given coordinates', () => {
expect(ws.findItemByCoordinates(150,150)).toBeFalsy();
});
});
describe('removeItem(item)', () => {
let ws;
let item;
beforeAll(() => {
ws = new WorkSpace();
ws.spawnItem({x:0,y:0,width:100,height:100});
ws.spawnItem({x:20,y:40,width:100,height:100});
ws.spawnItem({x:220,y:240,width:50,height:50});
item = ws.findItemByCoordinates(101,101);
});
test('Removes an item if it is found', () => {
expect(ws.removeItem(item)).toBe(true);
expect(ws.items).not.toContain(item);
});
test('Does not remove anything if item not found', () => {
const is = Array.from(ws.items);
expect(ws.removeItem(item)).toBe(false);
expect(ws.items).toMatchObject(is);
});
test('Throws exception if no item provided', () => {
expect(() => ws.removeItem()).toThrow();
});
});
describe('spawnView(values)', () => {
let DEFAULTS;
let ws;
beforeAll(() => {
ws = new WorkSpace({clientLimit:4});
DEFAULTS = {
x: 0,
y: 0,
width: 1600,
height: 900,
type: 'view/background',
effectiveWidth: 1600,
effectiveHeight: 900,
scale: 1,
rotation: 0,
};
});
test('Returns a ServerView', () => {
expect(ws.spawnView()).toBeInstanceOf(ServerView);
});
test('Uses default View values if none provided', () => {
expect(ws.spawnView()).toMatchObject(DEFAULTS);
});
test('Uses user-defined View values, if provided', () => {
const vs = ws.spawnView({
x: 42,
y: 71,
scale: 3.5,
});
expect(vs.x).toBe(42);
expect(vs.y).toBe(71);
expect(vs.scale).toBe(3.5);
expect(vs.width).toBe(DEFAULTS.width);
expect(vs.height).toBe(DEFAULTS.height);
});
test('Keeps track of View', () => {
const vs = ws.spawnView({
x:7,
y:9,
width: 42,
height: 870,
});
expect(ws.views).toContain(vs);
});
});
describe('reportViews()', () => {
let ws;
const expectedProperties = [
'x',
'y',
'width',
'height',
'type',
'effectiveWidth',
'effectiveHeight',
'scale',
'rotation',
'id',
];
beforeAll(() => {
ws = new WorkSpace();
ws.spawnView();
ws.spawnView({x:2});
ws.spawnView({x:42,y:43});
});
test('Returns an array', () => {
expect(ws.reportViews()).toBeInstanceOf(Array);
});
test('Does not return the actual Views, but simple Objects', () => {
ws.reportViews().forEach( v => {
expect(v).not.toBeInstanceOf(ServerView);
expect(v).toBeInstanceOf(Object);
});
});
test('Objects returned contain only the expected data', () => {
ws.reportViews().forEach( v => {
expect(Object.getOwnPropertyNames(v)).toEqual(expectedProperties);
});
});
test('Returns data for each View in the workspace', () => {
expect(ws.reportViews().length).toBe(ws.views.length);
});
});
describe('removeView(view)', () => {
let ws;
let view;
beforeAll(() => {
ws = new WorkSpace();
ws.spawnView();
view = ws.spawnView({x:2});
ws.spawnView({x:42,y:43});
});
test('Removes a view if it is found', () => {
expect(ws.removeView(view)).toBe(true);
expect(ws.views).not.toContain(view);
});
test('Does not remove anything if view not found', () => {
const v = new ServerView({x:200,y:200});
const curr = Array.from(ws.views);
expect(ws.removeView(v)).toBe(false);
expect(ws.views).toMatchObject(curr);
});
test('Throws exception if not view provided', () => {
expect(() => ws.removeView()).toThrow();
});
});
describe('on(event, listener)', () => {
let ws;
let vs;
beforeAll(() => {
ws = new WorkSpace();
vs = ws.spawnView();
});
test('Throws if invalid event supplied', () => {
expect(() => ws.on()).toThrow();
expect(() => ws.on('rag')).toThrow();
});
describe.each([['click'],['drag'],['layout'],['scale']])('%s', (s) => {
test('Handler starts as a NOP', () => {
expect(ws.handlers[s]).toBe(NOP);
});
test('Throws if invalid listener supplied', () => {
expect(() => ws.on(s, 'a')).toThrow();
});
test('Attaches a handler in the appropriate place', () => {
const fn = jest.fn();
ws.on(s, fn);
expect(ws.handlers[s]).not.toBe(NOP);
expect(ws.handlers[s]).toBeInstanceOf(Function);
});
test('Attached handler will call the listener when invoked', () => {
const fn = jest.fn();
ws.on(s, fn);
ws.handlers[s](vs, {});
expect(fn).toHaveBeenCalledTimes(1);
expect(fn.mock.calls[0][0]).toBe(vs);
});
});
});
describe('handle(message, ...args)', () => {
let ws;
let vs;
let x, y, dx, dy, scale;
beforeAll(() => {
ws = new WorkSpace();
vs = ws.spawnView();
x = 42;
y = 78;
dx = 5.2;
dy = -8.79;
scale = 0.883;
});
test('Throws if invalid message type provided', () => {
expect(() => ws.handle('rag')).toThrow();
});
describe('click', () => {
let fn;
beforeAll(() => {
fn = jest.fn();
ws.on('click', fn);
});
test('Calls the appropriate listener', () => {
expect(() => ws.handle('click', vs, {x, y})).not.toThrow();
expect(fn).toHaveBeenCalledTimes(1);
});
test('Calls the listener with the expected arguments', () => {
expect(() => ws.handle('click', vs, {x, y})).not.toThrow();
expect(fn.mock.calls[0][0]).toBe(vs);
expect(fn.mock.calls[0][1]).toBe(vs);
expect(fn.mock.calls[0][2]).toBeCloseTo(x);
expect(fn.mock.calls[0][3]).toBeCloseTo(y);
});
});
describe('drag', () => {
let fn;
beforeAll(() => {
fn = jest.fn();
ws.on('drag', fn);
});
test('Calls the appropriate listener', () => {
expect(() => ws.handle('drag', vs, {x, y, dx, dy})).not.toThrow();
expect(fn).toHaveBeenCalledTimes(1);
});
test('Calls the listener with the expected arguments', () => {
expect(() => ws.handle('drag', vs, {x, y, dx, dy})).not.toThrow();
expect(fn.mock.calls[0][0]).toBe(vs);
expect(fn.mock.calls[0][1]).toBe(vs);
expect(fn.mock.calls[0][2]).toBeCloseTo(x);
expect(fn.mock.calls[0][3]).toBeCloseTo(y);
expect(fn.mock.calls[0][4]).toBeCloseTo(dx);
expect(fn.mock.calls[0][5]).toBeCloseTo(dy);
});
});
describe('layout', () => {
let fn;
beforeAll(() => {
fn = jest.fn();
ws.on('layout', fn);
});
test('Calls the appropriate listener', () => {
expect(() => ws.handle('layout', vs, 0)).not.toThrow();
expect(fn).toHaveBeenCalledTimes(1);
});
test('Calls the listener with the expected arguments', () => {
expect(fn).toHaveBeenLastCalledWith(vs, 0);
});
});
describe('scale', () => {
let fn;
beforeAll(() => {
fn = jest.fn();
ws.on('scale', fn);
});
test('Calls the appropriate listener', () => {
expect(() => ws.handle('scale', vs, {scale})).not.toThrow();
expect(fn).toHaveBeenCalledTimes(1);
});
test('Calls the listener with the expected arguments', () => {
expect(() => ws.handle('scale', vs, {scale})).not.toThrow();
expect(fn).toHaveBeenLastCalledWith(vs, scale);
});
});
});
});
<file_sep>/src/server/ServerItem.js
/*
* WAMS - An API for Multi-Surface Environments
*
* Author: <NAME>
* |-> Date: July/August 2018
*
* Original author: <NAME>
* Other revisions and supervision: <NAME>
*
* The ServerItem provides operations for the server to locate and move items
* around.
*/
'use strict';
const { getInitialValues, IdStamper, Item } = require('../shared.js');
const DEFAULTS = Object.freeze({
x: 0,
y: 0,
width: 128,
height: 128,
type: 'item/foreground',
imgsrc: '',
blueprint: null,
});
const STAMPER = new IdStamper();
class ServerItem extends Item {
constructor(values = {}) {
super(getInitialValues(DEFAULTS, values));
STAMPER.stampNewId(this);
}
containsPoint(x,y) {
return (this.x <= x) &&
(this.y <= y) &&
(this.x + this.width >= x) &&
(this.y + this.height >= y);
}
/*
* Items are allowed to be moved off screen, so no limitations on where
* items can be moved to.
*/
moveTo(x = this.x, y = this.y) {
this.assign({x,y});
}
moveBy(dx = 0, dy = 0) {
this.moveTo(this.x + dx, this.y + dy);
}
}
module.exports = ServerItem;
<file_sep>/libs/zingtouch.js
../node_modules/zingtouch/dist/zingtouch.js<file_sep>/DESIGN.md
# Design
This document details the design of the WAMS project, beginning with the lowest
level classes and code, up to the high level end-user API.
## Contents
* [Installation](#installation)
* [Packages](#packages)
* [Build Tools](#build-tools)
* [Testing](#testing)
* [Shared Sources](#shared-sources)
* [Client Sources](#client-sources)
* [Server Sources](#server-sources)
## Installation
This project is built for [node.js](https://nodejs.org/en/) and
[npm](https://www.npmjs.com/). To install and run the project, you will need to
install the latest stable version of both tools.
With that done, clone the repo and install:
```shell
git clone 'https://github.com/mvanderkamp/wams'
cd wams
npm install
```
## Packages
This project has four dependencies:
1. [canvas-sequencer](https://www.npmjs.com/package/canvas-sequencer)
This package allows end users to define custom rendering sequences for the
canvas.
2. [zingtouch](https://github.com/zingchart/zingtouch)
This package is a gesture library that provides a normalization of
interaction across browsers and devices, and makes the following kinds of
gestures possible:
- __Tap__
- __Pan__
- __Swipe__
- __Pinch__
- __Rotate__
I am working with the maintainers on developing and improving this library,
and may end up forking my own version if I find the maintainers too cumbersome
to deal with.
3. [express](https://www.npmjs.com/package/express)
The `express` package provides a simple way of establishing routes for the
node.js server.
4. [socket.io](https://www.npmjs.com/package/socket.io)
The `socket.io` package is used on both client and server side behind the
scenes to maintain an open, real-time connection between the server and
client. Each client is on its own socket connection, but all clients share a
namespace.
Therefore messages are emitted as follows:
* __To a single client:__ on its socket.
* __To everyone but a single client:__ on its socket's broadcast channel.
* __To everyone:__ on the namespace.
## Build Tools
Currently, I am using Browserify to build the client side code. Why Browserify?
Well, because I've found it easy to use. It might not produce the most optimal
code, and it doesn't have much in the way of super fancy features built in, but
I don't need any of that, and the basic functionality just simply works, and
works well.
To build the client side code:
```shell
npm run build
```
The bundle will end up in `dist/wams-client.js`. An important design principle
in this project is that end users should never need to touch the client side
code.
No server side tools are currently in use.
## Testing
Testing is done with the `Jest` framework for `npm`. The test suites can be
found in `tests/`.
To run all the tests:
```shell
npm test
```
To test, for example, only the client-side code:
```shell
npm test client
```
To test, for example, only the WorkSpace class from the server-side code:
```shell
npm test WorkSpace
```
Extra configuration can be found and placed in the `jest` field of
`package.json`.
## Shared Sources
To coordinate activity between the client and server, I provide a shared set of
resources that are exposed by `shared.js`.
* [utilities](#utilities)
* [IdStamper](#idstamper)
* [Reporters](#reporters)
* [Message](#message)
### utilities
Exported by this module are a number of quality-of-life functions intended to be
used in disparate places throughout the codebase. They are there to make writing
other code easier, and to reduce repetition.
### IdStamper
This class controls ID generation so that I don't have to think about it ever
again. The class has access to a private generator function for IDs and exposes
a pair of methods for stamping new IDs onto objects and cloning previously
existing Ids onto objects:
1. stampNewId(object):
* object: The object to stamp with an id.
All IDs produced by this method are guaranteed to be unique, on a per-stamper
basis. (Two uniquely constructed stampers can and will generate identical Ids).
2. cloneId(object, id):
* object: Will receive a cloned id.
* id: The id to clone onto the object.
Example:
```javascript
const stamper = new IdStamper();
const obj = {};
stamper.stampNewId(obj);
console.log(obj.id); // Logs an integer unique to Ids stamped by stamper
obj.id = 2; // Assignment has no effect.
delete obj.id; // Is false and has no effect.
// (throws an error in strict mode).
const danger = {};
stamper.cloneId(danger, obj.id); // Will work. 'danger' & 'obj' are
// now both using the same ID.
```
### Reporters
All the "reporters" provided by this module share a common interface, as they
are all generated by the same class factory.
Specifically, each reporter exposes two methods for getting and setting a set of
core properties: `assign(data)` and `report()`. Each is guaranteed to only
affect the core properties that were passed to the factory.
The motivation for this design was to and provide some semblance of confidence
about the data that will be passed between the client and server. With the core
properties defined in a shared module, the chance of data being sent back and
forth in a format that one end or the other does not recognize is greaty
reduced. This was taken even further with the [Message](#message) class, which
uses this reporter interface for the data it transmits.
Importantly, the set of Reporters includes the common `Item` and `View`
definitions that both client and server extend. Think of these common reporter
definitions as pipes that both client and server must push their data through if
they wish to share it.
### Message
The Message class takes the notion of reporters one step further by centralizing
the method of data transmission between the client and server.
It does this by explicitly requiring that any data objects it receives for
transmission be reporters (or at least, they must have a `report` function
available at some location in their prototype chain... Insert complaints about
JavaScript here).
Messages can be transmitted by any object with an `emit` function.
## Client Sources
* [ShadowView](#shadowview)
* [ClientItem](#clientitem)
* [ClientView](#clientview)
* [Interactor](#interactor)
* [ClientController](#clientcontroller)
### ShadowView
The ShadowView class is a simply extension of the View class that provides a
`draw(context)` method. It is used for rendering the outlines of other views
onto the canvas, along with a triangle marker indicating the orientation of the
view. (The triangle appears in what is the view's top left corner).
Care must be taken with the drawing routines to ensure that the outlines
accurately reflect what is visible to the view they represent.
### ClientItem
The ClientItem class is an extension of the Item class that provides a
`draw(context)` method for rendering the item to the canvas. It is aware of and
able to make use of the `CanvasBlueprint` class from the `canvas-sequencer`
package for rendering custom sequences to the canvas.
To ensure that the blueprints, sequences, and images are kept up to date, the
`ClientItem` class wraps extra functionality around the base `assign(data)`
method.
### ClientView
The ClientView class maintains the client-side model of the system, keeping
track of the items and other views, as well as its own status. It is also
responsible for holding onto the canvas context and running the principle
`draw()` sequence.
These two responsibilities are bundled together because rendering requires
knowledge of the model. Note, however, that the ClientView is not actually in
charge of issuing changes to the model, but is rather the endpoint of such
commands. It is the ClientController which issues these commands as per the
messages it receieves from the server.
One thing that may appear odd is the `handle(message, ...args)` function. Why
not just call the methods directly, you might ask. This wrapper makes it
possible to guarantee that changes to the model will always be immediately
reflected in the render.
The `handle(message, ...args)` wrapper is necessary because I decided to reduce
the footprint of the WAMS application by foregoing a `draw()` loop in favour of
only drawing the canvas when changes to the model are made. This significantly
reduces the workload when the model is idle, as the page merely needs to
maintain the `socket.io` connection to the server.
### Interactor
The Interactor class provides a layer of abstraction between the controller and
the interaction / gesture library being used. This should make it relatively
easy, in the long run, to swap out interaction libraries if need be.
When a user interacts with the application in a way that is supported, the
Interactor tells the ClientController the necessary details so the
ClientController can forward those details to the server.
### ClientController
The ClientController maintains the `socket.io` connection to the server, and
informs the ClientView of changes to the model. It also forwards messages to the
server that it receieves from the Interactor about user interaction.
## Server Sources
* [ServerItem](#serveritem)
* [ServerView](#serverview)
* [ListenerFactory](#listenerfactory)
* [WorkSpace](#workspace)
* [Connection](#connection)
* [RequestHandler](#requesthandler)
* [Server](#server)
* [Wams](#wams)
### ServerItem
The ServerItem maintains the model of an item. It can be moved anywhere, and
provides a `containsPoint(x,y)` method for determining if a point is located
within its coordinates. It extends the shared Item class.
### ServerView
The ServerView maintains the model of a view. It can be moved, scaled, and
rotated. It also provides a routine for transforming a set of pointer data
from its user into the corresponding coordinates and data for the general model.
Also provided is a selection of positional getters for the bottom, top, left,
and right of the view.
### ListenerFactory
The ListenerFactory is not a class, but an object exposing a `build` routine for
the WorkSpace to use when registering event handlers. The handlers built by this
factory prepare and unpack data before calling the endpoint handler registered
by the user of the API.
### WorkSpace
The WorkSpace is the central maintainer of the model. It keeps track of views
and items, and registers and calls the endpoint event handlers.
### Connection
A Connection maintains a `socket.io` connection with a client. It keeps track of
the ServerView corresponding to that client, and informs the WorkSpace model of
messages it receives from its client.
### RequestHandler
The RequestHandler provides a layer of abstraction between the server and the
request handling library and its configuration.
### Server
The Server is responsible for establishing the server and gatekeeping incoming
connections. Currently it also handles message distribution when it is necessary
to send messages to the namespace.
### Wams
This module defines the API endpoint. In practice, this means it is a thin
wrapper around the Server class which exposes only that functionality of the
Server which should be available to the end user.
<file_sep>/src/shared.js
/*
* Utilities for the WAMS application.
*
* Author: <NAME>
* Date: July / August 2018
*
* The below set of utilities and classes are intended for use by both the
* client and the server, in order to provide a common interface.
*/
'use strict';
const IdStamper = require('./shared/IdStamper.js');
const Message = require('./shared/Message.js');
const Reporters = require('./shared/Reporters.js');
const Utils = require('./shared/util.js');
/*
* This object stores a set of core constants for use by both the client and
* the server.
*/
const constants = Object.freeze({
// General constants
ROTATE_0: 0,
ROTATE_90: Math.PI / 2,
ROTATE_180: Math.PI,
ROTATE_270: Math.PI * 1.5,
// Namespaces
NS_WAMS: '/wams',
});
/*
* Package up the module and freeze it for delivery.
*/
module.exports = Object.freeze({
constants,
IdStamper,
Message,
...Reporters,
...Utils,
});
<file_sep>/src/server.js
/*
* WAMS - An API for Multi-Surface Environments
*
* Author: <NAME>
* |-> Date: July/August 2018
*
* Original author: <NAME>
* Other revisions and supervision: <NAME>
*/
'use strict';
const Wams = require('./server/Wams.js');
const { CanvasBlueprint } = require('canvas-sequencer');
Wams.Sequence = CanvasBlueprint;
module.exports = Wams;
<file_sep>/src/shared/Reporters.js
/*
* Reporters for the WAMS application.
*
* Author: <NAME>
* Date: July / August 2018
*/
'use strict';
const ReporterFactory = require('./ReporterFactory.js');
/*
* This Item class provides a common interface between the client and
* the server by which the Items can interact safely.
*/
const Item = ReporterFactory([
'x',
'y',
'width',
'height',
'type',
'imgsrc',
'blueprint',
]);
/*
* This View class provides a common interface between the client and
* the server by which the Views can interact safely.
*/
const View = ReporterFactory([
'x',
'y',
'width',
'height',
'type',
'effectiveWidth',
'effectiveHeight',
'scale',
'rotation',
]);
/*
* This class is intended for sharing mouse action data between client and
* server.
*/
const MouseReporter = ReporterFactory([
'x',
'y',
'dx',
'dy',
]);
/*
* This class allows reporting of scale data between client and server.
*/
const ScaleReporter = ReporterFactory([
'scale',
]);
/*
* This class allows reporting of rotation data between client and server.
*/
const RotateReporter = ReporterFactory([
'radians',
]);
/*
* This class allows reporting of swipe data between client and server.
*/
const SwipeReporter = ReporterFactory([
'acceleration',
'velocity',
'x',
'y',
]);
/*
* This class allows reporting of the full state of the model, for bringing
* new clients up to speed (or potentially also for recovering a client, if
* need be).
*/
const FullStateReporter = ReporterFactory([
'views',
'items',
'color',
'id',
]);
module.exports = {
Item,
View,
MouseReporter,
ScaleReporter,
RotateReporter,
FullStateReporter,
};
<file_sep>/src/shared/IdStamper.js
/*
* IdStamper utility for the WAMS application.
*
* Author: <NAME>
* Date: July / August 2018
*
* I wrote this generator class to make Id generation more controlled.
* The class has access to a private (local lexical scope) generator
* function and Symbol for generators, and exposes a pair of methods for
* stamping new Ids onto objects and cloning previously existing Ids onto
* objects.
*
* stampNewId(object):
* object: The object to stamp with an id.
*
* All Ids produced by this method are guaranteed to be unique, on a
* per-stamper basis. (Two uniquely constructed stampers can and will
* generate identical Ids).
*
* cloneId(object, id):
* object: Will receive a cloned id.
* id: The id to clone onto the object.
*
* For example:
* const stamper = new IdStamper();
* const obj = {};
* stamper.stampNewId(obj);
* console.log(obj.id); // an integer unique to Ids stamped by stamper
* obj.id = 2; // has no effect.
* delete obj.id; // false
*
* const danger = {};
* stamper.cloneId(danger, obj.id); // Will work. 'danger' & 'obj' are
* // now both using the same Id.
*/
'use strict';
const { defineOwnImmutableEnumerableProperty } = require('./util.js');
function* id_gen() {
let next_id = 0;
while (Number.isSafeInteger(next_id + 1)) yield ++next_id;
}
const gen = Symbol();
class IdStamper {
constructor() {
this[gen] = id_gen();
}
stampNewId(obj) {
defineOwnImmutableEnumerableProperty(
obj,
'id',
this[gen].next().value
);
}
cloneId(obj, id) {
if (Number.isSafeInteger(id)) {
defineOwnImmutableEnumerableProperty(obj, 'id', id);
}
}
}
module.exports = IdStamper;
<file_sep>/edit.sh
#!/bin/bash
# Author: <NAME>
# Date: August 21, 2018
#
# This bash script opens a new vim instance with three windows, one of which is
# a small scratch buffer for reading the output of external commands.
#
# This file will be where I maintain my personal preference for opening up vim
# when working on a project. This is intended as a template, but is perfectly
# usable if a project follows this simple layout.
vim \
src/*.js \
src/client/*.js \
src/server/*.js \
src/shared/*.js \
tests/*.js \
tests/client/*.js \
tests/server/*.js \
tests/shared/*.js \
examples/*.js \
README.md \
TODO.md \
DESIGN.md \
"+bot vnew +setlocal\ buftype=nofile" \
"+abo new" \
"+argu 2" \
"+resize +10"
<file_sep>/src/server/ListenerFactory.js
/*
* WAMS - An API for Multi-Surface Environments
*
* Author: <NAME>
* |-> Date: July/August 2018
*
* Original author: <NAME>
* Other revisions and supervision: <NAME>
*
* Treat this factory as a static class with no constructor. If you try to
* instantiate it with the 'new' keyword you will get an exception. Its primary
* usage is for generating appropriate listeners via its 'build' function.
*/
'use strict';
function click(listener, workspace) {
return function handleClick(view, {x, y}) {
const mouse = view.refineMouseCoordinates(x, y);
if (mouse) {
const {x, y} = mouse;
const target = workspace.findItemByCoordinates(x, y) || view;
listener(view, target, x, y);
}
};
};
function drag(listener, workspace) {
return function handleDrag(view, {x, y, dx, dy}) {
const mouse = view.refineMouseCoordinates(x, y, dx, dy);
if (mouse) {
const {x, y, dx, dy} = mouse;
const target = workspace.findItemByCoordinates(x,y) || view;
listener(view, target, x, y, dx, dy);
}
};
};
function layout(listener, workspace) {
return function handleLayout(view, index) {
listener(view, index);
};
};
function rotate(listener, workspace) {
return function handleRotate(view, {radians}) {
listener(view, radians);
};
};
function scale(listener, workspace) {
return function handleScale(view, {scale}) {
listener(view, scale);
};
};
function swipe(listener, workspace) {
return function handleSwipe(view, {acceleration, velocity, x, y}) {;
listener(view, acceleration, velocity, x, y);
}
}
const BLUEPRINTS = Object.freeze({
click,
drag,
layout,
rotate,
scale,
swipe,
});
function build(type, listener, workspace) {
if (typeof listener !== 'function') {
throw 'Attached listener must be a function';
}
return BLUEPRINTS[type](listener, workspace);
};
const TYPES = Object.keys(BLUEPRINTS);
const ListenerFactory = Object.freeze({
build,
TYPES,
});
module.exports = ListenerFactory;
<file_sep>/src/shared/Message.js
/*
* Shared Message class for the WAMS application.
*
* Author: <NAME>
* Date: July / August 2018
*/
'use strict';
const { defineOwnImmutableEnumerableProperty } = require('./util.js');
const TYPES = Object.freeze({
// For the server to inform about changes to the model
ADD_ITEM: 'wams-add-item',
ADD_SHADOW: 'wams-add-shadow',
RM_ITEM: 'wams-remove-item',
RM_SHADOW: 'wams-remove-shadow',
UD_ITEM: 'wams-update-item',
UD_SHADOW: 'wams-update-shadow',
UD_VIEW: 'wams-update-view',
// Connection establishment related (disconnect, initial setup)
INITIALIZE: 'wams-initialize',
LAYOUT: 'wams-layout',
FULL: 'wams-full',
// User event related
CLICK: 'wams-click',
DRAG: 'wams-drag',
RESIZE: 'wams-resize',
ROTATE: 'wams-rotate',
SCALE: 'wams-scale',
SWIPE: 'wams-swipe',
// Page event related
IMG_LOAD: 'wams-image-loaded',
});
const TYPE_VALUES = Object.freeze(Object.values(TYPES));
class Message {
constructor(type, reporter) {
if (!TYPE_VALUES.includes(type)) {
throw 'Invalid message type!';
}
this.type = type;
this.reporter = reporter;
}
emitWith(emitter) {
// console.log('emitting:', this.type, this.reporter.report());
emitter.emit(this.type, this.reporter.report());
}
}
Object.entries(TYPES).forEach( ([p,v]) => {
defineOwnImmutableEnumerableProperty( Message, p, v );
});
module.exports = Message;
<file_sep>/src/server/WorkSpace.js
/*
* WAMS - An API for Multi-Surface Environments
*
* Author: <NAME>
* |-> Date: July/August 2018
*
* Original author: <NAME>
* Other revisions and supervision: <NAME>
*
* The WorkSpace keeps track of views and items, and can handle events on
* those items and views which allow them to be interacted with.
*/
'use strict';
const {
findLast,
getInitialValues,
IdStamper,
NOP,
safeRemoveById,
} = require('../shared.js');
const ListenerFactory = require('./ListenerFactory.js');
const ServerItem = require('./ServerItem.js');
const ServerView = require('./ServerView.js');
const DEFAULTS = Object.freeze({
bounds: { x: 10000, y: 10000 },
color: '#aaaaaa',
});
const MIN_BOUND = 100;
const STAMPER = new IdStamper();
/*
* Prevents NaN from falling through.
*/
function safeNumber(x) {
return Number(x) || 0;
}
/*
* Makes sure that the received bounds are valid.
*/
function resolveBounds(bounds = {}) {
const x = safeNumber(bounds.x);
const y = safeNumber(bounds.y);
if (x < MIN_BOUND || y < MIN_BOUND) {
throw `Invalid bounds received: ${bounds}`;
}
return { x, y };
}
class WorkSpace {
constructor(settings) {
this.settings = getInitialValues(DEFAULTS, settings);
this.settings.bounds = resolveBounds(this.settings.bounds);
STAMPER.stampNewId(this);
// Things to track.
// this.subWS = [];
this.views = [];
this.items = [];
// Attach NOPs for the event listeners, so they are callable.
this.handlers = {};
ListenerFactory.TYPES.forEach( ev => {
this.handlers[ev] = NOP;
});
}
get width() { return this.settings.bounds.x; }
get height() { return this.settings.bounds.y; }
set width(width) { this.settings.bounds.x = width; }
set height(height) { this.settings.bounds.y = height; }
// addSubWS(subWS) {
// this.subWS.push(subWS);
// //TODO: add check to make sure subWS is in bounds of the main workspace
// //TODO: probably send a workspace update message
// }
findItemByCoordinates(x,y) {
return findLast(this.items, o => o.containsPoint(x,y));
}
handle(message, ...args) {
return this.handlers[message](...args);
}
on(event, listener) {
const type = event.toLowerCase();
this.handlers[type] = ListenerFactory.build(type, listener, this);
}
removeView(view) {
return safeRemoveById( this.views, view, ServerView );
}
removeItem(item) {
return safeRemoveById( this.items, item, ServerItem );
}
reportViews() {
return this.views.map( v => v.report() );
}
reportItems() {
return this.items.map( o => o.report() );
}
spawnView(values = {}) {
values.bounds = this.settings.bounds;
const v = new ServerView(values);
this.views.push(v);
return v;
}
spawnItem(values = {}) {
const o = new ServerItem(values);
this.items.push(o);
return o;
}
}
module.exports = WorkSpace;
<file_sep>/src/client/ShadowView.js
/*
* WAMS code to be executed in the client browser.
*
* Author: <NAME>
* |-> Date: July/August 2018
*
* Original author: <NAME>
* Other revisions and supervision: <NAME>
*
* The ShadowView class exposes a simple draw() function which renders a
* shadowy outline of the view onto the canvas.
*/
/*
* SOME NOTES ABOUT CANVAS RENDERING:
* - Avoid using shadows. They appear to kill the framerate.
*/
'use strict';
const { IdStamper, View } = require('../shared.js');
const STAMPER = new IdStamper();
const COLOURS = [
'saddlebrown',
'red',
'blue',
'darkgreen',
'orangered',
'purple',
'aqua',
'lime',
];
const symbols = Object.freeze({
align: Symbol('align'),
style: Symbol('style'),
outline: Symbol('outline'),
marker: Symbol('marker'),
});
class ShadowView extends View {
constructor(values) {
super(values);
STAMPER.cloneId(this, values.id);
}
draw(context) {
/*
* WARNING: It is *crucial* that this series of instructions be wrapped in
* save() and restore().
*/
context.save();
this[symbols.align] (context);
this[symbols.style] (context);
this[symbols.outline] (context);
this[symbols.marker] (context);
context.restore();
}
[symbols.align](context) {
context.translate(this.x,this.y);
context.rotate((Math.PI * 2) - this.rotation);
}
[symbols.style](context) {
context.globalAlpha = 0.5;
context.strokeStyle = COLOURS[this.id % COLOURS.length];
context.fillStyle = context.strokeStyle;
context.lineWidth = 5;
}
[symbols.outline](context) {
context.strokeRect( 0, 0, this.effectiveWidth, this.effectiveHeight);
}
[symbols.marker](context) {
const base = context.lineWidth / 2;
const height = 25;
context.beginPath();
context.moveTo(base,base);
context.lineTo(base,height);
context.lineTo(height,base);
context.lineTo(base,base);
context.fill();
}
}
module.exports = ShadowView;
<file_sep>/src/server/Server.js
/*
* WAMS - An API for Multi-Surface Environments
*
* Author: <NAME>
* |-> Date: July/August 2018
*
* Original author: <NAME>
* Other revisions and supervision: <NAME>
*
* A WamsServer handles the core server operations of a Wams program, including
* server establishment, and establishing Connections when new clients connect
* to the server, as well as tracking the workspace associated with the server
* so that Connections can be linked to the workspace.
*/
'use strict';
// Node packages
const http = require('http');
const os = require('os');
// npm packages.
const IO = require('socket.io');
// local project packages.
const { constants: globals, Message } = require('../shared.js');
const Connection = require('./Connection.js');
const RequestHandler = require('./RequestHandler.js');
const ServerItem = require('./ServerItem.js');
const ServerView = require('./ServerView.js');
const WorkSpace = require('./WorkSpace.js');
// local constant data
const DEFAULTS = { clientLimit: 10 };
const PORT = 9000;
function findEmptyIndex(array) {
// This is a very deliberate use of '==' instead of '==='. It should catch
// both undefined and null.
const index = array.findIndex( e => e == undefined );
return index < 0 ? array.length : index;
}
function getLocalIP() {
let ipaddr = null;
Object.values(os.networkInterfaces()).some( f => {
return f.some( a => {
if (a.family === 'IPv4' && a.internal === false) {
ipaddr = a.address;
return true;
}
return false;
});
});
return ipaddr;
};
function logConnection(id, port, status) {
const event = status ? 'connected' : 'disconnected';
console.log( 'View', id, event, 'to workspace listening on port', port );
}
class Server {
constructor(settings = {}) {
this.clientLimit = settings.clientLimit || DEFAULTS.clientLimit;
this.workspace = new WorkSpace(settings);
this.server = http.createServer(new RequestHandler());
this.port = null;
this.io = IO(this.server);
this.namespace = this.io.of(globals.NS_WAMS);
this.namespace.on('connect', this.connect.bind(this));
this.connections = [];
}
accept(socket) {
const index = findEmptyIndex(this.connections);
const cn = new Connection(index, socket, this.workspace);
this.connections[index] = cn;
socket.on('disconnect', () => this.disconnect(cn) );
logConnection(cn.view.id, this.port, true);
}
connect(socket) {
this.namespace.clients((error, clients) => {
if (error) throw error;
if (clients.length <= this.clientLimit) {
this.accept(socket);
} else {
this.reject(socket);
}
});
}
disconnect(cn) {
if (cn.disconnect()) {
this.connections[cn.index] = undefined;
new Message(Message.RM_SHADOW, cn.view).emitWith(this.namespace);
logConnection(cn.view.id, this.port, false);
} else {
console.error('Failed to disconnect:', this);
}
}
reject(socket) {
socket.emit(Message.FULL);
socket.disconnect(true);
console.log('Rejected incoming connection: client limit reached.');
}
listen(port = PORT, host = getLocalIP()) {
this.server.listen(port, host, () => {
console.log('Listening on', this.server.address());
});
this.port = port;
}
on(event, handler) {
this.workspace.on(event, handler);
}
removeItem(item) {
if (this.workspace.removeItem(item)) {
new Message(Message.RM_ITEM, item).emitWith(this.namespace);
}
}
spawnItem(itemdata) {
const item = this.workspace.spawnItem(itemdata);
new Message(Message.ADD_ITEM, item).emitWith(this.namespace);
return item;
}
update(object) {
if (object instanceof ServerItem) {
this.updateItem(object);
} else if (object instanceof ServerView) {
this.updateView(object);
}
}
updateItem(item) {
new Message(Message.UD_ITEM, item).emitWith(this.namespace);
}
updateView(view) {
const cn = this.connections.find( c => c && c.view.id === view.id );
if (cn) {
new Message(Message.UD_SHADOW, view).emitWith(cn.socket.broadcast);
new Message(Message.UD_VIEW, view).emitWith(cn.socket);
} else {
console.warn('Failed to locate connection');
}
}
}
module.exports = Server;
<file_sep>/tests/shared/ReporterFactory.test.js
/*
* Test suite for the Reporters.js module.
*/
'use strict';
const ReporterFactory = require('../../src/shared/ReporterFactory.js');
describe('ReporterFactory', () => {
const props = [
'x',
'y',
'width',
'height',
'type',
'effectiveWidth',
'effectiveHeight',
'scale',
'rotation',
];
const View = ReporterFactory(props);
test('Builds Reporter classes', () => {
expect(View.prototype).toHaveProperty('report');
expect(View.prototype).toHaveProperty('assign');
})
describe('Reporter Classes', () => {
describe('constructor(data)', () => {
test('correctly constructs expected object', () => {
let vs
expect(() => vs = new View()).not.toThrow();
expect(vs).toBeInstanceOf(View);
});
test('produces expected properties when no data provided', () => {
const vs = new View();
expect(Object.keys(vs)).toEqual(props);
});
test('uses provided data', () => {
const vs = new View({x:100, y:100, rotation: 90});
expect(Object.keys(vs)).toEqual(props);
expect(vs.x).toBe(100);
expect(vs.y).toBe(100);
expect(vs.rotation).toBe(90);
expect(vs.width).toBeNull();
expect(vs.scale).toBeNull();
});
test('does not use incorrect property names in data', () => {
const vs = new View({x: 100, y:100, z:100});
expect(Object.keys(vs)).toEqual(props);
expect(vs.x).toBe(100);
expect(vs.y).toBe(100);
expect(vs).not.toHaveProperty('z');
});
});
describe('assign(data)', () => {
const vs = new View();
test('assigns data', () => {
expect(vs.x).not.toBe(100);
vs.assign({x:100});
expect(vs.x).toBe(100);
});
test('reassigns data', () => {
expect(vs.x).toBe(100);
vs.assign({x:2});
expect(vs.x).toBe(2);
});
test('does not assign data that is not a core property', () => {
expect(vs).not.toHaveProperty('z');
vs.assign({z:100});
expect(vs).not.toHaveProperty('z');
});
test('only affects assigned properties', () => {
expect(vs.x).toBe(2);
expect(vs.y).not.toBe(1);
vs.assign({y:1});
expect(vs.x).toBe(2);
expect(vs.y).toBe(1);
});
});
describe('report()', () => {
const vs = new View({x:100, y:50, width:200, height:300});
test('reports data', () => {
const data = vs.report();
expect(Object.keys(data)).toEqual(props);
expect(data.x).toBe(100);
expect(data.y).toBe(50);
expect(data.width).toBe(200);
expect(data.height).toBe(300);
expect(data.scale).toBeNull();
});
test('does not report an ID if none exists on the object', () => {
const data = vs.report();
expect(data).not.toHaveProperty('id');
});
test('reports an immutable ID if one exists on the object', () => {
vs.id = 1;
const data = vs.report();
expect(data).toHaveProperty('id');
expect(data.id).toBe(1);
expect(data).toHaveImmutableProperty('id');
});
});
});
});
<file_sep>/README.md
# WAMS: Workspaces Across Multiple Surfaces
## Contents
* [Basic Usage](#basic-usage)
* [Server API](#server-api)
* [Handlers](#handlers)
## Basic Usage
```JavaScript
const Wams = require('../src/server');
const ws = new Wams();
// When handlers are attached and beginning items are spawned:
ws.listen(port);
```
## Server API
* [listen(\[port\[, host\]\])](#listenport-host)
* [on(event, handler)](#onevent-handler)
* [removeItem(item)](#removeitemitem)
* [spawnItem(values)](#spawnitemvalues)
* [update(object)](#updateobject)
### listen(\[port\[, host\]\])
Starts the internal server on the given port and hostname and reports the
address on which it is listening.
- __DEFAULTS:__
* __port:__ 9000
* __host:__ your local, non-loopback IPv4 address
### on(event, handler)
Registers the given handler for the given event. See Handlers below for more
information.
### removeItem(item)
Removes the given item from the workspace.
### spawnItem(values)
Spawns a new item using the given data and immediately informs all clients of
the new item. `itemdata` is an object which you fill with some or all (or none)
of the following properties:
Property | Default Value | Description
---------|---------------|------------
x|0|The position of the left side of the item.
y|0|The position of the top side of the item.
width|128|The width of the item.
height|128|The height of the item.
type|'view/background'|For use by end-user for distinguishing items.
imgsrc|''|Define the image source of the item.
blueprint|null|The Sequence blueprint for custom canvas rendering.
Note that while you can assign both and imgsrc and a blueprint to an item, if an
imgsrc is defined for the item, the blueprint will be ignored when the item is
drawn.
Blueprints are special objects capable of storing, packing, unpacking, and
executing sequences of canvas instructions. WAMS uses blueprints instead of
plain sequences for the end user API so that, if you wish, you can use special
tags instead of normal arguments in the sequence, allowing WAMS to update the
values in the item automatically. Note that only values that are in the above
properties table will be updated automatically, and that you must use the same
name as in the above table.
For more information about Blueprints and Sequences, see
[canvas-sequencer](https://www.npmjs.com/package/canvas-sequencer).
### update(object)
Updates the object with the given data, then announces the changes to all
clients. `object` can be either an item or a view.
## Handlers
Each of these handlers can be attached using the name listed below as the event
name when calling `ws.on(event, handler)`. The first argument passed to any
handler will be an object describing the view who initiated the event.
* [click](#click)
* [drag](#drag)
* [layout](#layout)
* [scale](#scale)
* [rotate](#rotate)
### click
This handler will be called whenever a user clicks in their view.
* Arguments:
* __view:__ The view which initiated the event.
* __x:__ The x coordinate at which the user clicked.
* __y:__ The y coordinate at which the user clicked.
### drag
This handler will be called whenever the user drags somewhere in their view.
* Arguments:
* __view:__ The view which initiated the event.
* __x:__ The x coordinate at which the user clicked.
* __y:__ The y coordinate at which the user clicked.
* __dx:__ The distance between the current drag and the last drag along the x
axis.
* __dx:__ The distance between the current drag and the last drag along the y
axis.
### layout
This handler will only be called once per view, when they initially connect.
* Arguments:
* __view:__ The view which initiated the event.
* __position:__ A non-zero integer identifying the 'position' of the view.
If someone disconnects, their identifier will be reused.
### scale
This handler will be called when a view zooms in or out.
* Arguments:
* __view:__ The view which initiated the event.
* __scale:__ The new zoom scale of the view. 1 is normal. 2 means 200% zoom.
0.5 means 50% zoom.
### rotate
This handler will be called when a user tries to rotate the view.
Currently only implemented for touch devices, via two-finger rotate.
* Arguments:
* __view:__ The view which initiated the event.
* __radians:__ The amount of the rotation, in radians.
<file_sep>/src/client.js
/*
* WAMS code to be executed in the client browser.
*
* Author: <NAME>
* |-> Date: July/August 2018
*
* Original author: <NAME>
* Other revisions and supervision: <NAME>
*
* This file defines the entry point for the client side of a WAMS application.
*/
'use strict';
const ClientController = require('./client/ClientController.js');
window.addEventListener(
'load',
function run() {
new ClientController(document.querySelector('canvas'));
},
{
capture: false,
once: true,
passive: true,
}
);
<file_sep>/tests/server/ListenerFactory.test.js
/*
* Test suite for ListenerFactory object.
*
* Author: <NAME>
* Date: July/August 2018
*/
'use strict';
const ListenerFactory = require('../../src/server/ListenerFactory.js');
const WorkSpace = require('../../src/server/WorkSpace.js');
describe('ListenerFactory Object', () => {
const ws = new WorkSpace();
test('Throws exception if used with "new" operator', () => {
expect(() => new ListenerFactory()).toThrow();
});
describe('.build(type, listener, workspace)', () => {
test('Throws exception if no arguments provided', () => {
expect(() => ListenerFactory.build()).toThrow();
});
test('Throws exception if invalid event type supplied', () => {
expect(() => ListenerFactory.build('resize')).toThrow();
});
describe.each([['click'],['drag'],['layout'],['scale']])('%s', (s) => {
test('Will throw if listener is invalid', () => {
expect(
() => fn = ListenerFactory.build(s, 5, ws)
).toThrow();
});
test('Returns a function', () => {
expect(
ListenerFactory.build(s, jest.fn(), ws)
).toBeInstanceOf(Function);
});
test('Calls the listener', () => {
const handler = jest.fn();
const listener = ListenerFactory.build(s, handler, ws);
const vs = ws.spawnView();
expect(() => listener(vs,1,2,3,4)).not.toThrow();
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0][0]).toBe(vs);
});
});
});
});
<file_sep>/tests/client/ClientItem.test.js
/*
* Test suite for the class.
*
* Author: <NAME>
* Date: July/August 2018
*/
'use strict';
const ClientItem = require('../../src/client/ClientItem.js');
const { CanvasBlueprint, CanvasSequencer } = require('canvas-sequencer');
describe('ClientItem', () => {
let item;
beforeEach(() => item = {
x: 42,
y: 43,
width: 800,
height: 97,
type: 'booyah',
imgsrc: 'img/scream.png',
id: 3
});
describe('constructor(data)', () => {
test('Constructs an object of the correct type', () => {
expect(new ClientItem(item)).toBeInstanceOf(ClientItem);
});
test('Throws exception if no data provided', () => {
expect(() => new ClientItem()).toThrow();
});
test('Uses input values, if provided', () => {
const ci = new ClientItem(item);
Object.keys(item).forEach( k => {
expect(ci[k]).toBe(item[k]);
});
});
test('Clones an immutable ID onto the item', () => {
const ci = new ClientItem(item);
expect(ci).toHaveImmutableProperty('id');
expect(ci.id).toBe(3);
});
test('Creates an image, if data provides an imgsrc', () => {
const ci = new ClientItem(item);
expect(ci).toHaveProperty('img');
expect(ci.img).toBeInstanceOf(Image);
expect(ci.img.src.endsWith(item.imgsrc)).toBe(true);
});
test('Does not create an image, if no imgsrc provided', () => {
const ci = new ClientItem({x:10,y:12,id:42});
expect(ci.img).toBeNull();
});
test('Creates a blueprint if one is provided', () => {
const bp = new CanvasBlueprint();
bp.fillStyle = 'red';
bp.fillRect(0,0,100,200);
item.blueprint = bp.toJSON();
let ci;
expect(() => ci = new ClientItem(item)).not.toThrow();
expect(ci.blueprint).toBeInstanceOf(CanvasBlueprint);
});
test('Does not create a blueprint if none provided', () => {
const ci = new ClientItem(item);
expect(ci.blueprint).toBeFalsy();
});
test('Builds the sequence if a blueprint was provided', () => {
const bp = new CanvasBlueprint();
bp.fillStyle = 'red';
bp.fillRect(0,0,100,200);
item.blueprint = bp.toJSON();
const ci = new ClientItem(item);
expect(ci.sequence).toBeInstanceOf(CanvasSequencer);
});
test('Does not build a sequence if no blueprint provided', () => {
const ci = new ClientItem(item);
expect(ci.sequence).toBeFalsy();
});
});
describe('draw(context)', () => {
let ctx;
beforeEach(() => ctx = new CanvasRenderingContext2D());
test('Throws an exception if no context provided', () => {
const ci = new ClientItem(item);
expect(() => ci.draw()).toThrow();
});
test('If a sequence is available, renders the sequence', () => {
const bp = new CanvasBlueprint();
bp.fillStyle = 'red';
bp.fillRect(0,0,100,200);
item.blueprint = bp.toJSON();
const ci = new ClientItem(item);
expect(() => ci.draw(ctx)).not.toThrow();
expect(ctx.fillStyle).toBe('red');
expect(ctx.fillRect).toHaveBeenCalled();
expect(ctx.fillRect).toHaveBeenLastCalledWith(0,0,100,200);
expect(ctx.drawImage).not.toHaveBeenCalled();
});
test('If no sequence, but an image is provided, draws an image', () => {
const ci = new ClientItem(item);
ci.img.loaded = true;
expect(() => ci.draw(ctx)).not.toThrow();
expect(ctx.drawImage).toHaveBeenCalledTimes(1);
expect(ctx.drawImage).toHaveBeenLastCalledWith(
ci.img, ci.x, ci.y, ci.width, ci.height
);
});
test('If no sequence or image is available, draws a blank rect', () => {
const ci = new ClientItem(item);
expect(() => ci.draw(ctx)).not.toThrow();
expect(ctx.fillRect).toHaveBeenCalled();
expect(ctx.fillRect).toHaveBeenLastCalledWith(
ci.x, ci.y, ci.width, ci.height
);
});
});
});
<file_sep>/src/client/ClientController.js
/*
* WAMS code to be executed in the client browser.
*
* Author: <NAME>
* |-> Date: July/August 2018
*
* Original author: <NAME>
* Other revisions and supervision: <NAME>
*
* The ClientController coordinates communication with the wams server. It sends
* messages based on user interaction with the canvas and receives messages from
* the server detailing changes to post to the view. This is essentially the
* controller in an MVC-esque design.
*/
'use strict';
const io = require('socket.io-client');
const {
constants: globals,
IdStamper,
Message,
MouseReporter,
NOP,
RotateReporter,
ScaleReporter,
} = require('../shared.js');
const ClientView = require('./ClientView.js');
const Interactor = require('./Interactor.js');
const STAMPER = new IdStamper();
const symbols = Object.freeze({
attachListeners: Symbol('attachListeners'),
establishSocket: Symbol('establishSocket'),
});
class ClientController {
constructor(canvas) {
this.canvas = canvas;
this.socket = null;
this.view = new ClientView({ context: this.canvas.getContext('2d') });
this.interactor = new Interactor(this.canvas, {
pan: this.pan.bind(this),
rotate: this.rotate.bind(this),
swipe: this.swipe.bind(this),
tap: this.tap.bind(this),
zoom: this.zoom.bind(this),
});
this.resizeCanvasToFillWindow();
window.addEventListener('resize', this.resize.bind(this), false);
this[symbols.establishSocket]();
}
[symbols.attachListeners]() {
const listeners = {
// For the server to inform about changes to the model
[Message.ADD_ITEM]: (...args) => this.handle('addItem', ...args),
[Message.ADD_SHADOW]: (...args) => this.handle('addShadow', ...args),
[Message.RM_ITEM]: (...args) => this.handle('removeItem', ...args),
[Message.RM_SHADOW]: (...args) => this.handle('removeShadow', ...args),
[Message.UD_ITEM]: (...args) => this.handle('updateItem', ...args),
[Message.UD_SHADOW]: (...args) => this.handle('updateShadow', ...args),
[Message.UD_VIEW]: (...args) => this.handle('assign', ...args),
// Connection establishment related (disconnect, initial setup)
[Message.INITIALIZE]: (...args) => this.setup(...args),
[Message.LAYOUT]: NOP,
// User event related
[Message.CLICK]: NOP,
[Message.DRAG]: NOP,
[Message.RESIZE]: NOP,
[Message.ROTATE]: NOP,
[Message.SCALE]: NOP,
[Message.SWIPE]: NOP,
/*
* TODO: This could be more... elegant...
*/
[Message.FULL]: () => document.body.innerHTML = 'WAMS is full! :(',
};
Object.entries(listeners).forEach( ([p,v]) => this.socket.on(p, v) );
}
[symbols.establishSocket]() {
this.socket = io.connect( globals.NS_WAMS, {
autoConnect: false,
reconnection: false,
});
this[symbols.attachListeners]();
this.socket.connect();
}
handle(message, ...args) {
this.view.handle(message, ...args);
}
pan(x, y, dx, dy) {
const mreport = new MouseReporter({ x, y, dx, dy });
new Message(Message.DRAG, mreport).emitWith(this.socket);
}
resize() {
this.resizeCanvasToFillWindow();
new Message(Message.RESIZE, this.view).emitWith(this.socket);
}
resizeCanvasToFillWindow() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.handle('resizeToFillWindow');
}
setup(data) {
STAMPER.cloneId(this, data.id);
this.canvas.style.backgroundColor = data.color;
this.handle('setup', data);
new Message(Message.LAYOUT, this.view).emitWith(this.socket);
}
rotate(radians) {
const rreport = new RotateReporter({ radians });
new Message(Message.ROTATE, rreport).emitWith(this.socket);
}
swipe(acceleration, velocity, {x,y}) {
const sreport = new SwipeReporter({ acceleration, velocity, x, y });
new Message(Message.SWIPE, sreport).emitWith(this.socket);
}
tap(x, y) {
const mreport = new MouseReporter({ x, y });
new Message(Message.CLICK, mreport).emitWith(this.socket);
}
zoom(diff) {
const scale = this.view.scale + diff;
const sreport = new ScaleReporter({ scale });
new Message(Message.SCALE, sreport).emitWith(this.socket);
}
}
module.exports = ClientController;
<file_sep>/src/client/ClientView.js
/*
* WAMS code to be executed in the client browser.
*
* Author: <NAME>
* |-> Date: July/August 2018
*
* Original author: <NAME>
* Other revisions and supervision: <NAME>
*
* The ClientView class is used for all rendering activities on the client
* side. This is essentially the view in an MVC-esque design.
*/
'use strict';
const ClientItem = require('./ClientItem.js');
const ShadowView = require('./ShadowView.js');
const {
constants: globals,
getInitialValues,
removeById,
IdStamper,
Message,
View,
} = require('../shared.js');
const DEFAULTS = Object.freeze({
x: 0,
y: 0,
rotation: globals.ROTATE_0,
scale: 1,
type: 'view/background',
});
const STATUS_KEYS = Object.freeze([
'x',
'y',
'width',
'height',
'effectiveWidth',
'effectiveHeight',
'rotation',
'scale',
]);
const REQUIRED_DATA = Object.freeze([
'id',
'items',
'views',
]);
const STAMPER = new IdStamper();
const symbols = Object.freeze({
align: Symbol('align'),
drawItems: Symbol('drawItems'),
drawShadows: Symbol('drawShadows'),
drawStatus: Symbol('drawStatus'),
wipe: Symbol('wipe'),
});
class ClientView extends View {
constructor(values = {}) {
super(getInitialValues(DEFAULTS, values));
if (values.context) this.context = values.context;
else throw 'ClientView requires a CanvasRenderingContext2D!';
this.items = [];
this.shadows = [];
document.addEventListener( Message.IMG_LOAD, this.draw.bind(this) );
}
[symbols.align]() {
/*
* WARNING: It is crucially important that the instructions below occur
* in *precisely* this order!
*/
this.context.scale(this.scale, this.scale);
this.context.rotate(this.rotation);
this.context.translate(-this.x, -this.y);
}
[symbols.drawItems]() {
this.items.forEach( o => o.draw(this.context) );
}
[symbols.drawShadows]() {
this.shadows.forEach( v => v.draw(this.context) );
}
[symbols.drawStatus]() {
const messages = STATUS_KEYS
.map( k => `${k}: ${this[k].toFixed(2)}` )
.concat([`# of Shadows: ${this.shadows.length}`]);
let ty = 40;
let tx = 20;
this.context.save();
this.context.setTransform(1,0,0,1,0,0);
this.context.font = '18px Georgia';
messages.forEach( m => {
this.context.fillText(m, tx, ty);
ty += 20;
});
this.context.restore();
}
[symbols.wipe]() {
this.context.clearRect(0, 0, window.innerWidth, window.innerHeight);
}
addItem(values) {
this.items.push(new ClientItem(values));
}
addShadow(values) {
this.shadows.push(new ShadowView(values));
}
draw() {
this.context.save();
this[symbols.wipe]();
this[symbols.align]();
this[symbols.drawItems]();
this[symbols.drawShadows]();
this[symbols.drawStatus]();
this.context.restore();
}
handle(message, ...args) {
this[message](...args);
this.draw();
}
removeItem(item) {
return removeById( this.items, item );
}
removeShadow(shadow) {
return removeById( this.shadows, shadow );
}
resizeToFillWindow() {
this.width = window.innerWidth;
this.height = window.innerHeight;
this.effectiveWidth = this.width / this.scale;
this.effectiveHeight = this.height / this.scale;
}
setup(data) {
REQUIRED_DATA.forEach( d => {
if (!data.hasOwnProperty(d)) throw `setup requires: ${d}`;
});
STAMPER.cloneId(this, data.id);
data.views.forEach( v => v.id !== this.id && this.addShadow(v) );
data.items.forEach( o => this.addItem(o) );
}
update(container, data) {
const object = this[container].find( o => o.id === data.id );
if (object) object.assign(data);
else console.warn(`Unable to find in ${container}: id: `, data.id);
}
updateItem(data) {
this.update('items', data);
}
updateShadow(data) {
this.update('shadows', data);
}
}
module.exports = ClientView;
|
1cbad678207f13a06f63c345addcdd0cd0cd85f8
|
[
"Markdown",
"Shell",
"JavaScript"
] | 29 |
Markdown
|
mvanderkamp/WAMS-API
|
e7dfb7cea5b2145eb106b9531543e08f5c0d2a4b
|
ad1ba4af989b329fc790b0fbb3e6f3d53b08bdc0
|
refs/heads/master
|
<file_sep>import { Container, Button, Header, Icon } from 'semantic-ui-react';
import React, { Component } from 'react';
import StripeCheckout from 'react-stripe-checkout';
import axios from 'axios';
import { hasActiveSubscription } from '../actions/billing';
const w_id = '5add171bf82fa1509c5407d9';
class Billing extends Component {
constructor() {
super();
this.state = {
w_id: '',
active: false,
};
}
onToken = token => {
axios.post('http://localhost:3031/stripe', { w_id, token }).then(res => {
alert('Payment Successful');
});
};
componentWillMount() {
this.setState({ w_id: localStorage.getItem('doc_id') });
if (hasActiveSubscription(w_id)) {
this.setState({ active: true });
}
}
render() {
if (this.state.active) {
return (
<Container>
<Header as="h2" icon textAlign="center">
<Icon name="checkmark" circular color="green" />
<Header.Content>
Looks like your Subscription is still active!!
</Header.Content>
</Header>
</Container>
);
} else {
return (
<Container>
<StripeCheckout
name="Hey Team"
description="30 Day Subscription - $9.99"
amount={999}
token={this.onToken}
stripeKey="<KEY>"
>
{' '}
<Header as="h2" icon textAlign="center">
<Icon name="close" circular color="red" />
<Header.Content>
Looks like your Subscription as run out
</Header.Content>
<Header.Content>Click here to re-activate!!</Header.Content>
<Header.Content>
<Button color="green"> Activate </Button>
</Header.Content>
</Header>
</StripeCheckout>
</Container>
);
}
}
}
export default Billing;
<file_sep>import axios from 'axios';
const URL = '';
const w_id = '5add171bf82fa1509c5407d9';
export const saveConversation = async c => {
// console.log(c);
try {
await axios.post('http://localhost:3031/conversation/create', {
w_id,
c,
});
alert('saved');
} catch (error) {}
};
export const updateConversation = async (c_id, c) => {
// console.log(c);
try {
await axios.put('http://localhost:3031/conversation/update', {
c_id,
c,
});
alert('saved');
} catch (error) {}
};
export const findConversation = async c_id => {
// console.log(c);
try {
const res = await axios.post('http://localhost:3031/conversation/find', {
c_id,
});
return res;
alert('conversation found', res);
} catch (error) {}
};
export const allConversations = async () => {
try {
const res = await axios.post('http://localhost:3031/conversation/all', {
w_id,
});
return res;
} catch (error) {}
};
export const deleteConversation = async (w_id, c_id) => {
try {
await axios.post('http://localhost:3031/conversation/delete', {
w_id,
c_id,
});
} catch (error) {}
};
<file_sep>const { WebClient } = require('@slack/client');
const colors = require('colors');
const util = require('util');
const initializeConversation = require('./helpers/initializeConversation');
const createQuestion = require('./helpers/createQuestion');
const Conversation = require('../models/conversationModel');
const Workspace = require('../models/workspaceModel');
const Question = require('../models/questionModel');
const Response = require('../models/responseModel');
const Member = require('../models/memberModel');
const createConversation = async (req, res) => {
const { c, w_id } = req.body;
// console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
// console.log(c);
// console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
await c.members.forEach(m => {
console.log(typeof m);
});
// find all members and add a conversation to member object
/** Golden */
// console.log('here'.red);
const members = await Member.find({
id: { $in: c.members },
});
const conversation = await new Conversation({
workspace: w_id,
members: members,
title: c.title,
broadcast: c.broadcast,
questions: c.questions,
schedule: c.schedule,
});
await conversation.save();
// questions.forEach(q => {
// console.log('calling createQuestion');
// createQuestion(w_id, conversation._id, q);
// });
console.log('push conversation');
await Workspace.findByIdAndUpdate(w_id, {
$push: { conversations: conversation._id },
})
.then('pushed conversation to workspace')
.catch(console.error);
res.send(conversation);
};
const updateExistingConversation = async (req, res) => {
const { c_id, c } = req.body;
/** Golden */
const members = await Member.find({
id: { $in: c.members },
});
await Conversation.findByIdAndUpdate(c_id, {
members: members,
title: c.title,
questions: c.questions,
schedule: c.schedule,
})
.then(response => {
console.log(response);
res.send('OK');
})
.catch(console.error);
};
const deleteConversation = async (req, res) => {
const { w_id, c_id } = req.body;
await Conversation.findByIdAndRemove(c_id);
await Workspace.findByIdAndUpdate(w_id, {
$pull: { conversations: c_id },
});
res.send('OK');
};
const getMemberFromId = id => {
const member = Member.findOne({ id: id });
if (member.id) {
return member.id;
} else {
return false;
}
};
const getConversation = async (req, res) => {
const { c_id } = req.body;
await Conversation.findById(c_id)
.populate('members')
.populate('responses')
.then(c => {
res.json(c);
})
.catch(console.error);
};
const editConversation = async (req, res) => {
const { c_id, c } = req.body;
const dbMembers = [];
await c.members.forEach(m => {
const foundMemberId = getMemberFromId(m);
if (foundMemberId) {
dbMembers.push(foundMemberId);
}
});
const conversation = await Conversation.findByIdAndUpdate(c_id, {
title: c.title,
members: dbMembers,
questions: c.questions,
schedule: c.schedule,
responses: [],
});
res.send('OK');
};
const allConversations = async (req, res) => {
const { w_id } = req.body;
/** Golden */
Workspace.findById(w_id)
.populate({
path: 'conversations',
populate: { path: 'responses' },
})
.populate({
path: 'conversations',
populate: { path: 'members' },
})
.then(w => {
res.send(w.conversations);
})
.catch(console.error);
};
const startConversation = async (c_id, m) => {
initializeConversation(c_id, m);
};
// const startConversation = async (req, res) => {
// const { c_id, members } = req.body;
// members.forEach(m_id => {
// initializeConversation(c_id, m_id);
// });
// res.send('probably worked');
// };
const updateConversation = async body => {
if (body.event.bot_id) {
return;
}
const web = new WebClient(process.env.XOXB);
const dm = await web.im.open({ user: body.event.user });
const history = await web.im.history({ channel: dm.channel.id, count: 2 });
if (history.messages[1].user === body.event.user) {
return;
}
const [q_count, c_id] = history.messages[1].attachments[0].fallback.split(
','
);
const member = await Member.findOne({ id: body.event.user });
const conversation = await Conversation.findById(c_id).populate('responses');
let numResponses = 0;
conversation.responses.forEach(r => {
if (r.member.toString() === member._id.toString()) {
numResponses++;
}
});
if (numResponses === conversation.questions.length - 1) {
const newResponse = await new Response({
conversation: c_id,
member: member._id,
time_stamp: body.event.ts,
response: body.event.text,
});
await newResponse.save();
await Conversation.findByIdAndUpdate(c_id, {
$push: { responses: newResponse._id },
});
const cr = await Conversation.findById(c_id).populate('responses');
const broadcast = await web.im.open({ user: cr.broadcast });
let certainMemberResponses = [];
let questionIndex = 0;
cr.responses.forEach(r => {
let attachmentObj = {};
if (member._id.toString() === r.member.toString()) {
attachmentObj = {
fallback: `${conversation.questions[questionIndex]}\n${r.response}`,
text: `${r.response}`,
title: `${conversation.questions[questionIndex]}`,
color: 'c0dadb',
mrkdwn_in: ['text'],
};
certainMemberResponses.push(attachmentObj);
questionIndex++;
}
});
web.chat
.postMessage({
channel: broadcast.channel.id,
text: `Hey! This is ${member.real_name}'s standup for ${cr.title}:`,
attachments: certainMemberResponses,
})
.then(res => {})
.catch(console.error);
return;
} else if (numResponses < conversation.questions.length - 1) {
const newResponse = await new Response({
conversation: c_id,
member: member._id,
time_stamp: body.event.ts,
response: body.event.text,
});
await newResponse.save();
await Conversation.findByIdAndUpdate(c_id, {
$push: { responses: newResponse._id },
});
web.chat
.postMessage({
channel: dm.channel.id,
text: `${conversation.questions[numResponses + 1]}`,
attachments: [
{
fallback: `${conversation.questions.length},${c_id}`,
},
],
})
.then(res => {})
.catch(console.error);
return;
} else if (numResponses === conversation.questions.length) {
return;
}
};
const im = (req, res) => {
updateConversation(req.body);
/** Golden */
const stuff = util.inspect(req.body, false, null);
console.log(stuff);
res.send(req.body);
};
module.exports = {
im,
getConversation,
editConversation,
allConversations,
startConversation,
createConversation,
deleteConversation,
updateConversation,
updateExistingConversation,
};
<file_sep>import { connect } from 'react-redux';
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { findUsers } from '../actions/FindUsers';
import { saveConversation } from '../actions/Conversation';
import {
Button,
Form,
Grid,
Header,
Image,
Message,
Segment,
Label,
Container,
Checkbox,
Input,
List,
Radio,
Select,
TextArea,
Dropdown,
FormGroup,
Search,
Icon,
Accordion,
Popup,
} from 'semantic-ui-react';
const options = [
{ key: 'a', text: 'AM', value: 'AM' },
{ key: 'p', text: 'PM', value: 'PM' },
];
class New extends Component {
constructor() {
super();
this.state = {
searchResults: [],
questions: [],
title: '',
schedule: {
mon: false,
tue: false,
wed: false,
thu: false,
fri: false,
sat: false,
sun: false,
time: '',
modifier: 'AM',
tz: '',
},
members: [],
localMembers: [],
questionToAdd: '',
};
this.handleUserSearch = this.handleUserSearch.bind(this);
}
handleAddUser = (e, d) => {
console.log('result', d.result);
this.state.members.push(d.result.id);
this.state.localMembers.push(d.result);
this.setState({ localMembers: this.state.localMembers });
this.setState({ members: this.state.members });
console.log(this.state.members);
};
handleUserSearch = async e => {
// console.log(e.target.value);
const users = await findUsers(e.target.value);
this.setState({ searchResults: users.data });
// console.log(this.state.searchResults);
};
handleUpdateSchedule = (e, d) => {
// console.log(d.label.toLowerCase());
const day = d.label.toLowerCase();
const checked = !this.state.schedule[day];
Object.keys(this.state.schedule).forEach(key => {
if (key === day) {
this.state.schedule[day] = checked;
}
});
this.setState({ schedule: this.state.schedule });
};
handleAddQuestion = (e, d) => {
this.state.questions.push(this.state.questionToAdd);
this.setState({ questions: this.state.questions });
this.setState({ questionToAdd: '' });
};
handleUpdateQuestionToAdd = (e, d) => {
this.setState({ questionToAdd: e.target.value });
console.log(this.state.questionToAdd);
};
handleRemoveQuestion = (e, d) => {
console.log(d.children);
const questions = [];
this.state.questions.forEach(p => {
if (p !== d.children) {
questions.push(p);
}
});
console.log(questions);
this.setState({ questions });
};
handleRemoveParticipant = (e, d) => {
console.log('event', e);
console.log('data', d);
const localMembers = [];
const members = [];
this.state.localMembers.forEach(q => {
if (q.real_name !== d.children[1]) {
localMembers.push(q);
members.push(q.id);
}
});
console.log(members);
this.setState({ localMembers });
this.setState({ members });
};
handleUpdateTitle = async (e, d) => {
this.state.title = e.target.value;
await this.setState({ title: this.state.title });
// console.log(this.state.title);
};
handleModifier = async (e, d) => {
// console.log(e.target.value, d.value);
await this.setState({ schedule: { modifier: d.value } });
console.log(this.state);
};
handleSave = async () => {
console.log(this.state);
await saveConversation(this.state);
this.props.history.push('/dashboard/conversations');
};
handleUpdateTime = async e => {
await this.setState({ schedule: { time: e.target.value } });
};
render() {
const { schedule } = this.state;
return (
<div className="form-group">
<Container>
<Form>
<Form.Group widths="equal">
<Form.Field
control={Input}
value={this.state.title}
placeholder="Enter a title for this conversation"
onChange={(e, d) => this.handleUpdateTitle(e, d)}
style={{ maxWidth: '500px' }}
/>
</Form.Group>
<Form.Group>
<label>Schedule: </label>
</Form.Group>
<Form.Group inline>
<Form.Field
control={Checkbox}
label="Mon"
value="1"
checked={this.state.schedule.mon}
onChange={(e, d) => this.handleUpdateSchedule(e, d)}
/>
<Form.Field
control={Checkbox}
label="Tue"
value="1"
checked={this.state.schedule.tue}
onChange={(e, d) => this.handleUpdateSchedule(e, d)}
/>
<Form.Field
control={Checkbox}
label="Wed"
value="1"
checked={this.state.schedule.wed}
onChange={(e, d) => this.handleUpdateSchedule(e, d)}
/>
<Form.Field
control={Checkbox}
label="Thu"
value="1"
checked={this.state.schedule.thu}
onChange={(e, d) => this.handleUpdateSchedule(e, d)}
/>
<Form.Field
control={Checkbox}
label="Fri"
value="1"
checked={this.state.schedule.fri}
onChange={(e, d) => this.handleUpdateSchedule(e, d)}
/>
<Form.Field
control={Checkbox}
label="Sat"
value="1"
checked={this.state.schedule.sat}
onChange={(e, d) => this.handleUpdateSchedule(e, d)}
/>
<Form.Field
control={Checkbox}
label="Sun"
value="1"
checked={this.state.schedule.sun}
onChange={(e, d) => this.handleUpdateSchedule(e, d)}
/>
</Form.Group>
<Form.Group inline>
<Input
onChange={this.handleUpdateTime}
label={
<Dropdown
defaultValue="AM"
options={options}
onChange={(e, d) => this.handleModifier(e, d)}
/>
}
labelPosition="right"
placeholder="Time"
/>
</Form.Group>
<Form.Group>
<label>Questions: </label>
</Form.Group>
<Form.Group>
<Form.Input
// action={{ icon: 'plus', color: 'green' }}
placeholder="Questions"
onChange={(e, d) => this.handleUpdateQuestionToAdd(e, d)}
/>
<Form.Button
circular
color="green"
icon="plus"
onClick={(e, d) => this.handleAddQuestion(e, d)}
// onClick={(e, d) => this.handleAddQuestion(e, d)}
/>
</Form.Group>
{this.state.questions.map(q => {
return (
<Form.Group>
<Popup
trigger={
<Label
as="a"
size="large"
onClick={(e, d) => this.handleRemoveQuestion(e, d)}
>
{q}
{/* <Icon
name="delete"
onClick={(e, d) => this.handleRemoveQuestion(e, d)}
/> */}
</Label>
}
content="Click to remove from list"
// onClick={(e, d) => this.handleRemoveQuestion(e, d)}
/>
</Form.Group>
);
})}
<Form.Group>
<label>localMembers: </label>
</Form.Group>
<Form.Group inline>
<Search
results={this.state.searchResults}
// icon="search"
placeholder="search"
onSearchChange={e => this.handleUserSearch(e)}
onResultSelect={(e, d) => this.handleAddUser(e, d)}
/>
</Form.Group>
<Form.Group inline>
{this.state.localMembers.map(p => {
return (
<Popup
trigger={
<Label
as="a"
size="large"
onClick={(e, d) => this.handleRemoveParticipant(e, d)}
>
<img src={p.image} />
{`${p.real_name}`}
</Label>
}
content="Click to remove from list"
/>
);
})}
</Form.Group>
<Form.Field
control={Button}
onClick={(e, d) => this.handleSave(e, d)}
>
Save
</Form.Field>
</Form>
</Container>
</div>
);
}
}
const mapStateToProps = state => {
return {
// user: state.user,
};
};
/** Golden */
export default withRouter(connect(mapStateToProps, {})(New));
<file_sep>import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import {
Container,
Header,
Grid,
Label,
List,
Card,
Item,
} from 'semantic-ui-react';
import { findConversation } from '../actions/Conversation';
class ConversationView extends Component {
constructor() {
super();
this.state = {};
}
componentWillMount() {
const url = new URL(window.location.href);
const params = new URLSearchParams(url.search.slice(1));
const id = params.get('c_id');
findConversation(id)
.then(c => this.setState(c.data))
.catch(console.error);
}
render() {
console.log(this.state);
if (this.state.members) {
return (
<Container>
<Header>Participants</Header>
<Grid stackable={true} doubling={true} columns={6}>
{this.state.members.map((m, i) => {
return (
<Label key={i}>
<img src={m.image} /> {' '}
{`${m.real_name}`}
</Label>
);
})}
</Grid>
<Header>Questions</Header>
<List>
{this.state.questions.map((q, i) => {
return (
<List.Item key={i}>
<Label>{q}</Label>
</List.Item>
);
})}
</List>
<Header>Schedule</Header>
<Header>Responses</Header>
<Card.Group stackable={true} doubling={true} itemsPerRow={3}>
{this.state.members.map((m, i) => {
return (
<Card key={i}>
<Card.Content>
<Item>
<Item.Content>
<img
style={{ height: '30px', width: '30px' }}
src={m.image}
/>
<Item.Header>{m.real_name}</Item.Header>
<Item.Meta>date</Item.Meta>
</Item.Content>
</Item>
</Card.Content>
</Card>
);
})}
</Card.Group>
</Container>
);
} else {
return <div />;
}
}
}
export default withRouter(ConversationView);
<file_sep>import React, { Component } from 'react';
import { Route, BrowserRouter as Router } from 'react-router-dom';
// import New from './components/New';
import Login from './components/Login';
import Dashboard from './components/Dashboard';
// import SidebarMenu from './components/SidebarMenu';
// import { Sidebar, Segment, Button, Menu } from 'semantic-ui-react';
class App extends Component {
// state = { visible: false };
// toggleVisibility = () => {
// this.setState({ visible: !this.state.visible });
// };
render() {
// const { visible } = this.state;
return (
<div style={{ height: '100vh' }}>
<Route exact path="/" component={Login} />
<Route path="/dashboard" component={Dashboard} />
</div>
);
}
}
export default App;
<file_sep>import axios from 'axios';
const URL = '';
const w_id = '5add171bf82fa1509c5407d9';
// export const saveConversation = async c => {
// // console.log(c);
// try {
// const res = await axios.post('http://localhost:3031/stripe', {
// w_id,
// token,
// });
// alert('Payment Successful');
// } catch (error) {}
// };
export const hasActiveSubscription = async w_id => {
try {
const res = await axios.post('http://localhost:3031/auth/active', {
w_id,
});
return res;
} catch (error) {
console.error;
}
};
<file_sep>const request = require('request');
const Workspace = require('../models/workspaceModel');
const createWorkspace = require('./helpers/createWorkspace');
const colors = require('colors');
const login = (req, res) => {
if (!req.query.code) {
// access denied
return;
}
var data = {
form: {
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
redirect_uri: process.env.REDIRECT_AUTH,
code: req.query.code,
},
};
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>'.green);
request.post('https://slack.com/api/oauth.access', data, async function(
error,
response,
body
) {
if (!error && response.statusCode == 200) {
body = JSON.parse(body);
const workspace = await Workspace.findOne({
'info.id': body.team_id,
});
if (workspace) {
console.log('workspace exists');
return res.redirect(
`${process.env.REDIRECT_URI}/?doc_id=${workspace._id}`
);
} else {
await createWorkspace(body, req, res);
}
}
});
};
const addBot = (req, res) => {
if (!req.query.code) {
// access denied
return;
}
var data = {
form: {
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
redirect_uri: process.env.REDIRECT_BOT,
code: req.query.code,
},
};
request.post('https://slack.com/api/oauth.access', data, async function(
error,
response,
body
) {
if (!error && response.statusCode == 200) {
body = JSON.parse(body);
console.log(body);
const workspace = await Workspace.findOne({ 'info.id': body.team_id });
await Workspace.findOneAndUpdate({
'info.id': body.team_id,
$set: {
bot: {
access_token: body.access_token,
user_id: body.user_id,
team_name: body.team_name,
team_id: body.team_id,
bot_user_id: body.bot.bot_user_id,
bot_access_token: body.bot.bot_access_token,
},
},
})
.then(() => {
return res.redirect(
`${process.env.REDIRECT_URI}/?doc_id=${workspace._id}`
);
})
.catch(console.error);
}
});
};
const getAllMembers = async (req, res) => {
const { w_id } = req.body;
const workspace = await Workspace.findById(w_id).populate('members');
res.json(workspace.members);
};
const findMembers = async (req, res) => {
// console.log('trying to find member by ', req.body.searchTerm);
const { w_id, searchTerm } = req.body;
console.log(w_id, searchTerm);
const regex = new RegExp(`${searchTerm}`, 'i');
const searchResult = [];
const workspace = await Workspace.findById(w_id).populate('members');
workspace.members.forEach(m => {
if (m.real_name) {
if (m.real_name.match(regex)) {
const memberShort = {
id: m.id,
image: m.image,
color: m.color,
title: m.real_name,
real_name: m.real_name,
description: m.name,
};
searchResult.push(memberShort);
}
}
});
// console.log(searchResult);
res.json(searchResult);
};
const hasActiveSubstription = async (req, res) => {
const { w_id } = req.body;
const workspace = await Workspace.findById(w_id);
res.send(workspace.info.active);
};
module.exports = {
login,
addBot,
getAllMembers,
findMembers,
hasActiveSubstription,
};
<file_sep>import React, { Component } from 'react';
import { Route, withRouter } from 'react-router-dom';
import New from './New';
import Edit from './Edit';
import Login from './Login';
import Billing from './Billing';
import Preferences from './Preferences';
import SidebarMenu from './SidebarMenu';
import Conversations from './Conversations';
import ConversationView from './ConversationView';
import { Sidebar, Segment, Button, Menu } from 'semantic-ui-react';
class Dashboard extends Component {
state = { visible: false };
toggleVisibility = () => {
this.setState({ visible: !this.state.visible });
};
componentWillMount() {
console.log(localStorage.doc_id);
if (!localStorage.doc_id) {
const url = new URL(window.location.href);
const params = new URLSearchParams(url.search.slice(1));
const id = params.get('doc_id');
localStorage.setItem('doc_id', id);
}
}
handleLogout = (e, d) => {
console.log(e, d);
localStorage.setItem('doc_id', null);
this.props.history.push('/');
};
render() {
const { visible } = this.state;
if (localStorage.doc_id === 'null') {
this.props.history.push('/');
return <div />;
} else {
return (
<div style={{ height: '100vh' }}>
<Sidebar.Pushable>
<Sidebar animation="push" vertical visible={visible} as={Menu}>
<SidebarMenu toggle={this.toggleVisibility} />
</Sidebar>
<Sidebar.Pusher>
<Menu
secondary
style={{
marginTop: '10px',
marginLeft: '110px',
marginRight: '3em',
}}
>
<Menu.Item
name="Menu"
icon="list layout"
onClick={this.toggleVisibility}
/>
<Menu.Item
name="Log out"
position="right"
onClick={(e, d) => this.handleLogout(e, d)}
/>
</Menu>
<Route
exact
path="/dashboard/conversations/new"
component={New}
style={{ margin: '5em' }}
/>
{/* <Route exact path="/dashboard" component={Overview} /> */}
<Route
exact
path="/dashboard/conversations"
component={Conversations}
/>
<Route
exact
path="/dashboard/conversations/edit"
component={Edit}
/>
<Route exact path="/dashboard/billing" component={Billing} />
<Route
exact
path="/dashboard/conversation"
component={ConversationView}
/>
<Route
exact
path="/dashboard/preferences"
component={Preferences}
/>
</Sidebar.Pusher>
</Sidebar.Pushable>
</div>
);
}
}
}
export default withRouter(Dashboard);
|
9d8cdfaafea7dd8cd4803a3f9febf0d4d4ecef4c
|
[
"JavaScript"
] | 9 |
JavaScript
|
CosmonautJones/Ham-Standwich
|
9be42091725fbf57a7f29e7572159bf46bc3793a
|
ad55e9b3d554a03b40ed20faf7a0b1efabdbec4e
|
refs/heads/master
|
<file_sep>const ObjectId = require('mongodb').ObjectId;
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/mydb";
function resolveError(err, responseObj) {
if (err) responseObj.status(400).send(err);
}
function addEntry(entryObj, responseObj) {
// connect to db instance
MongoClient.connect(url, (err, db) => {
if (err) {
responseObj.status(400).send(err)
}
else {
const dbo = db.db("mydb");
// ensure collection exists
dbo.createCollection("entries", (err, res) => {
if (err) {
responseObj.status(400).send(err);
db.close();
}
else {
// add datetime stamp to entry
const now = new Date();
entryObj.createDate = now;
entryObj.updateDate = now;
// add new entry to collection
dbo.collection("entries").insertOne(entryObj, (err, res) => {
if (err) {
responseObj.status(400).send(err)
db.close();
}
else {
console.info(res);
responseObj.status(200).send({"insertedId": res.insertedId});
db.close();
}
});
}
});
}
});
}
function getEntries(responseObj) {
// connect to db instance
MongoClient.connect(url, (err, db) => {
if (err) {
responseObj.status(400).send(err)
}
else {
var dbo = db.db("mydb");
// ensure collection exists
dbo.createCollection("entries", (err, res) => {
if (err) {
responseObj.status(400).send(err)
db.close();
}
else {
// sort ascending by date created
const sort = { createDate: 1 }
// find all entries in collection
dbo.collection("entries").find({}).sort(sort).toArray((err, result) => {
if (err) {
responseObj.status(400).send(err)
db.close();
}
else {
console.info(result);
responseObj.status(200).send({"entries": result});
db.close();
}
});
}
});
}
});
}
function editEntry(entryId, entryObj, responseObj) {
// connect to db instance
MongoClient.connect(url, (err, db) => {
if (err) {
responseObj.status(400).send(err);
}
else {
var dbo = db.db("mydb");
// specify id of entry to update
const q = { _id: ObjectId(entryId) };
// setup new values
const now = new Date();
const newVals = { $set: { subject: entryObj.subject, body: entryObj.body, updateDate: now } }
dbo.collection("entries").updateOne(q, newVals, (err, obj) => {
if (err) {
responseObj.status(400).send(err);
db.close();
}
else {
console.log(obj);
obj.modifiedCount > 0 ?
responseObj.status(200).send({
"updatedId": entryId
})
:
resolveError(new Error("No such entry with id " + entryId), responseObj);
db.close();
}
});
}
});
}
function deleteEntry(entryId, responseObj) {
// connect to db instance
MongoClient.connect(url, (err, db) => {
if (err) {
responseObj.status(400).send(err);
}
else {
var dbo = db.db("mydb");
// specify id of entry to delete
const q = { _id: ObjectId(entryId) };
dbo.collection("entries").deleteOne(q, (err, obj) => {
if (err) {
responseObj.status(400).send(err);
db.close();
}
else {
console.log(obj);
obj.deletedCount > 0 ? responseObj.status(200).send({"deleted": obj}) : resolveError(new Error("No such entry with id " + entryId), responseObj);
db.close();
}
});
}
});
}
function deleteAllEntries(responseObj) {
MongoClient.connect(url, (err, db) => {
if (err) {
responseObj.status(400).send(err);
}
else {
var dbo = db.db("mydb");
dbo.collection("entries").remove((err, obj) => {
if (err) {
responseObj.status(400).send(err)
db.close();
}
else {
obj ? responseObj.status(200).send({"deleted": obj}) : resolveError(new Error("Something went wrong..."), responseObj);
db.close();
}
});
}
});
}
module.exports = {
addEntry,
getEntries,
editEntry,
deleteEntry,
deleteAllEntries,
}<file_sep>const cors = require('cors')
const express = require('express');
const bodyParser = require('body-parser');
const { addEntry, getEntries, deleteEntry, deleteAllEntries, editEntry } = require('./db.connection')
const app = express();
app.use(
bodyParser.urlencoded({
extended: true,
})
);
app.use(bodyParser.json());
app.use(cors());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST');
res.setHeader(
'Access-Control-Allow-Headers',
'X-Requested-With, content-type'
);
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.get('/entry', (req, res, next) => {
getEntries(res);
});
app.post('/entry', (req, res, next) => {
addEntry(req.body, res);
});
app.patch('/entry/:entryId', (req, res, next) => {
editEntry(req.params.entryId, req.body, res);
});
app.delete('/entry/:entryId', (req, res, next) => {
deleteEntry(req.params.entryId, res);
});
app.delete('/entry', (req, res, next) => {
deleteAllEntries(res);
});
const PORT = process.env.PORT || 3000
app.listen(PORT, function() {
console.log('Server listening on ' + PORT)
})<file_sep># JournalAPI
Simple NODE.js API to be consumed by JournalApp for CS 406
## To run locally
Install MongoDB and start mongod service. Instructions can be found <a href="https://docs.mongodb.com/manual/installation/">here</a>.
Clone repo:<br/>
`git clone https://github.com/taylorrgriffin/JournalAPI.git`
Install dependencies and start API:<br/>
`npm install`<br/>
`npm start`
## Avaliable Endpoints
_Fetch all entries:_<br/>
`GET /entry`
_Add entry:_<br/>
`POST /entry` with request body like:<br/>
`{
"subject:" "Example Subject Line",
"body:" "Example content..."
}`
_Update entry:_<br/>
`PATCH /entry/entryId` with request body like:<br/>
`{
"subject:" "Example Subject Line",
"body:" "Example content..."
}`
_Delete entry:_<br/>
`DELETE /entry/entryId`
_Delete all entries:_<br/>
`DELETE /entry`
|
6406591590a8817497b42f4e918b05d9fd8d555b
|
[
"Markdown",
"JavaScript"
] | 3 |
Markdown
|
taylorrgriffin/JournalAPI
|
6931b174465160f31032d9684c7b8c0a93054603
|
1d1fd1e212cb8cc5e2db518da1c122c4026d7f57
|
refs/heads/master
|
<file_sep>using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace imgify
{
class Program
{
private static string _source, _dest;
private static int _width, _quality;
static void Main(string[] args)
{
if(args.Length < 2)
{
Console.WriteLine("Sorry, this app requires both a source file and a destination folder. Please enter them after the app file name.");
} else if( args.Length == 2)
{
try {
_source = args[0];
_dest = args[1];
}catch (Exception e)
{
Console.WriteLine("Sorry There is an issue with the file path(s) Provided. Try Quoting the path(s) \n " + e.ToString());
}
_width = 300;
_quality = 75;
/*Console.WriteLine(_source);
Console.WriteLine(_dest);
Console.WriteLine(_width);
Console.ReadLine();*/
ReadImgFile(_source, _dest, _width, _quality);
}else if( args.Length == 3)
{
_source = args[0];
_dest = args[1];
_width = int.Parse(args[2]);
_quality = 75;
/*Console.WriteLine(_source);
Console.WriteLine(_dest);
Console.WriteLine(_width);
Console.WriteLine(_quality);
Console.ReadLine();*/
ReadImgFile(_source, _dest, _width, _quality);
}else if (args.Length == 4)
{
_source = args[0];
_dest = args[1];
_width = int.Parse(args[2]);
_quality = int.Parse(args[3]);
/*Console.WriteLine(_source);
Console.WriteLine(_dest);
Console.WriteLine(_width);
Console.WriteLine(_quality);
Console.ReadLine();*/
}
}
private static void ReadImgFile(string _sourceLocation, string _destLocation, int _w, int _q)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo ici = null;
foreach(ImageCodecInfo codec in codecs)
{
if(codec.MimeType == "image/jpeg")
{
ici = codec;
}
}
EncoderParameters ep = new EncoderParameters();
ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)_q);
Image img = Bitmap.FromFile(_sourceLocation);
Console.WriteLine(img.Size);
int h = img.Size.Height, w = img.Size.Width;
Size nSize = new Size(_w, ((h * _w) / w));
Console.Write("Working on: " + _sourceLocation + "\nCompressing by a factor of: " + _q + "\nResizing to: " + nSize);
/* Console.WriteLine(nSize);
Console.ReadLine();*/
img = ResizeImage(img, nSize);
try {
img.Save(_destLocation, ici, ep);
}catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static Image ResizeImage(Image img, Size newSize)
{
Image newImg = new Bitmap(newSize.Width, newSize.Height);
using(Graphics Gfx = Graphics.FromImage((Bitmap)newImg))
{
Gfx.DrawImage(img, new Rectangle(Point.Empty, newSize));
}
return newImg;
}
}
}
<file_sep># imgify-Csharp
Image Resize and Compression tool (Scriptable)
# Imgify in C Sharp
Simple tool to compress and resize images
###Usage
`imgify.exe <path to source file> <path to destination> <desired width> <desired compression>`
Width and Compression is optional, and defaults are 300 for width, and 75 for compression.
Resizing automatically keeps the aspect ratio, and compression is from poor, 0, to High, 100
|
17cb07c8d6add756874ef96f35c90d6eacade7fe
|
[
"C#",
"Markdown"
] | 2 |
C#
|
cjrutherford/imgify-Csharp
|
7214339573eb0e0a5a5e3c006ea71edc60d42c81
|
24bf7dce0ceb44b470776c749a1de80e5ae84bdf
|
refs/heads/master
|
<file_sep>from flask import Flask, jsonify
from credentials import value
from flask_ask import Ask, statement, question
from flask_cors import CORS
import firebase_admin
from firebase_admin import credentials, db
import logging
from datetime import datetime
app = Flask(__name__)
CORS(app)
ask = Ask(app, "/dogpictures")
@app.route('/')
def homepage():
return 'hi you, how ya doin?'
# admin json key values exported from firebase portal
cred = credentials.Certificate(value)
default_app = firebase_admin.initialize_app(cred, {
'databaseURL': 'https://alexa-dogpictures.firebaseio.com/'
})
app.config.update(dict(
DEBUG=True,
RDB_HOST='localhost',
RDB_PORT='28015',
RDB_DB='dogpictures'
))
def update_dog(number):
ref = db.reference('DogPictures').child('1')
print(ref)
values = {
'dogPicture': number
}
ref.update(values)
return 'success!'
@app.route('/getdog')
def getdog():
try:
ref = db.reference('DogPictures').child('1').get()
print(ref)
result = jsonify(ref)
return result
except Exception as err:
return {'error': err.message}
log = logging.getLogger()
log.addHandler(logging.StreamHandler())
log.setLevel(logging.DEBUG)
logging.getLogger("flask_ask").setLevel(logging.DEBUG)
@ask.launch
def start_skill():
welcome_message = 'Welcome to dog pictures, you can ask for a dog picture by saying dog number 1'
return question(welcome_message)
@ask.intent("AMAZON.NoIntent")
def no_intent():
bye_text = "Thank you... bye"
return statement(bye_text)
@ask.intent("AMAZON.StopIntent")
def StopIntent():
return statement('Stopping,bye bye, have a nice day')
@ask.intent("AMAZON.CancelIntent")
def CancelIntent():
return statement('Cancelling, bye bye, have a nice day')
@ask.intent("AMAZON.YesIntent")
def YesIntent():
yes_message = "Please confirm which dog picture you will like to see?"
return question(yes_message)
@ask.intent("AMAZON.HelpIntent")
def HelpIntent():
help_message = "You can search for dog picture by saying all pictures or dog number 1,... please state what will you like to search?"
return question(help_message)
# @ask.intent("ShowAllDogPicturesIntent")
# def all_dogs():
# msg = '{}, Do you want to search more'.format('all dogs')
# return question(msg)
@ask.intent("ShowDogPictureIntent")
def share_dog_picture(number):
update_dog(number)
msg = 'You said number {}, Do you want to search more'.format(number)
return question(msg)
@ask.session_ended
def session_ended():
log.debug("Session Ended")
return "", 200
if __name__ == '__main__':
app.run(debug=True)
# app.run(host='0.0.0.0')
<file_sep># get these values form firebase admin json
value = {
"type": "service_account",
"project_id": "alexa-dogpictures",
"private_key_id": "",
"private_key": "",
"client_email": "",
"client_id": "",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": ""
}
<file_sep>## Using voice to control a website with Amazon Echo
This project is inspired from tutorial by <NAME>
We have used Flask-Ask and Firebase to create real-time response on webpage using voice control
|
aac4d301639e4016d54743ec1e2ee2399a276eab
|
[
"Markdown",
"Python"
] | 3 |
Markdown
|
navenduagarwal/alexa_dogpictures
|
f2b63e91830308ba83da41d94586655d44dd9d89
|
f4857ab6687b4fba1f25ec98eb0dd7525b26aea4
|
refs/heads/master
|
<file_sep> const baseUrl = "https://temperaturerestget.azurewebsites.net/Sensor"
const WeatherUrl = "https://www.7timer.info/bin/civillight.php?lon=12.1&lat=55.6&ac=0&unit=metric&output=json&tzshift=0"
Vue.createApp({
data() {
return {
temperatures: [],
dataseries: [],
}
},
async created() {
// created() is a life cycle method, not an ordinary method
// created() is called automatically when the page is loaded
console.log("created method called")
this.helperGetAndShow(baseUrl)
},
methods: {
getAllTemperatures() {
this.helperGetAndShow(baseUrl)
},
async helperGetAndShow(url) {
try {
const response = await axios.get(url)
this.temperatures = await response.data
} catch (ex) {
alert(ex.message)
}
},
async helperGetAndShowWeather(WeatherUrl) {
try {
const response = await axios.get(WeatherUrl)
this.dataseries = await response.data
} catch (ex) {
alert(ex.message)
}
},
getAllWeathers() {
this.helperGetAndShow(WeatherUrl)
},
}
}).mount("#app")
|
33234847bd53785cb1547e0be68f802f84df008c
|
[
"JavaScript"
] | 1 |
JavaScript
|
AkRockss/Temperature
|
c2e0246ad63e37100ff8471b6f611abd0fb21dec
|
ed6a543cc01021197b0e8a9bffd8ee65f1d7b9ae
|
refs/heads/master
|
<file_sep>
# coding: utf-8
from sklearn.cluster import KMeans # Class sklear.cluster enables using KMeans for clustering the dataset
import numpy as np # For the use of number functions like array,arange etc.
import csv # Enables processing the CSV(comma-separated values) files
import math # Enables the use of mathematical operations like exponentials, powers,squareroot etc.
import matplotlib.pyplot # Enables plotting graphs
import pandas as pd
from matplotlib import pyplot as plt
## PREPARING RAW DATAGETS
def GenerateRawData(humanmatrix):
humanmatrix.drop(['img_id_A','img_id_B','target'],axis=1,inplace=True)
RawData = humanmatrix.values
RawData = np.transpose(RawData)
return RawData
# In[80]:
def GenerateRawDatasub(humanmatrix):
RawData = humanmatrix.values
RawData = np.transpose(RawData)
return RawData
# Computes the Spread Of the Radial Basis Functions i.e the variance
def GenerateBigSigma(Data, MuMatrix,TrainingPercent,IsSynthetic):
BigSigma = np.zeros((len(Data),len(Data))) # Computing a matrix of with entries as zero as the length of Data is 1024; corresponds to the number of rows
DataT = np.transpose(Data) # Computing the transpose of the Data matrix;
TrainingLen = math.ceil(len(DataT)*(TrainingPercent*0.01)) # Computing the Length of the training data set which is 3200
#TrainingLen=TrainingLen-1
varVect = [] # Initializing an array to store the variance
for i in range(0,len(DataT[0])): # running the loop from 0 to 1023
vct = []
for j in range(0,int(TrainingLen)): # running an inner loop from 0 to 3200
vct.append(Data[i][j]) # append the values in Date[i][j] to the vct array
varVect.append(np.var(vct)) # Compute the variance for the features
for j in range(len(Data)):
BigSigma[j][j] = varVect[j] # Appending the computed values of variance along the diagonal of the Covariance matrix
BigSigma[j][j] = BigSigma[j][j] + 0.5
BigSigma = np.dot(3,BigSigma)
#BigSigma = np.dot(200,BigSigma)
##print ("BigSigma Generated..")
return BigSigma
# Calculate the Value of the terms In the powers of the exponential term of the guassian RBF
def GetScalar(DataRow,MuRow, BigSigInv):
R = np.subtract(DataRow,MuRow) # Subtract the values of inputs and the mean and store in R
T = np.dot(BigSigInv,np.transpose(R)) # Multiply the transpose of R with the Covariance matrix(BigSigma) and store in T
L = np.dot(R,T) # Dot product of R and T gives a scalar value
return L
# Calculate the Gaussian radial basis function
def GetRadialBasisOut(DataRow,MuRow, BigSigInv):
phi_x = math.exp(-0.5*GetScalar(DataRow,MuRow,BigSigInv)) # Calculate the gaussian RBF by the formula
return phi_x
# Generate the design matrix PHI that contains the basis functions for all input features
def GetPhiMatrix(Data, MuMatrix, BigSigma, TrainingPercent = 80):
DataT = np.transpose(Data) # Tranpose of the Data matrix; dimensions are now (3200,1024)
TrainingLen = math.ceil(len(DataT)*(TrainingPercent*0.01)) # Length of the training set which is 3200
#TrainingLen=TrainingLen-1
PHI = np.zeros((int(TrainingLen),len(MuMatrix))) # Initialize a Matrix (80% data)xM with entries as zeroes i.e (3200,15)
BigSigInv = np.linalg.inv(BigSigma) # Inverse of the BigSigma matrix
for C in range(0,len(MuMatrix)): # running a loop from 0 to 15
for R in range(0,int(TrainingLen)): # running an inner loop from 0 to 3200
PHI[R][C] = GetRadialBasisOut(DataT[R], MuMatrix[C], BigSigInv) # Calculate the RBF value using the formula
#print ("PHI Generated..")
return PHI
# Compute the weights of the Closed form solution to minimize the error
def GetWeightsClosedForm(PHI, T, Lambda):
Lambda_I = np.identity(len(PHI[0])) # Create an indentity matrix with dimenions as (15,15)
# Computing the regularization term of the Closed form equation i.e Lambda multipled with the identity matrix
for i in range(0,len(PHI[0])):
Lambda_I[i][i] = Lambda # Gives Lambda along the diagonal
# Compute the Closed form solution equation
PHI_T = np.transpose(PHI) # Transpose of the PHI matrix i.e. dimensions are (15, 3200)
PHI_SQR = np.dot(PHI_T,PHI) # Dot product of the Phi matrix with its Transpose. Dimensions are (15,15)
PHI_SQR_LI = np.add(Lambda_I,PHI_SQR) # Add the product with the Regularization term. Dimensions are (15,15)
PHI_SQR_INV = np.linalg.inv(PHI_SQR_LI) # Inverse of the sum
INTER = np.dot(PHI_SQR_INV, PHI_T) # Resultant matrix is multipled with the transpose of PHI. Dimensions are (15, 3200)
W = np.dot(INTER, T) # Finally multipled with the target values of the training set giving a (15,1) shape
##print ("Training Weights Generated..")
return W
# Calulate the Target values of the Testing dataset using the calculated weights
def GetValTest(VAL_PHI,W):
Y = np.dot(W,np.transpose(VAL_PHI)) # Compute the target values from the product of the adjusted weights and PHI
##print ("Test Out Generated..")
return Y
# Calculate the root mean square value for the Validation data output with respect to the actual validation output
def GetErms(VAL_TEST_OUT,ValDataAct):
sum = 0.0
t=0
accuracy = 0.0
counter = 0
val = 0.0
# Compute Sum of the square of differences between the Predicted and Actual data
for i in range (0,len(VAL_TEST_OUT)):
sum = sum + math.pow((ValDataAct[i] - VAL_TEST_OUT[i]),2)
# Increment counter if the predicted value is equal to the actual value
if(int(np.around(VAL_TEST_OUT[i], 0)) == ValDataAct[i]): # np.around() rounds the number to the given number of decimals
counter+=1
accuracy = (float((counter*100))/float(len(VAL_TEST_OUT))) # Compute accuarcy of the validation set
##print ("Accuracy Generated..")
##print ("Validation E_RMS : " + str(math.sqrt(sum/len(VAL_TEST_OUT))))
return (str(accuracy) + ',' + str(math.sqrt(sum/len(VAL_TEST_OUT)))) # Compute the RMS by finding the squareroot of the mean i.e sum/N
def getWeight(RawData,TrainDataConcat,TrainTargetConcat,TestDataConcat,ValidateDataConcat):
M=5
# Cluster the Training dataset into M clusters using KMeans
#for i in M:
kmeans = KMeans(n_clusters=M, random_state=0).fit(np.transpose(TrainDataConcat))
# Form the Mu matrix with the centers of the M clusters
Mu = kmeans.cluster_centers_
BigSigma = GenerateBigSigma(RawData, Mu, TrainingPercent,IsSynthetic) # Compute Spread of Basis functions i.e. covariance matrix
TRAINING_PHI = GetPhiMatrix(RawData, Mu, BigSigma, TrainingPercent) # Compute the desgin matrix for training set
W = GetWeightsClosedForm(TRAINING_PHI,TrainTargetConcat,(C_Lambda)) # Compute weights
TEST_PHI = GetPhiMatrix(TestDataConcat, Mu, BigSigma, 100)
VAL_PHI = GetPhiMatrix(ValidateDataConcat, Mu, BigSigma, 100)
#print(Mu.shape)
#print(BigSigma.shape)
#print(TRAINING_PHI.shape)
#print(W.shape)
return W, TRAINING_PHI
def calculateLinR(W,TRAINING_PHI,TrainTargetSub,ValidateTargetSub,TestTargetSub):
W_Now = np.dot(220, W)
La = 5
learningRate = 0.009
L_Erms_Val = []
L_Erms_TR = []
L_Erms_Test = []
W_Mat = []
Erms = []
Acc_Test=[]
Acc_Train=[]
Acc_Val=[]
acc = []
#for j in learningRate:
for i in range(0,400):
#print ('---------Iteration: ' + str(i) + '--------------')
Delta_E_D = -np.dot((TrainTargetSub[i] - np.dot(np.transpose(W_Now),TRAINING_PHI[i])),TRAINING_PHI[i])
La_Delta_E_W = np.dot(La,W_Now)
Delta_E = np.add(Delta_E_D,La_Delta_E_W)
Delta_W = -np.dot(learningRate,Delta_E) # Negative value of the dot product of learning rate and Delta-E
W_T_Next = W_Now + Delta_W # Sum of Initial weights and Delta-W
W_Now = W_T_Next # Calculate the updated W
#-----------------TrainingData Accuracy---------------------#
TR_TEST_OUT = GetValTest(TRAINING_PHI,W_T_Next) # Get training target
Erms_TR = GetErms(TR_TEST_OUT,TrainTargetSub) # Get training E-RMS
L_Erms_TR.append(float(Erms_TR.split(',')[1]))
Acc_Train.append(float(Erms_TR.split(',')[0]))
#-----------------ValidationData Accuracy---------------------#
#VAL_TEST_OUT = GetValTest(VAL_PHI,W_T_Next) # Get validation target
#Erms_Val = GetErms(VAL_TEST_OUT,ValidateTargetSub) # Get Validation E-RMS
#L_Erms_Val.append(float(Erms_Val.split(',')[1]))
#Acc_Val.append(float(Erms_Val.split(',')[0]))
#-----------------TestingData Accuracy---------------------#
#TEST_OUT = GetValTest(TEST_PHI,W_T_Next)
#Erms_Test = GetErms(TEST_OUT,TestTargetSub) # Get Tssting target
#L_Erms_Test.append(float(Erms_Test.split(',')[1])) # Get testing E-RMS
#Acc_Test.append(float(Erms_Test.split(',')[0]))
#Erms.append(min(L_Erms_TR))
#acc.append((max(Acc_Train)))
#print(Erms)
#print(acc)
#print(min(L_Erms_Test))
#print(max(Acc_Test))
return L_Erms_TR, Acc_Train
def printfun(Erms_Test,ACC_Test):
print ('----------Gradient Descent Solution--------------------')
print ('---------- LINEAR REGRESSION:GSC DATASET- FEATURE CONCATENATION--------------------')
#print ("E_rms Training = " + str(np.around(min(L_Erms_TR),5))) # Print Erms for training set
#print ("E_rms Validation = " + str(np.around(min(L_Erms_Val),5))) # Print Erms for validation set
#print ("Training Accuracy = " + str(np.around(max(Acc_Train),5))) # Print Erms for training set
#print ("Validation Accuracy= " + str(np.around(max(Acc_Val),5))) # Print Erms for validation set
print ("Testing Accuracy= " + str(np.around(max(ACC_Test),5)))
print ("E_rms Testing = " + str(np.around(min(Erms_Test),5))) # Print Erms for testing set
# In[ ]:
def printfun1(Erms_Test1,ACC_Test1):
print ('----------Gradient Descent Solution--------------------')
print ('---------- LINEAR REGRESSION:GSC DATASET- FEATURE SUBTRACTION--------------------')
#print ("E_rms Training = " + str(np.around(min(L_Erms_TR),5))) # Print Erms for training set
#print ("E_rms Validation = " + str(np.around(min(L_Erms_Val),5))) # Print Erms for validation set
#print ("Training Accuracy = " + str(np.around(max(Acc_Train),5))) # Print Erms for training set
#print ("Validation Accuracy= " + str(np.around(max(Acc_Val),5))) # Print Erms for validation set
print ("Testing Accuracy= " + str(np.around(max(ACC_Test1),5)))
print ("E_rms Testing = " + str(np.around(min(Erms_Test1),5))) # Print Erms for testing set
# ## LOGISTIC REGRESSION
def calculateLR(TrainDataSub,ValidateDataSub,TestDataSub,TrainTargetSub,ValidateTargetSub,TestTargetSub):
DataTrain = np.transpose(TrainDataSub)
DataVal = np.transpose(ValidateDataSub)
DataTest = np.transpose(TestDataSub)
W_Now = np.ones(len(DataTrain[0]))
W_Now = np.dot(0.2,W_Now)
W_Now = np.transpose(W_Now)
La = 5
learningRate = 0.02
L_Erms_Val = []
L_Erms_TR = []
L_Erms_Test = []
W_Mat = []
Erms = []
Acc_Test=[]
Acc_Train=[]
Acc_Val=[]
acc = []
def ComputefunctionG(W_Now,phi):
z=np.dot(np.transpose(W_Now),phi)
g=math.exp(-z)
h_x= 1/(1+g)
return h_x
#for j in learningRate:
for i in range(0,20):
#print ('---------Iteration: ' + str(i) + '--------------')
G=ComputefunctionG(W_Now,DataTrain[i])
Delta_E_D = -np.dot((TrainTargetSub[i] - G),DataTrain[i])
La_Delta_E_W = np.dot(La,W_Now)
Delta_E = np.add(Delta_E_D,La_Delta_E_W)
Delta_W = -np.dot(learningRate,Delta_E) # Negative value of the dot product of learning rate and Delta-E
W_T_Next = W_Now + Delta_W # Sum of Initial weights and Delta-W
W_Now = W_T_Next # Calculate the updated W
#-----------------TrainingData Accuracy---------------------#
TR_TEST_OUT = GetValTest(DataTrain,W_T_Next) # Get training target
Erms_TR = GetErms(TR_TEST_OUT,TrainTargetSub) # Get training E-RMS
L_Erms_TR.append(float(Erms_TR.split(',')[1]))
Acc_Train.append(float(Erms_TR.split(',')[0]))
#-----------------ValidationData Accuracy---------------------#
VAL_TEST_OUT = GetValTest(DataVal,W_T_Next) # Get validation target
Erms_Val = GetErms(VAL_TEST_OUT,ValidateTargetSub) # Get Validation E-RMS
L_Erms_Val.append(float(Erms_Val.split(',')[1]))
Acc_Val.append(float(Erms_Val.split(',')[0]))
#-----------------TestingData Accuracy---------------------#
TEST_OUT = GetValTest(DataTest,W_T_Next)
Erms_Test = GetErms(TEST_OUT,TestTargetSub) # Get Tssting target
L_Erms_Test.append(float(Erms_Test.split(',')[1])) # Get testing E-RMS
Acc_Test.append(float(Erms_Test.split(',')[0]))
#Erms.append(min(L_Erms_Test))
#acc.append(np.around(max(Acc_Test),5))
#print(Erms)
#print(acc)
#print(min(L_Erms_Test))
#print(max(Acc_Test))
return L_Erms_Test, Acc_Test
# In[ ]:
def subtractfeature(fd,x1,x2,y1,y2):
temp1=fd.iloc[:,x1:x2]
temp2=fd.iloc[:,y1:y2]
sub=(temp1-temp2.values).abs()
return sub
def lmain():
TrainingPercent = 80 # Given data set is partitioned; 80% of the dataset is assigned for training
ValidationPercent = 10 # Given data set is partitioned; 10% of the dataset is assigned for validation
TestPercent = 10 # Given data set is partitioned; 10% of the dataset is assigned for testing
maxAcc = 0.0
maxIter = 0
C_Lambda = 0.005 # Coefficient of the Weight decay regularizer term
M = 5 # No of Basis functions
PHI = []
IsSynthetic = False
# In[65]:
##READING THE CSV FILES AND GENERATING THE DATASETS
df1= pd.read_csv('same1_pairs.csv', nrows=2000)
df2= pd.read_csv('GSC-Features.csv',nrows=2000)
df3= pd.read_csv('diffn1_pairs.csv',nrows=2000)
# ## GSC DATA- FEATURE CONTATENATION
# In[66]:
#merge same_pairs.csv and HumanObserved.csv files
df4=pd.merge(df1,df2,left_on="img_id_A",right_on="img_id")
df5=pd.merge(df4,df2,left_on="img_id_B",right_on="img_id")
df5.drop(['img_id_x','img_id_y'],axis=1,inplace=True)
#df5
#merge diffn_pairs.csv and HumanObserved.csv files
df6=pd.merge(df3,df2,left_on="img_id_A",right_on="img_id")
df7=pd.merge(df6,df2,left_on="img_id_B",right_on="img_id")
df7.drop(['img_id_x','img_id_y'],axis=1,inplace=True)
#df7
gsc_con=df5.append(df7)
gsc_con1=gsc_con
#print(gsc_con)
gsc_sub=df5.append(df7)
gsc_sub.shape
# ## GSC DATA- FEATURE SUBTRACTION
# In[67]:
Sub_Feature = subtractfeature(gsc_sub,3,514,516,1027)
gsc_sub1=Sub_Feature
#Sub_Feature.shape
## DATA PARTIONING INTO TRAINING, TESTING AND VALIDATION DATASETS
## DATA PARTITION FOR FEATURE CONTATENATION- HUMAN_OBSERVED
# In[70]:
trainingdata_concat = gsc_con.sample(frac = 0.8)
trainingdata_concat.drop(['img_id_A','img_id_B'],axis=1,inplace=True)
testingdata_concat = gsc_con.drop(trainingdata_concat.index).sample(frac = 0.5)
validatingdata_concat = gsc_con.drop(trainingdata_concat.index).drop(testingdata_concat.index)
validatingdata_concat.drop(['img_id_A','img_id_B'],axis=1,inplace=True)
testingdata_concat.drop(['img_id_A','img_id_B'],axis=1,inplace=True)
## DATA PARTITION FOR FEATURE SUBTRACTION- HUMAN_OBSERVED
# In[71]:
trainingdata_sub= Sub_Feature.sample(frac = 0.8)
traintarget_sub = gsc_sub.sample(frac = 0.8)
testingdata_sub = Sub_Feature.drop(trainingdata_sub.index).sample(frac = 0.5)
testingtarget_sub = gsc_sub.drop(traintarget_sub.index).sample(frac = 0.5)
validatingdata_sub = Sub_Feature.drop(trainingdata_sub.index).drop(testingdata_sub.index)
validatetarget_sub = gsc_sub.drop(traintarget_sub.index).drop(testingtarget_sub.index)
#validatingdata_sub.drop(['img_id_A','img_id_B'],axis=1,inplace=True)
#testingdata_sub.drop(['img_id_A','img_id_B'],axis=1,inplace=True)
# In[72]:
## GRADIENT DESCENT SOLUTION FOR LINEAR REGRESSION
# In[73]:
# CONVERTING THE DATAFRAMES INTO MATRICES FOR DATA PROCESSING
TrainTargetConcat= trainingdata_concat['target'].values
TrainTargetConcat = np.transpose(TrainTargetConcat)
trainingdata_concat.drop(['target'],axis=1,inplace=True)
TrainDataConcat= trainingdata_concat.values
TrainDataConcat = np.transpose(TrainDataConcat)
print(TrainTargetConcat.shape)
print(TrainDataConcat.shape)
# In[74]:
ValidateTargetConcat= validatingdata_concat['target'].values
ValidateTargetConcat = np.transpose(ValidateTargetConcat)
validatingdata_concat.drop(['target'],axis=1,inplace=True)
ValidateDataConcat= validatingdata_concat.values
ValidateDataConcat = np.transpose(ValidateDataConcat)
print(ValidateTargetConcat.shape)
print(ValidateDataConcat.shape)
# In[75]:
TestTargetConcat= testingdata_concat['target'].values
TestTargetConcat = np.transpose(TestTargetConcat)
testingdata_concat.drop(['target'],axis=1,inplace=True)
TestDataConcat= testingdata_concat.values
TestDataConcat = np.transpose(TestDataConcat)
print(TestTargetConcat.shape)
print(TestDataConcat.shape)
# In[76]:
# CONVERTING THE DATAFRAMES INTO MATRICES FOR DATA PROCESSING
TrainTargetSub= traintarget_sub['target'].values
TrainTargetSub = np.transpose(TrainTargetSub)
#trainingdata_sub.drop(['target'],axis=1,inplace=True)
TrainDataSub= trainingdata_sub.values
TrainDataSub = np.transpose(TrainDataSub)
print(TrainTargetSub.shape)
#print(TrainDataSub.shape)
# In[77]:
ValidateTargetSub= validatetarget_sub['target'].values
ValidateTargetSub = np.transpose(ValidateTargetSub)
#validatingdata_sub.drop(['target'],axis=1,inplace=True)
ValidateDataSub= validatingdata_sub.values
ValidateDataSub = np.transpose(ValidateDataSub)
print(ValidateTargetSub.shape)
#print(ValidateDataSub.shape)
# In[78]:
TestTargetSub= testingtarget_sub['target'].values
TestTargetSub = np.transpose(TestTargetSub)
#testingdata_sub.drop(['target'],axis=1,inplace=True)
TestDataSub= testingdata_sub.values
TestDataSub = np.transpose(TestDataSub)
print(TestTargetSub.shape)
#print(TestDataSub.shape)
RawData = GenerateRawData(gsc_con1)
RawData1 = GenerateRawDatasub(gsc_sub1)
weight,phi=getWeight(RawData,TrainDataConcat,TrainTargetConcat,TestDataConcat,ValidateDataConcat)
weight1,phi1=getWeight(RawData1,TrainDataSub,TrainTargetSub,TestDataSub,ValidateDataSub)
Erms_Test,ACC_Test= calculateLinR(weight,phi,TrainTargetConcat,ValidateTargetConcat,TestTargetConcat)
printfun(Erms_Test,ACC_Test)
Erms_Test1,ACC_Test1= calculateLinR(weight1,phi1,TrainTargetSub,ValidateTargetSub,TestTargetSub)
printfun(Erms_Test1,ACC_Test1)
L_Erms_Test,Acc_Test= calculateLR(TrainDataConcat,ValidateDataConcat,TestDataConcat,TrainTargetConcat,ValidateTargetConcat,TestTargetConcat)
printfun2(L_Erms_Test,Acc_Test)
L_Erms_Test1,Acc_Test1= calculateLR(TrainDataSub,ValidateDataSub,TestDataSub,TrainTargetSub,ValidateTargetSub,TestTargetSub)
printfun3(L_Erms_Test1,Acc_Test1)
# In[ ]:
def printfun2(L_Erms_Test,Acc_Test):
print ('----------Gradient Descent Solution--------------------')
print ('----------LOGISTIC REGRESSION: Featue Concatenation--------------------')
#print ("E_rms Training = " + str(np.around(min(L_Erms_TR),5))) # Print Erms for training set
#print ("E_rms Validation = " + str(np.around(min(L_Erms_Val),5))) # Print Erms for validation set
#print ("Training Accuracy = " + str(np.around(max(Acc_Train),5))) # Print Erms for training set
#print ("Validation Accuracy= " + str(np.around(max(Acc_Val),5))) # Print Erms for validation set
print ("Testing Accuracy= " + str(np.around(max(Acc_Test),5)))
print ("E_rms Testing = " + str(np.around(min(L_Erms_Test),5))) # Print Erms for testing set
# In[ ]:
def printfun3(L_Erms_Test1,Acc_Test1):
print ('----------Gradient Descent Solution--------------------')
print ('----------LOGISTIC REGRESSION: Featue Subtraction--------------------')
#print ("E_rms Training = " + str(np.around(min(L_Erms_TR),5))) # Print Erms for training set
#print ("E_rms Validation = " + str(np.around(min(L_Erms_Val),5))) # Print Erms for validation set
#print ("Training Accuracy = " + str(np.around(max(Acc_Train),5))) # Print Erms for training set
#print ("Validation Accuracy= " + str(np.around(max(Acc_Val),5))) # Print Erms for validation set
print ("Testing Accuracy= " + str(np.around(max(Acc_Test1),5)))
print ("E_rms Testing = " + str(np.around(min(L_Erms_Test1),5))) # Print Erms for testing set
<file_sep>
# coding: utf-8
# In[38]:
from sklearn.cluster import KMeans # Class sklear.cluster enables using KMeans for clustering the dataset
import numpy as np # For the use of number functions like array,arange etc.
import csv # Enables processing the CSV(comma-separated values) files
import math # Enables the use of mathematical operations like exponentials, powers,squareroot etc.
import matplotlib.pyplot # Enables plotting graphs
import pandas as pd
from matplotlib import pyplot as plt
## PREPARING RAW DATAGETS
def GenerateRawData(humanmatrix):
humanmatrix.drop(['img_id_A','img_id_B','target'],axis=1,inplace=True)
RawData = humanmatrix.values
RawData = np.transpose(RawData)
return RawData
# Computes the Spread Of the Radial Basis Functions i.e the variance
def GenerateBigSigma(Data, MuMatrix,TrainingPercent,IsSynthetic):
BigSigma = np.zeros((len(Data),len(Data))) # Computing a matrix of 9x9 with entries as zero as the length of Data is 9; corresponds to the number of rows
DataT = np.transpose(Data) # Computing the transpose of the Data matrix;
TrainingLen = math.ceil(len(DataT)*(TrainingPercent*0.01)) # Computing the Length of the training data set which is 235058
TrainingLen=TrainingLen-1
varVect = [] # Initializing an array to store the variance
for i in range(0,len(DataT[0])): # running the loop from 0 to 9
vct = []
for j in range(0,int(TrainingLen)): # running an inner loop from 0 to 235058
vct.append(Data[i][j]) # append the values in Date[i][j] to the vct array
varVect.append(np.var(vct)) # Compute the variance for the features
for j in range(len(Data)):
BigSigma[j][j] = varVect[j] # Appending the computed values of variance along the diagonal of the Covariance matrix
if IsSynthetic == True:
BigSigma = np.dot(3,BigSigma)
else:
BigSigma = np.dot(200,BigSigma)
##print ("BigSigma Generated..")
return BigSigma
# Calculate the Value of the terms In the powers of the exponential term of the guassian RBF
def GetScalar(DataRow,MuRow, BigSigInv):
R = np.subtract(DataRow,MuRow) # Subtract the values of inputs and the mean and store in R
T = np.dot(BigSigInv,np.transpose(R)) # Multiply the transpose of R with the Covariance matrix(BigSigma) and store in T
L = np.dot(R,T) # Dot product of R and T gives a scalar value
return L
# Calculate the Gaussian radial basis function
def GetRadialBasisOut(DataRow,MuRow, BigSigInv):
phi_x = math.exp(-0.5*GetScalar(DataRow,MuRow,BigSigInv)) # Calculate the gaussian RBF by the formula
return phi_x
# Generate the design matrix PHI that contains the basis functions for all input features
def GetPhiMatrix(Data, MuMatrix, BigSigma, TrainingPercent = 80):
DataT = np.transpose(Data) # Tranpose of the Data matrix; dimensions are now (293823,9)
TrainingLen = math.ceil(len(DataT)*(TrainingPercent*0.01)) # Length of the training set which is 235058
TrainingLen=TrainingLen-1
PHI = np.zeros((int(TrainingLen),len(MuMatrix))) # Initialize a Matrix (80% data)xM with entries as zeroes i.e (235058,15)
BigSigInv = np.linalg.inv(BigSigma) # Inverse of the BigSigma matrix
for C in range(0,len(MuMatrix)): # running a loop from 0 to 15
for R in range(0,int(TrainingLen)): # running an inner loop from 0 to 235058
PHI[R][C] = GetRadialBasisOut(DataT[R], MuMatrix[C], BigSigInv) # Calculate the RBF value using the formula
#print ("PHI Generated..")
return PHI
# Compute the weights of the Closed form solution to minimize the error
def GetWeightsClosedForm(PHI, T, Lambda):
Lambda_I = np.identity(len(PHI[0])) # Create an indentity matrix with dimenions as (15,15)
# Computing the regularization term of the Closed form equation i.e Lambda multipled with the identity matrix
for i in range(0,len(PHI[0])):
Lambda_I[i][i] = Lambda # Gives Lambda along the diagonal
# Compute the Closed form solution equation
PHI_T = np.transpose(PHI) # Transpose of the PHI matrix i.e. dimensions are (15, 235058)
PHI_SQR = np.dot(PHI_T,PHI) # Dot product of the Phi matrix with its Transpose. Dimensions are (15,15)
PHI_SQR_LI = np.add(Lambda_I,PHI_SQR) # Add the product with the Regularization term. Dimensions are (15,15)
PHI_SQR_INV = np.linalg.inv(PHI_SQR_LI) # Inverse of the sum
INTER = np.dot(PHI_SQR_INV, PHI_T) # Resultant matrix is multipled with the transpose of PHI. Dimensions are (15, 235058)
W = np.dot(INTER, T) # Finally multipled with the target values of the training set giving a (15,1) shape
##print ("Training Weights Generated..")
return W
# Calulate the Target values of the Testing dataset using the calculated weights
def GetValTest(VAL_PHI,W):
Y = np.dot(W,np.transpose(VAL_PHI)) # Compute the target values from the product of the adjusted weights and PHI
##print ("Test Out Generated..")
return Y
# Calculate the root mean square value for the Validation data output with respect to the actual validation output
def GetErms(VAL_TEST_OUT,ValDataAct):
sum = 0.0
t=0
accuracy = 0.0
counter = 0
val = 0.0
# Compute Sum of the square of differences between the Predicted and Actual data
for i in range (0,len(VAL_TEST_OUT)):
sum = sum + math.pow((ValDataAct[i] - VAL_TEST_OUT[i]),2)
# Increment counter if the predicted value is equal to the actual value
if(int(np.around(VAL_TEST_OUT[i], 0)) == ValDataAct[i]): # np.around() rounds the number to the given number of decimals
counter+=1
accuracy = (float((counter*100))/float(len(VAL_TEST_OUT))) # Compute accuarcy of the validation set
##print ("Accuracy Generated..")
##print ("Validation E_RMS : " + str(math.sqrt(sum/len(VAL_TEST_OUT))))
return (str(accuracy) + ',' + str(math.sqrt(sum/len(VAL_TEST_OUT)))) # Compute the RMS by finding the squareroot of the mean i.e sum/N
def getweight(RawData,TrainDataSub,TrainTargetSub,TestDataSub,ValidateDataSub):
M = 5
# Cluster the Training dataset into M clusters using KMeans
#for i in M:
kmeans = KMeans(n_clusters=M, random_state=0).fit(np.transpose(TrainDataSub))
# Form the Mu matrix with the centers of the M clusters
Mu = kmeans.cluster_centers_
BigSigma = GenerateBigSigma(RawData, Mu, TrainingPercent,IsSynthetic) # Compute Spread of Basis functions i.e. covariance matrix
TRAINING_PHI = GetPhiMatrix(RawData, Mu, BigSigma, TrainingPercent) # Compute the desgin matrix for training set
W = GetWeightsClosedForm(TRAINING_PHI,TrainTargetSub,(C_Lambda)) # Compute weights
TEST_PHI = GetPhiMatrix(TestDataSub, Mu, BigSigma, 100)
VAL_PHI = GetPhiMatrix(ValidateDataSub, Mu, BigSigma, 100)
return W, TRAINING_PHI
#print(Mu.shape)
#print(BigSigma.shape)
#print(TRAINING_PHI.shape)
#print(W.shape)
# In[57]:
def calculateLinR(W,TRAINING_PHI,TrainTargetSub,ValidateTargetSub,TestTargetSub):
W_Now = np.dot(220, W)
La = 5
learningRate = 0.02
L_Erms_Val = []
L_Erms_TR = []
L_Erms_Test = []
W_Mat = []
Erms = []
Acc_Test=[]
Acc_Train=[]
Acc_Val=[]
acc = []
#for j in learningRate:
for i in range(0,400):
#print ('---------Iteration: ' + str(i) + '--------------')
Delta_E_D = -np.dot((TrainTargetSub[i] - np.dot(np.transpose(W_Now),TRAINING_PHI[i])),TRAINING_PHI[i])
La_Delta_E_W = np.dot(La,W_Now)
Delta_E = np.add(Delta_E_D,La_Delta_E_W)
Delta_W = -np.dot(learningRate,Delta_E) # Negative value of the dot product of learning rate and Delta-E
W_T_Next = W_Now + Delta_W # Sum of Initial weights and Delta-W
W_Now = W_T_Next # Calculate the updated W
#-----------------TrainingData Accuracy---------------------#
TR_TEST_OUT = GetValTest(TRAINING_PHI,W_T_Next) # Get training target
Erms_TR = GetErms(TR_TEST_OUT,TrainTargetSub) # Get training E-RMS
L_Erms_TR.append(float(Erms_TR.split(',')[1]))
Acc_Train.append(float(Erms_TR.split(',')[0]))
#-----------------ValidationData Accuracy---------------------#
#VAL_TEST_OUT = GetValTest(VAL_PHI,W_T_Next) # Get validation target
#Erms_Val = GetErms(VAL_TEST_OUT,ValidateTargetSub) # Get Validation E-RMS
#L_Erms_Val.append(float(Erms_Val.split(',')[1]))
#Acc_Val.append(float(Erms_Val.split(',')[0]))
#-----------------TestingData Accuracy---------------------#
#TEST_OUT = GetValTest(TEST_PHI,W_T_Next)
#Erms_Test = GetErms(TEST_OUT,TestTargetSub) # Get Tssting target
#L_Erms_Test.append(float(Erms_Test.split(',')[1])) # Get testing E-RMS
#Acc_Test.append(float(Erms_Test.split(',')[0]))
#Erms.append(min(L_Erms_Test))
#acc.append(np.around(max(Acc_Test),5))
#print(min(L_Erms_Test))
#print(max(Acc_Test))
#print(Erms)
#print(acc)
return L_Erms_TR, Acc_Train
def printfun(Erms_Test,ACC_Test):
print ('----------Gradient Descent Solution--------------------')
print ('----------LINEAR REGRESSION:Feature Concatenation--------------------')
#print ("E_rms Training = " + str(np.around(min(L_Erms_TR),5))) # Print Erms for training set
#print ("E_rms Validation = " + str(np.around(min(L_Erms_Val),5))) # Print Erms for validation set
#print ("Training Accuracy = " + str(np.around(max(Acc_Train),5))) # Print Erms for training set
#print ("Validation Accuracy= " + str(np.around(max(Acc_Val),5))) # Print Erms for validation set
print ("Testing Accuracy= " + str(np.around(max(ACC_Test),5)))
print ("E_rms Testing = " + str(np.around(min(Erms_Test),5))) # Print Erms for testing set
# In[60]:
def printfun1(Erms_Test1,ACC_Test1):
print ('----------Gradient Descent Solution--------------------')
print ('----------LINEAR REGRESSION:Feature Subtraction--------------------')
#print ("E_rms Training = " + str(np.around(min(L_Erms_TR),5))) # Print Erms for training set
#print ("E_rms Validation = " + str(np.around(min(L_Erms_Val),5))) # Print Erms for validation set
#print ("Training Accuracy = " + str(np.around(max(Acc_Train),5))) # Print Erms for training set
#print ("Validation Accuracy= " + str(np.around(max(Acc_Val),5))) # Print Erms for validation set
print ("Testing Accuracy= " + str(np.around(max(ACC_Test1),5)))
print ("E_rms Testing = " + str(np.around(min(Erms_Test1),5))) # Print Erms for testing set
# ## LOGISTIC REGRESSION
# In[74]:
def calculateLR(TrainDataConcat,ValidateDataConcat,TestDataConcat,TrainTargetConcat,ValidateTargetConcat,TestTargetConcat):
DataTrain = np.transpose(TrainDataConcat)
DataVal = np.transpose(ValidateDataConcat)
DataTest = np.transpose(TestDataConcat)
W_Now = np.ones(len(DataTrain[0]))
W_Now =np.transpose(W_Now)
La = 5
learningRate = 0.02
L_Erms_Val = []
L_Erms_TR = []
L_Erms_Test = []
W_Mat = []
Erms = []
Acc_Test=[]
Acc_Train=[]
Acc_Val=[]
acc = []
def ComputefunctionG(W_Now,phi):
z=np.dot(np.transpose(W_Now),phi)
g=math.exp(-z)
h_x= 1/(1+g)
return h_x
#for j in learningRate:
for i in range(0,400):
#print ('---------Iteration: ' + str(i) + '--------------')
G=ComputefunctionG(W_Now,DataTrain[i])
Delta_E_D = -np.dot((TrainTargetConcat[i] - G),DataTrain[i])
La_Delta_E_W = np.dot(La,W_Now)
Delta_E = np.add(Delta_E_D,La_Delta_E_W)
Delta_W = -np.dot(learningRate,Delta_E) # Negative value of the dot product of learning rate and Delta-E
W_T_Next = W_Now + Delta_W # Sum of Initial weights and Delta-W
W_Now = W_T_Next # Calculate the updated W
#-----------------TrainingData Accuracy---------------------#
TR_TEST_OUT = GetValTest(DataTrain,W_T_Next) # Get training target
Erms_TR = GetErms(TR_TEST_OUT,TrainTargetConcat) # Get training E-RMS
L_Erms_TR.append(float(Erms_TR.split(',')[1]))
Acc_Train.append(float(Erms_TR.split(',')[0]))
#-----------------ValidationData Accuracy---------------------#
VAL_TEST_OUT = GetValTest(DataVal,W_T_Next) # Get validation target
Erms_Val = GetErms(VAL_TEST_OUT,ValidateTargetConcat) # Get Validation E-RMS
L_Erms_Val.append(float(Erms_Val.split(',')[1]))
Acc_Val.append(float(Erms_Val.split(',')[0]))
#-----------------TestingData Accuracy---------------------#
TEST_OUT = GetValTest(DataTest,W_T_Next)
Erms_Test = GetErms(TEST_OUT,TestTargetConcat) # Get Tssting target
L_Erms_Test.append(float(Erms_Test.split(',')[1])) # Get testing E-RMS
Acc_Test.append(float(Erms_Test.split(',')[0]))
#Erms.append(min(L_Erms_Test))
#acc.append(np.around(max(Acc_Test),5))
#print(min(L_Erms_Test))
#print(max(Acc_Test))
#print(Erms)
#print(acc)
return L_Erms_Test, Acc_Test
# In[75]:
def lmain():
TrainingPercent = 80 # Given data set is partitioned; 80% of the dataset is assigned for training
ValidationPercent = 10 # Given data set is partitioned; 10% of the dataset is assigned for validation
TestPercent = 10 # Given data set is partitioned; 10% of the dataset is assigned for testing
maxAcc = 0.0
maxIter = 0
C_Lambda = 0.005 # Coefficient of the Weight decay regularizer term
M = 10 # No of Basis functions
PHI = []
IsSynthetic = False
# In[41]:
##READING THE CSV FILES AND GENERATING THE DATASETS
df1= pd.read_csv('same_pairs.csv')
df2= pd.read_csv('HumanObserved-Features-Data.csv')
df3= pd.read_csv('diffn_pairs.csv')
# ## HUMAN OBSERVED DATA- FEATURE CONTATENATION
# In[42]:
#merge same_pairs.csv and HumanObserved.csv files
df4=pd.merge(df1,df2,left_on="img_id_A",right_on="img_id")
df5=pd.merge(df4,df2,left_on="img_id_B",right_on="img_id")
df5.drop(['Unnamed: 0_x','Unnamed: 0_y','img_id_x','img_id_y'],axis=1,inplace=True)
#df5
#merge diffn_pairs.csv and HumanObserved.csv files
df6=pd.merge(df3,df2,left_on="img_id_A",right_on="img_id")
df7=pd.merge(df6,df2,left_on="img_id_B",right_on="img_id")
df7.drop(['Unnamed: 0_x','Unnamed: 0_y','img_id_x','img_id_y'],axis=1,inplace=True)
#df7
human_con=df5.append(df7)
human_con1=human_con
#human_con
# ## HUMAN OBSERVED DATA- FEATURE SUBTRACTION
# In[43]:
human_sub=df5.append(df7)
human_sub["f1"]=human_sub["f1_x"]-human_sub["f1_y"]
human_sub["f1"]= human_sub["f1"].abs()
human_sub["f2"]=human_sub["f2_x"]-human_sub["f2_y"]
human_sub["f2"]= human_sub["f2"].abs()
human_sub["f3"]=human_sub["f3_x"]-human_sub["f3_y"]
human_sub["f3"]= human_sub["f3"].abs()
human_sub["f4"]=human_sub["f4_x"]-human_sub["f4_y"]
human_sub["f4"]= human_sub["f4"].abs()
human_sub["f5"]=human_sub["f5_x"]-human_sub["f5_y"]
human_sub["f5"]= human_sub["f5"].abs()
human_sub["f6"]=human_sub["f6_x"]-human_sub["f6_y"]
human_sub["f6"]= human_sub["f6"].abs()
human_sub["f7"]=human_sub["f7_x"]-human_sub["f7_y"]
human_sub["f7"]= human_sub["f7"].abs()
human_sub["f8"]=human_sub["f8_x"]-human_sub["f8_y"]
human_sub["f8"]= human_sub["f8"].abs()
human_sub["f9"]=human_sub["f9_x"]-human_sub["f9_y"]
human_sub["f9"]= human_sub["f9"].abs()
human_sub.drop(['f1_x','f2_x','f3_x','f4_x','f5_x','f6_x','f7_x','f8_x','f9_x'],axis=1,inplace=True)
human_sub.drop(['f1_y','f2_y','f3_y','f4_y','f5_y','f6_y','f7_y','f8_y','f9_y'],axis=1,inplace=True)
human_sub= human_sub[['img_id_A','img_id_B','f1','f2','f3','f4','f5','f6','f7','f8','f9','target']]
human_sub1 = human_sub
#human_sub
## DATA PARTIONING INTO TRAINING, TESTING AND VALIDATION DATASETS
# ## DATA PARTITION FOR FEATURE CONTATENATION- HUMAN_OBSERVED
# In[45]:
trainingdata_concat = human_con.sample(frac = 0.8)
trainingdata_concat.drop(['img_id_A','img_id_B'],axis=1,inplace=True)
testingdata_concat = human_con.drop(trainingdata_concat.index).sample(frac = 0.5)
validatingdata_concat = human_con.drop(trainingdata_concat.index).drop(testingdata_concat.index)
validatingdata_concat.drop(['img_id_A','img_id_B'],axis=1,inplace=True)
testingdata_concat.drop(['img_id_A','img_id_B'],axis=1,inplace=True)
# ## DATA PARTITION FOR FEATURE SUBTRACTION- HUMAN_OBSERVED
# In[46]:
trainingdata_sub= human_sub.sample(frac = 0.8)
trainingdata_sub.drop(['img_id_A','img_id_B'],axis=1,inplace=True)
testingdata_sub = human_sub.drop(trainingdata_sub.index).sample(frac = 0.5)
validatingdata_sub = human_sub.drop(trainingdata_sub.index).drop(testingdata_sub.index)
validatingdata_sub.drop(['img_id_A','img_id_B'],axis=1,inplace=True)
testingdata_sub.drop(['img_id_A','img_id_B'],axis=1,inplace=True)
# # CONVERTING THE DATAFRAMES INTO MATRICES FOR DATA PROCESSING
# In[47]:
TrainTargetConcat= trainingdata_concat['target'].values
TrainTargetConcat = np.transpose(TrainTargetConcat)
trainingdata_concat.drop(['target'],axis=1,inplace=True)
TrainDataConcat= trainingdata_concat.values
TrainDataConcat = np.transpose(TrainDataConcat)
print(TrainTargetConcat.shape)
print(TrainDataConcat.shape)
# In[48]:
ValidateTargetConcat= validatingdata_concat['target'].values
ValidateTargetConcat = np.transpose(ValidateTargetConcat)
validatingdata_concat.drop(['target'],axis=1,inplace=True)
ValidateDataConcat= validatingdata_concat.values
ValidateDataConcat = np.transpose(ValidateDataConcat)
print(ValidateTargetConcat.shape)
print(ValidateDataConcat.shape)
# In[49]:
TestTargetConcat= testingdata_concat['target'].values
TestTargetConcat = np.transpose(TestTargetConcat)
testingdata_concat.drop(['target'],axis=1,inplace=True)
TestDataConcat= testingdata_concat.values
TestDataConcat = np.transpose(TestDataConcat)
print(TestTargetConcat.shape)
print(TestDataConcat.shape)
# In[50]:
# CONVERTING THE DATAFRAMES INTO MATRICES FOR DATA PROCESSING
TrainTargetSub= trainingdata_sub['target'].values
TrainTargetSub = np.transpose(TrainTargetSub)
trainingdata_sub.drop(['target'],axis=1,inplace=True)
TrainDataSub= trainingdata_sub.values
TrainDataSub = np.transpose(TrainDataSub)
print(TrainTargetSub.shape)
print(TrainDataSub.shape)
# In[51]:
ValidateTargetSub= validatingdata_sub['target'].values
ValidateTargetSub = np.transpose(ValidateTargetSub)
validatingdata_sub.drop(['target'],axis=1,inplace=True)
ValidateDataSub= validatingdata_sub.values
ValidateDataSub = np.transpose(ValidateDataSub)
print(ValidateTargetSub.shape)
print(ValidateDataSub.shape)
# In[52]:
TestTargetSub= testingdata_sub['target'].values
TestTargetSub = np.transpose(TestTargetSub)
testingdata_sub.drop(['target'],axis=1,inplace=True)
TestDataSub= testingdata_sub.values
TestDataSub = np.transpose(TestDataSub)
print(TestTargetSub.shape)
print(TestDataSub.shape)
RawData = GenerateRawData(human_con1)
RawData1 = GenerateRawData(human_sub1)
weight,phi=getweight(RawData,TrainDataConcat,TrainTargetConcat,TestDataConcat,ValidateDataConcat)
weight1,phi1=getweight(RawData1,TrainDataSub,TrainTargetSub,TestDataSub,ValidateDataSub)
Erms_Test,ACC_Test= calculateLinR(weight,phi,TrainTargetConcat,ValidateTargetConcat,TestTargetConcat)
printfun(Erms_Test,ACC_Test)
Erms_Test1,ACC_Test1= calculateLinR(weight1,phi1,TrainTargetSub,ValidateTargetSub,TestTargetSub)
printfun1(Erms_Test1,ACC_Test1)
L_Erms_Test,Acc_Test= calculateLR(TrainDataConcat,ValidateDataConcat,TestDataConcat,TrainTargetConcat,ValidateTargetConcat,TestTargetConcat)
printfun2(L_Erms_Test,Acc_Test)
L_Erms_Test1,Acc_Test1= calculateLR(TrainDataSub,ValidateDataSub,TestDataSub,TrainTargetSub,ValidateTargetSub,TestTargetSub)
printfun3(L_Erms_Test1,Acc_Test1)
# In[64]:
def printfun2(L_Erms_Test,Acc_Test):
print ('----------Gradient Descent Solution--------------------')
print ('----------LOGISTIC REGRESSION: Feature Concatenation--------------------')
#print ("E_rms Training = " + str(np.around(min(L_Erms_TR),5))) # Print Erms for training set
#print ("E_rms Validation = " + str(np.around(min(L_Erms_Val),5))) # Print Erms for validation set
#print ("Training Accuracy = " + str(np.around(max(Acc_Train),5))) # Print Erms for training set
#print ("Validation Accuracy= " + str(np.around(max(Acc_Val),5))) # Print Erms for validation set
print ("Testing Accuracy= " + str(np.around(max(Acc_Test),5)))
print ("E_rms Testing = " + str(np.around(min(L_Erms_Test),5))) # Print Erms for testing set
# In[65]:
def printfun3(L_Erms_Test1,Acc_Test1):
print ('----------Gradient Descent Solution--------------------')
print ('----------LOGISTIC REGRESSION: Feature Subtraction--------------------')
#print ("E_rms Training = " + str(np.around(min(L_Erms_TR),5))) # Print Erms for training set
#print ("E_rms Validation = " + str(np.around(min(L_Erms_Val),5))) # Print Erms for validation set
#print ("Training Accuracy = " + str(np.around(max(Acc_Train),5))) # Print Erms for training set
#print ("Validation Accuracy= " + str(np.around(max(Acc_Val),5))) # Print Erms for validation set
print ("Testing Accuracy= " + str(np.around(max(Acc_Test1),5)))
print ("E_rms Testing = " + str(np.around(min(L_Erms_Test1),5))) # Print Erms for testing set
# In[ ]:
#plt.plot(learningRate, Erms,'ro')
#plt.ylabel('E-RMS Value for Testing')
#plt.xlabel("Learning Rate")
#plt.title("Learning Rate VS E-RMS Plot for Logistic Regression")
#plt.show()
# In[ ]:
#plt.plot(learningRate,acc,'ro')
#plt.ylabel('Testing Accuracy of the model')
#plt.xlabel("Learning Rate")
#plt.title("Learning Rate VS Accuracy Plot for Logistic Regression")
#plt.show()
<file_sep>import run
import GSC
run.lmain()
GSC.lmain()
<file_sep># Handwriting-Analysis-Using-Linear-And-Logistic-Regression
|
64cb047db030762f0d6140bb0f8e4d436c731c59
|
[
"Markdown",
"Python"
] | 4 |
Markdown
|
Monisha-Balaji/Handwriting-Analysis-Using-Linear-And-Logistic-Regression
|
e5c5ab42bf39870385e57877f6392fc8eed2c174
|
4512059a700f4b111770403f82c088df908fa655
|
refs/heads/master
|
<file_sep>package Hello;
public class HelloGit {
public static void main(String[] args){
System.out.println("Hello Git,I coe from IDEA.");
}
}
|
79e9d703ee4571fcbf655a3868b8fac39a6a2768
|
[
"Java"
] | 1 |
Java
|
tutu-ty/yy
|
a27da37de0d7c4f031967652d384550f1a0aa053
|
c779dd57fe0a501534264438d90af3a3263e4980
|
refs/heads/master
|
<file_sep><?php
include 'conn/dbpdo.php';
session_start();
echo '<script>alert("123");document.location.href="index.html";</script>';
$a=$_SESSION['user'];
$sql='delete from users_message where run_id='.$a;
$pdo->query($sql);
header('location:user_login.php');
?><file_sep>
<link href="css/style.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/navigation.css"/>
<html>
<head>
<meta charset="utf-8" />
<title>主界面</title>
</head>
<body>
<?php include('css/header_index.php') ?>
<div class="nav">
<a class="left current" href="admin_login.php" >管理员登录</a>
<!--<a class="left" href="user_add.php">用户注册</a>-->
<a class="left " href="user_login.php">用户登录</a>
<a class="left " href="user_add.php">用户注册</a>
<!--<a href="user_login.php"></a>
<a class="right" href="admin_logout.php">退出登录</a>-->
<div style="clear: both;"></div>
</div>
<!--<div style="text-align: center;">
<a href="admin_login.php"><button class="bt2">管理员登录</button></a>
<a href="user_login.php"><button class="bt2">用户登录</button></a>
<a href="user_add.php"><button class="bt2">用户注册</button></a>
</div>-->
</body>
</html>
<file_sep><link rel="stylesheet" type="text/css" href="css/style.css"/>
<html>
<head>
<meta charset="utf-8" />
<title>管理员页面</title>
<link href="css/navigation.css" rel="stylesheet" type="text/css">
</head>
<body >
<?php include('css/header_admin.php') ?>
<div class="nav">
<a class="left " href="admin_add.php" >管理员注册</a>
<!--<a class="left" href="user_add.php">用户注册</a>-->
<a class="left " href="user_message.php">用户列表</a>
<a class="left " href="vege_message.php">蔬菜列表</a>
<a class="left " href="select_user.php">查找用户</a>
<a class="left " href="select_vege.php">查找蔬菜</a>
<a href="user_login.php"></a>
<a class="right" href="admin_logout.php">退出登录</a>
<div style="clear: both;"></div>
</div>
</body>
</html>
<?php
include 'conn/verify_admin.php';
?>
|
b4893a98337c3751118307b1106bf17a3184a2c5
|
[
"PHP"
] | 3 |
PHP
|
Axchgit/test
|
ba920592557386c72b701e54851e4a17c5e50beb
|
7cb8a370333f564446a3f6416bbecba10c99df5a
|
refs/heads/master
|
<repo_name>gitmics/Vidzy<file_sep>/README.md
# Vidzy
Basic project to learn MEAN stack from Udemy tutorial - https://blog.udemy.com/node-js-tutorial/
Check that tutorial to see how to create the database.
|
e94d679e4b5d2281f5f9e3fad05872550bcc6f97
|
[
"Markdown"
] | 1 |
Markdown
|
gitmics/Vidzy
|
cbac4aa317be7760d13a9c225e3e435c85f9cfef
|
bb1df91b58d39491e7840558e3435add846aa0a9
|
refs/heads/master
|
<repo_name>vdesu/dashboard<file_sep>/Dockerfile
FROM tomcat:8.5.50-jdk8-openjdk
COPY target/dashboard-1.0.war /usr/local/tomcat/webapps/ROOT.war
COPY target/dashboard-1.0.war /usr/local/tomcat/webapps/dashboard.war
CMD ["catalina.sh","run"]
<file_sep>/src/main/webapp/js/index.js
console.log("log index.js");
var myApp=angular.module('myApp',[]);
myApp.controller('mainController',function($scope,$log,$http,$filter) {
prodarr=[2373,2374,2365,
2375,9575,2363,9769,
2370,2366,2364,2376,
2380,2369,9623,2381,
2371,2368,9376]
var ltag="12clrg";
var prod=-1;
var urlPart1="https://bug.oraclecorp.com/pls/bug/WEBBUG_REPORTS.do_edit_report?rpt_title=&fcont_arr=";
var urlPart2="&fid_arr=1&fcont_arr=10%2C11%2C30%2C40&fid_arr=4&fcont_arr=%3D&fid_arr=159&fcont_arr=&fid_arr=122&fcont_arr=AND&fid_arr=136&fcont_arr=&fid_arr=138&fcont_arr=syaddula&fid_arr=30&fcont_arr=INTERNAL%25&fid_arr=200&fcont_arr=&fid_arr=10&fcont_arr=off&fid_arr=157&fcont_arr=off&fid_arr=166&fcont_arr=";
var urlPart3="&fid_arr=125&fcont_arr=N&fid_arr=165&fcont_arr=N&fid_arr=161&fcont_arr=2&fid_arr=100&cid_arr=2&cid_arr=3&cid_arr=9&cid_arr=8&cid_arr=7&cid_arr=11&cid_arr=6&cid_arr=13&f_count=15&c_count=8&query_type=2";
$http.get('/bugapis/webapi/resources/countlrg/-1?tag='+ltag)
.success(function (result){
$scope.allLRG=result;
console.log(result);
})
.error(function (data, status){
console.log(data);
});
prod=prodarr[1];
$http.get('/bugapis/webapi/resources/countlrg/'+prodarr[0]+'?tag='+ltag)
.success(function (result){
$scope.apLRG=result;
$scope.apURL=urlPart1+prodarr[0]+urlPart2;
console.log(result);
})
.error(function (data, status){
console.log(data);
});
$http.get('/bugapis/webapi/resources/countlrg/'+prodarr[1]+'?tag='+ltag)
.success(function (result){
$scope.ibyLRG=result;
$scope.ibyURL=urlPart1+prodarr[1]+urlPart2+ltag+urlPart3;
console.log(result);
})
.error(function (data, status){
console.log(data);
});
$http.get('/bugapis/webapi/resources/countlrg/'+prodarr[2]+'?tag='+ltag)
.success(function (result){
$scope.ceLRG=result;
$scope.ceURL=urlPart1+prodarr[2]+urlPart2+ltag+urlPart3;
console.log(result);
})
.error(function (data, status){
console.log(data);
});
$http.get('/bugapis/webapi/resources/countlrg/'+prodarr[3]+'?tag='+ltag)
.success(function (result){
$scope.arLRG=result;
$scope.arURL=urlPart1+prodarr[3]+urlPart2+ltag+urlPart3;
console.log(result);
})
.error(function (data, status){
console.log(data);
});
$http.get('/bugapis/webapi/resources/countlrg/'+prodarr[4]+'?tag='+ltag)
.success(function (result){
$scope.vrmLRG=result;
$scope.vrmURL=urlPart1+prodarr[4]+urlPart2+ltag+urlPart3;
console.log(result);
})
.error(function (data, status){
console.log(data);
});
$http.get('/bugapis/webapi/resources/countlrg/'+prodarr[5]+'?tag='+ltag)
.success(function (result){
$scope.iexLRG=result;
$scope.iexURL=urlPart1+prodarr[5]+urlPart2+ltag+urlPart3;
console.log(result);
})
.error(function (data, status){
console.log(data);
});
$http.get('/bugapis/webapi/resources/countlrg/'+prodarr[6]+'?tag='+ltag)
.success(function (result){
$scope.arbLRG=result;
$scope.arbURL=urlPart1+prodarr[6]+urlPart2+ltag+urlPart3;
console.log(result);
})
.error(function (data, status){
console.log(data);
});
$http.get('/bugapis/webapi/resources/countlrg/'+prodarr[7]+'?tag='+ltag)
.success(function (result){
$scope.glLRG=result;
$scope.glURL=urlPart1+prodarr[7]+urlPart2+ltag+urlPart3;
console.log(result);
})
.error(function (data, status){
console.log(data);
});
$http.get('/bugapis/webapi/resources/countlrg/'+prodarr[8]+'?tag='+ltag)
.success(function (result){
$scope.zxLRG=result;
$scope.zxURL=urlPart1+prodarr[8]+urlPart2+ltag+urlPart3;
console.log(result);
})
.error(function (data, status){
console.log(data);
});
$http.get('/bugapis/webapi/resources/countlrg/'+prodarr[9]+'?tag='+ltag)
.success(function (result){
$scope.faLRG=result;
$scope.faURL=urlPart1+prodarr[9]+urlPart2+ltag+urlPart3;
console.log(result);
})
.error(function (data, status){
console.log(data);
});
$http.get('/bugapis/webapi/resources/countlrg/'+prodarr[10]+'?tag='+ltag)
.success(function (result){
$scope.xlaLRG=result;
$scope.xlaURL=urlPart1+prodarr[10]+urlPart2+ltag+urlPart3;
console.log(result);
})
.error(function (data, status){
console.log(data);
});
$http.get('/bugapis/webapi/resources/countlrg/'+prodarr[11]+'?tag='+ltag)
.success(function (result){
$scope.jaLRG=result;
$scope.jaURL=urlPart1+prodarr[11]+urlPart2+ltag+urlPart3;
console.log(result);
})
.error(function (data, status){
console.log(data);
});
$http.get('/bugapis/webapi/resources/countlrg/'+prodarr[12]+'?tag='+ltag)
.success(function (result){
$scope.jeLRG=result;
$scope.jeURL=urlPart1+prodarr[12]+urlPart2+ltag+urlPart3;
console.log(result);
})
.error(function (data, status){
console.log(data);
});
$http.get('/bugapis/webapi/resources/countlrg/'+prodarr[13]+'?tag='+ltag)
.success(function (result){
$scope.jgLRG=result;
$scope.jgURL=urlPart1+prodarr[13]+urlPart2+ltag+urlPart3;
console.log(result);
})
.error(function (data, status){
console.log(data);
});
$http.get('/bugapis/webapi/resources/countlrg/'+prodarr[14]+'?tag='+ltag)
.success(function (result){
$scope.jlLRG=result;
$scope.jlURL=urlPart1+prodarr[14]+urlPart2+ltag+urlPart3;
console.log(result);
})
.error(function (data, status){
console.log(data);
});
$http.get('/bugapis/webapi/resources/countlrg/'+prodarr[15]+'?tag='+ltag)
.success(function (result){
$scope.exmLRG=result;
$scope.exmURL=urlPart1+prodarr[15]+urlPart2+ltag+urlPart3;
console.log(result);
})
.error(function (data, status){
console.log(data);
});
$http.get('/bugapis/webapi/resources/countlrg/'+prodarr[16]+'?tag='+ltag)
.success(function (result){
$scope.funLRG=result;
$scope.funURL=urlPart1+prodarr[16]+urlPart2+ltag+urlPart3;
console.log(result);
})
.error(function (data, status){
console.log(data);
});
$http.get('/bugapis/webapi/resources/countlrg/'+prodarr[17]+'?tag='+ltag)
.success(function (result){
$scope.biLRG=result;
$scope.biURL=urlPart1+prodarr[17]+urlPart2+ltag+urlPart3;
console.log(result);
})
.error(function (data, status){
console.log(data);
});
});
myApp.directive("tile", function(){
return {
templateUrl: 'resources/directives/tile.html',
replace: true,
}
});
|
444d86bf9bde5220811ff60cd441ff4f2dba7342
|
[
"JavaScript",
"Dockerfile"
] | 2 |
JavaScript
|
vdesu/dashboard
|
0827f286bb4fd5d12acfa989c4720d4c69dd6b82
|
9e1d0bae7df42ab070b1b46fea57f4cb9fa3c0fc
|
refs/heads/master
|
<file_sep>def prime?(x)
new_ints = []
ints = [*2..Math.sqrt(x)]
ints.each do |i|
new_ints << x % i
end
new_ints
if x == 2
return true
elsif x == 3
return true
elsif x > 3 and new_ints.include?(0) == false
return true
else
return false
end
end
|
0df1b2c3fb1f33c341a908d5a435a0675deef37d
|
[
"Ruby"
] | 1 |
Ruby
|
bfitzpa5/prime-ruby-001-prework-web
|
920bd1cb6a3bff997daac4435ca83478e55b5ade
|
115b4adb8fc29fbc057a400307035d1e04e878e1
|
refs/heads/master
|
<repo_name>justindhill/Snooball<file_sep>/README.md
# Snooball [](https://travis-ci.org/justindhill/snooball)
A simple Reddit client using Texture
<file_sep>/Snooball/Model/LinkType.swift
//
// LinkType.swift
// Snooball
//
// Created by <NAME> on 3/13/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import reddift
enum LinkType {
case selfPost
case image
case webLink
init?(link: Link) {
self = .selfPost
}
}
extension Link {
var linkType: LinkType? {
get { return LinkType(link: self) }
}
}
<file_sep>/Snooball/Link List/LinkCellNode.swift
//
// LinkCellNode.swift
// Snooball
//
// Created by <NAME> on 3/12/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import reddift
import AsyncDisplayKit
import OpenGraph
fileprivate let INTERITEM_PADDING: CGFloat = 16
fileprivate let THUMBNAIL_SIDELEN: CGFloat = 75
fileprivate let THUMBNAIL_CORNER_RADIUS: CGFloat = 3
class LinkCellNode: ASCellNode {
let titleLabel = ASTextNode()
let previewImageNode = ASNetworkImageNode()
let link: Link
let subredditLabel = ASTextNode()
let scoreLabel = ASTextNode()
let commentCountLabel = ASTextNode()
let domainLabel = ASTextNode()
let scoreIconNode = ASImageNode()
let commentsIconNode = ASImageNode()
let separatorNode = ASDisplayNode()
static var numberFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter
}()
init(link: Link) {
self.link = link
super.init()
self.automaticallyManagesSubnodes = true
self.titleLabel.maximumNumberOfLines = 0
self.previewImageNode.imageModificationBlock = { image in
return LinkCellNode.roundedCroppedImage(image: image, cornerRadius: THUMBNAIL_CORNER_RADIUS)
}
self.titleLabel.isLayerBacked = true
self.previewImageNode.isLayerBacked = true
self.subredditLabel.isLayerBacked = true
self.scoreLabel.isLayerBacked = true
self.commentCountLabel.isLayerBacked = true
self.scoreIconNode.isLayerBacked = true
self.commentsIconNode.isLayerBacked = true
self.separatorNode.isLayerBacked = true
self.commentsIconNode.contentMode = UIViewContentMode.center
self.commentsIconNode.image = UIImage(named: "comments")
self.commentsIconNode.imageModificationBlock = ASImageNodeTintColorModificationBlock(.lightGray)
self.scoreIconNode.contentMode = UIViewContentMode.center
self.scoreIconNode.image = UIImage(named: "score")
self.scoreIconNode.imageModificationBlock = ASImageNodeTintColorModificationBlock(.lightGray)
self.previewImageNode.defaultImage = LinkCellNode.placeholderImage
self.applyLink(link: link)
self.backgroundColor = UIColor.white
self.separatorNode.backgroundColor = UIColor.lightGray
self.separatorNode.style.preferredLayoutSize = ASLayoutSize(width: ASDimensionAuto, height: ASDimensionMake(0.5))
}
func applyLink(link: Link) {
let titlePara = NSMutableParagraphStyle()
titlePara.lineHeightMultiple = Constants.titleTextLineHeightMultiplier
self.titleLabel.attributedText = NSAttributedString(string: link.title, attributes: [
NSFontAttributeName: UIFont.preferredFont(forTextStyle: .subheadline),
NSParagraphStyleAttributeName: titlePara
])
if (link.thumbnail != "default") {
if link.thumbnail == "self" {
self.previewImageNode.url = nil
} else if let url = URL(string: link.thumbnail) {
self.previewImageNode.url = url
}
} else if let url = URL(string: link.url) {
// set the url to a dummy url to prevent the image from being hidden during layout if the OpenGraph
// image URL hasn't been discovered yet
self.previewImageNode.url = URL(string: "about:blank")
OpenGraph.fetch(url: url, completion: { [weak self] (og, error) in
if let og = og, let imageUrlString = og[.image], let imageUrl = URL(string: imageUrlString) {
self?.previewImageNode.url = imageUrl
}
})
} else {
self.previewImageNode.url = nil
}
self.subredditLabel.attributedText = metadataAttributedString(string: link.subreddit, bold: true)
self.scoreLabel.attributedText = metadataAttributedString(string: LinkCellNode.numberFormatter.string(from: NSNumber(integerLiteral: link.score)) ?? "0")
self.commentCountLabel.attributedText = metadataAttributedString(string: LinkCellNode.numberFormatter.string(from: NSNumber(integerLiteral: link.numComments)) ?? "0")
self.setNeedsLayout()
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
let size = CGSize(width: THUMBNAIL_SIDELEN, height: THUMBNAIL_SIDELEN)
self.previewImageNode.style.minSize = size
self.previewImageNode.style.maxSize = size
let textVerticalStack = ASStackLayoutSpec.vertical()
textVerticalStack.style.flexGrow = 1.0
textVerticalStack.style.flexShrink = 1.0
let titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 16)
textVerticalStack.children = [ASInsetLayoutSpec(insets: titleInsets, child: self.titleLabel)]
let horizontalContentStack = ASStackLayoutSpec.horizontal()
horizontalContentStack.children = [textVerticalStack]
if self.previewImageNode.url != nil {
let imageVerticalStack = ASStackLayoutSpec.vertical()
imageVerticalStack.children = [self.previewImageNode]
horizontalContentStack.children?.append(imageVerticalStack)
} else {
self.previewImageNode.isHidden = true
}
let wrapperVerticalStack = ASStackLayoutSpec.vertical()
wrapperVerticalStack.children = [horizontalContentStack, metadataBarLayoutSpec(), separatorNode]
let cellInsets = UIEdgeInsets(top: Constants.verticalPageMargin, left: Constants.horizontalPageMargin, bottom: 0, right: Constants.horizontalPageMargin)
return ASInsetLayoutSpec(insets: cellInsets, child: wrapperVerticalStack)
}
func metadataBarLayoutSpec() -> ASLayoutSpec {
let horizontalStack = ASStackLayoutSpec.horizontal()
horizontalStack.children = [
self.subredditLabel,
ASInsetLayoutSpec(insets: UIEdgeInsetsMake(0, 7, 0, 0), child: scoreIconNode),
ASInsetLayoutSpec(insets: UIEdgeInsetsMake(0, 3, 0, 0), child: scoreLabel),
ASInsetLayoutSpec(insets: UIEdgeInsetsMake(0, 7, 0, 0), child: commentsIconNode),
ASInsetLayoutSpec(insets: UIEdgeInsetsMake(0, 3, 0, 0), child: commentCountLabel)
]
return ASInsetLayoutSpec(insets: UIEdgeInsets(top: INTERITEM_PADDING / 2, left: 0, bottom: Constants.verticalPageMargin, right: 0), child: horizontalStack)
}
func metadataAttributedString(string: String, bold: Bool = false) -> NSAttributedString {
let fontSize = UIFont.preferredFont(forTextStyle: .caption1).pointSize
let weight = bold ? UIFontWeightSemibold : UIFontWeightRegular
let attributes = [
NSForegroundColorAttributeName: UIColor.lightGray,
NSFontAttributeName: UIFont.systemFont(ofSize: fontSize, weight: weight)
]
return NSAttributedString(string: string, attributes: attributes)
}
static var placeholderImage: UIImage? {
get {
let size = CGSize(width: THUMBNAIL_SIDELEN, height: THUMBNAIL_SIDELEN)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
UIColor.lightGray.setFill()
let drawingRect = CGRect(origin: CGPoint.zero, size: size)
let maskPath = UIBezierPath(roundedRect: drawingRect, cornerRadius: THUMBNAIL_CORNER_RADIUS)
maskPath.addClip()
let context = UIGraphicsGetCurrentContext()
context?.fill(drawingRect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
static func roundedCroppedImage(image: UIImage, cornerRadius radius: CGFloat) -> UIImage {
var modifiedImage: UIImage?
UIGraphicsBeginImageContextWithOptions(CGSize(width: THUMBNAIL_SIDELEN, height: THUMBNAIL_SIDELEN), false, 0)
var drawingRect = CGRect(origin: CGPoint.zero, size: image.size)
let ratio: CGFloat = image.size.width / image.size.height
if ratio > 1 {
let width = THUMBNAIL_SIDELEN * ratio
drawingRect = CGRect(x: -(width - THUMBNAIL_SIDELEN) / 2, y: 0, width: width, height: THUMBNAIL_SIDELEN)
} else {
let height = THUMBNAIL_SIDELEN / ratio
drawingRect = CGRect(x: 0, y: -(height - THUMBNAIL_SIDELEN) / 2, width: THUMBNAIL_SIDELEN, height: height)
}
let maskPath = UIBezierPath(roundedRect: drawingRect, cornerRadius: radius)
maskPath.addClip()
image.draw(in: drawingRect)
modifiedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
assert(modifiedImage != nil)
return modifiedImage ?? image
}
}
<file_sep>/Snooball/Link Detail View/CommentCell.swift
//
// CommentCell.swift
// Snooball
//
// Created by <NAME> on 3/26/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import AsyncDisplayKit
import reddift
import TSMarkdownParser
class CommentCell: ASCellNode {
let depth: Int
let contentNode: ASDisplayNode
let colorRail = ASDisplayNode()
var unhighlightedBackgroundColor: UIColor?
let colorSequence = [
UIColor.black, // dummy color
UIColor(red: 239/255, green: 69/255, blue: 61/255, alpha: 1.0), // r
UIColor(red: 253/255, green: 145/255, blue: 60/255, alpha: 1.0), // o
UIColor(red: 248/255, green: 207/255, blue: 79/255, alpha: 1.0), // y
UIColor(red: 47/255, green: 112/255, blue: 77/255, alpha: 1.0), // g
UIColor(red: 26/255, green: 118/255, blue: 217/255, alpha: 1.0), // b
UIColor(red: 36/255, green: 72/255, blue: 133/255, alpha: 1.0), // i
UIColor(red: 99/255, green: 62/255, blue: 147/255, alpha: 1.0), // v
]
init(contentNode: ASDisplayNode, depth: Int) {
self.depth = depth
self.contentNode = contentNode
super.init()
self.automaticallyManagesSubnodes = true
self.backgroundColor = UIColor(red: 237.0/255.0, green: 238.0/255.0, blue: 240.0/255.0, alpha: 1)
self.contentNode.style.flexShrink = 1.0
self.contentNode.style.flexGrow = 1.0
self.colorRail.backgroundColor = self.colorSequence[depth % self.colorSequence.count]
self.colorRail.style.preferredLayoutSize = ASLayoutSize(width: ASDimensionMake(3.0), height: ASDimensionAuto)
self.selectionStyle = .none
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
let hStack = ASStackLayoutSpec.horizontal()
if (self.depth > 0) {
hStack.children?.append(self.colorRail)
}
hStack.children?.append(self.contentNode)
hStack.style.flexGrow = 1.0
let insetSpec = ASInsetLayoutSpec(insets: UIEdgeInsets(
top: 0,
left: CGFloat(self.depth * 6),
bottom: 0,
right: 0),
child: hStack)
insetSpec.style.flexGrow = 1.0
insetSpec.style.flexShrink = 1.0
return insetSpec
}
override var isHighlighted: Bool {
didSet(value) {
if value {
self.unhighlightedBackgroundColor = self.contentNode.backgroundColor
self.contentNode.backgroundColor = self.contentNode.backgroundColor?.darkened(byPercent: 0.1)
} else if let unhighlightedBackgroundColor = self.unhighlightedBackgroundColor {
self.unhighlightedBackgroundColor = nil
self.contentNode.backgroundColor = unhighlightedBackgroundColor
}
}
}
}
<file_sep>/Snooball/Utilities/DRPRefreshControl+Extensions.swift
//
// DRPRefreshControl+Extensions.swift
// Snooball
//
// Created by <NAME> on 5/29/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import DRPLoadingSpinner
extension DRPRefreshControl {
class func customizedRefreshControl() -> DRPRefreshControl {
let refreshControl = DRPRefreshControl()
refreshControl.loadingSpinner.drawCycleDuration = 0.65;
refreshControl.loadingSpinner.rotationCycleDuration = 1.15;
refreshControl.loadingSpinner.drawTimingFunction = DRPLoadingSpinnerTimingFunction.sharpEaseInOut()
return refreshControl
}
}
<file_sep>/Podfile
target 'Snooball' do
use_frameworks!
pod 'Texture'
pod 'reddift', :git => "https://github.com/sonsongithub/reddift", :branch => "master", :submodules => true
pod 'OpenGraph'
pod 'TSMarkdownParser'
pod 'Reveal-SDK'
pod 'DRPLoadingSpinner/Texture'
end
<file_sep>/Snooball/Link Detail View/SelfLinkDetailHeader.swift
//
// SelfLinkDetailHeader.swift
// Snooball
//
// Created by <NAME> on 3/13/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import AsyncDisplayKit
import reddift
class SelfLinkDetailHeader: ASCellNode {
let link: Link
let InterItemVerticalSpacing: CGFloat = 12.0
let titleLabel = ASTextNode()
let scoreIconNode = ASImageNode()
let scoreLabel = ASTextNode()
let upvoteRatioIconNode = ASImageNode()
let upvoteRatioLabel = ASTextNode()
let timeAgoIconNode = ASImageNode()
let timeAgoLabel = ASTextNode()
let authorInfoLabel = ASTextNode()
let selfTextLabel = ASTextNode()
let separatorNode = ASDisplayNode()
let contentNode = ASVideoNode()
init(link: Link) {
self.link = link
super.init()
self.automaticallyManagesSubnodes = true
self.contentNode.backgroundColor = UIColor.black
self.contentNode.contentMode = .scaleAspectFit
self.scoreIconNode.image = UIImage(named: "score")
self.upvoteRatioIconNode.image = UIImage(named: "score")
self.timeAgoIconNode.image = UIImage(named: "clock")
self.separatorNode.style.preferredLayoutSize = ASLayoutSize(width: ASDimensionAuto, height: ASDimensionMake(0.5))
self.separatorNode.backgroundColor = Constants.separatorColor
self.contentNode.shouldAutoplay = true
self.contentNode.shouldAutorepeat = true
self.contentNode.muted = true
self.applyLink(link)
}
private func applyLink(_ link: Link) {
self.titleLabel.attributedText = NSAttributedString(string: link.title, attributes: self.titleFontAttributes())
self.scoreLabel.attributedText = NSAttributedString(string: String(link.score))
self.upvoteRatioLabel.attributedText = NSAttributedString(string: String(link.upvoteRatio))
self.timeAgoLabel.attributedText = NSAttributedString(string: String(link.createdUtc))
self.selfTextLabel.attributedText = NSAttributedString(string: String(link.selftext), attributes: self.selfTextFontAttributes())
self.authorInfoLabel.attributedText = NSAttributedString(string: "by \(link.author) in \(link.subreddit)")
if let thumbnailUrl = URL(string: link.thumbnail) {
self.contentNode.url = thumbnailUrl
}
if let linkUrl = URL(string: link.url) {
if linkUrl.pathExtension == "gifv" {
let replacementUrlString = linkUrl.absoluteString.replacingOccurrences(of: "gifv", with: "mp4")
if let replacementUrl = URL(string: replacementUrlString) {
let asset = AVAsset(url: replacementUrl)
self.contentNode.asset = asset
}
} else {
self.contentNode.url = linkUrl
}
}
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
let headerMargins = UIEdgeInsetsMake(Constants.verticalPageMargin, Constants.horizontalPageMargin, 0, Constants.horizontalPageMargin)
let photoContainer = ASRatioLayoutSpec(ratio: (9/16), child: self.contentNode)
photoContainer.style.preferredLayoutSize = ASLayoutSizeMake(ASDimensionMake("100%"), ASDimensionAuto)
let postInfoStack = ASInsetLayoutSpec(insets: headerMargins, child:
ASStackLayoutSpec(direction: .vertical, spacing: 0, justifyContent: .start, alignItems: .start, children: [
self.titleLabel,
self.postMetadataLayoutSpec(),
ASInsetLayoutSpec(insets: UIEdgeInsets(top: InterItemVerticalSpacing, left: 0, bottom: 0, right: 0), child: self.selfTextLabel)
])
)
var mainStackChildren = [ASLayoutElement]()
mainStackChildren.append(photoContainer)
mainStackChildren.append(postInfoStack)
mainStackChildren.append(self.separatorNode)
return ASStackLayoutSpec(direction: .vertical, spacing: 0, justifyContent: .start, alignItems: .start, children: mainStackChildren)
}
private func postMetadataLayoutSpec() -> ASLayoutSpec {
return ASInsetLayoutSpec(insets: UIEdgeInsets(top: InterItemVerticalSpacing, left: 0, bottom: 0, right: 0), child:
ASStackLayoutSpec(direction: .vertical, spacing: Constants.verticalPageMargin / 2, justifyContent: .start, alignItems: .start, children: [
ASStackLayoutSpec(direction: .horizontal, spacing: 3, justifyContent: .start, alignItems: .center, children: [
self.scoreIconNode,
self.scoreLabel,
ASInsetLayoutSpec(insets: UIEdgeInsets(top: 0, left: 7, bottom: 0, right: 0), child: self.upvoteRatioIconNode),
self.upvoteRatioLabel,
ASInsetLayoutSpec(insets: UIEdgeInsets(top: 0, left: 7, bottom: 0, right: 0), child: self.timeAgoIconNode),
self.timeAgoLabel
]),
self.authorInfoLabel
]
)
)
}
private func titleFontAttributes() -> [String: AnyObject] {
let para = NSMutableParagraphStyle()
para.lineHeightMultiple = Constants.titleTextLineHeightMultiplier
return [
NSFontAttributeName: UIFont.preferredFont(forTextStyle: .headline),
NSParagraphStyleAttributeName: para
]
}
private func selfTextFontAttributes() -> [String: AnyObject] {
let para = NSMutableParagraphStyle()
para.lineHeightMultiple = 1.05
return [
NSFontAttributeName: UIFont.preferredFont(forTextStyle: .body),
NSParagraphStyleAttributeName: para
]
}
}
<file_sep>/Snooball/Utilities/UIFont+Utils.swift
//
// UIFont+Utils.swift
// Snooball
//
// Created by <NAME> on 3/26/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
extension UIFont {
class func snb_preferredFont(forTextStyle style: UIFontTextStyle, weight: CGFloat) -> UIFont {
let font = UIFont.preferredFont(forTextStyle: style)
return UIFont.systemFont(ofSize: font.pointSize, weight: weight)
}
}
<file_sep>/Snooball/Link Detail View/CommentCellContentWrapperNode.swift
//
// CommentCellContentWrapperNode.swift
// Snooball
//
// Created by <NAME> on 4/1/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import AsyncDisplayKit
import reddift
import TSMarkdownParser
class CommentCellContentWrapperNode: ASDisplayNode {
let usernameLabel = ASTextNode()
let upvoteCountLabel = ASTextNode()
let upvoteIconImage = ASImageNode()
let timeAgoLabel = ASTextNode()
let commentBodyLabel = ASTextNode()
let separatorNode = ASDisplayNode()
let collapsed: Bool
init(comment: Comment, collapsed: Bool) {
self.collapsed = collapsed
super.init()
self.automaticallyManagesSubnodes = true
self.upvoteIconImage.image = UIImage(named: "score")
self.separatorNode.backgroundColor = Constants.separatorColor
self.separatorNode.style.preferredLayoutSize = ASLayoutSize(width: ASDimensionAuto, height: ASDimensionMake(0.5))
if !collapsed {
self.backgroundColor = UIColor.white
}
self.apply(comment: comment)
}
func apply(comment: Comment) {
var usernameColor: UIColor = .black
if comment.distinguished == .moderator {
usernameColor = .green
} else if comment.distinguished == .admin {
usernameColor = .orange
} else if comment.distinguished == .special {
usernameColor = .purple
}
let usernameAttributes: [String: Any] = [
NSFontAttributeName: UIFont.snb_preferredFont(forTextStyle: .caption1, weight: UIFontWeightSemibold),
NSForegroundColorAttributeName: usernameColor
]
self.usernameLabel.attributedText = NSAttributedString(string: comment.author, attributes: usernameAttributes)
let upvoteCountAttributes = [
NSFontAttributeName: UIFont.preferredFont(forTextStyle: .caption1),
NSForegroundColorAttributeName: UIColor.lightGray
]
self.upvoteCountLabel.attributedText = NSAttributedString(string: String(comment.ups), attributes: upvoteCountAttributes)
self.timeAgoLabel.attributedText = NSAttributedString(string: "7h", attributes: usernameAttributes)
let trimmedBody = comment.body.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
self.commentBodyLabel.attributedText = TSMarkdownParser.standard().attributedString(fromMarkdown: trimmedBody)
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
let stretchy = ASDisplayNode()
stretchy.style.flexGrow = 1.0
// stfu AsyncDisplayKit.
stretchy.style.preferredSize = CGSize(width: 5, height: 5)
let commentMetadataStack = ASStackLayoutSpec(direction: .horizontal, spacing: 3, justifyContent: .start, alignItems: .start, children: [
self.usernameLabel,
self.upvoteIconImage,
self.upvoteCountLabel,
stretchy,
self.timeAgoLabel
])
commentMetadataStack.style.flexGrow = 1.0
let mainVerticalStack = ASStackLayoutSpec(direction: .vertical, spacing: 5, justifyContent: .start, alignItems: .stretch, children: [
commentMetadataStack
])
mainVerticalStack.style.flexGrow = 1.0
mainVerticalStack.style.flexShrink = 1.0
if !self.collapsed {
mainVerticalStack.children?.append(self.commentBodyLabel)
}
let insetMainVerticalStack = ASInsetLayoutSpec(insets: UIEdgeInsetsMake(Constants.verticalPageMargin / 1.5, Constants.horizontalPageMargin, Constants.verticalPageMargin / 1.5, Constants.horizontalPageMargin), child: mainVerticalStack)
insetMainVerticalStack.style.flexShrink = 1.0
insetMainVerticalStack.style.flexGrow = 1.0
return ASStackLayoutSpec(direction: .vertical, spacing: 0, justifyContent: .start, alignItems: .stretch, children: [
insetMainVerticalStack,
self.separatorNode
])
}
}
<file_sep>/Snooball/Link Detail View/LinkDetailViewController.swift
//
// LinkDetailViewController.swift
// Snooball
//
// Created by <NAME> on 3/13/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import AsyncDisplayKit
import reddift
import TSMarkdownParser
import DRPLoadingSpinner
fileprivate let SECTION_HEADER = 0
fileprivate let SECTION_COMMENTS = 1
class LinkDetailViewController: ASViewController<ASDisplayNode>, ASTableDelegate, ASTableDataSource {
let link: Link
var commentTableAdapter: CommentThreadTableAdapter? = nil
let refreshControl = DRPRefreshControl.customizedRefreshControl()
init(link: Link) {
self.link = link
super.init(node: ASTableNode())
self.applyLink(link: link)
self.loadThread()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var tableNode: ASTableNode {
get { return self.node as! ASTableNode }
}
func loadThread() {
do {
try AppDelegate.shared.session?.getArticles(link, sort: .top, comments: nil, depth: 8, limit: 120, context: nil, completion: { [weak self] (result) in
if let comments = result.value?.1.children {
let commentAdapter = CommentThreadTableAdapter(comments: comments)
self?.commentTableAdapter = commentAdapter
DispatchQueue.main.async {
self?.tableNode.reloadData(completion: {
self?.refreshControl.endRefreshing()
})
}
}
})
} catch {
self.refreshControl.endRefreshing()
// TODO: empty/error state
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableNode.delegate = self
self.tableNode.dataSource = self
self.tableNode.view.separatorStyle = .none
self.refreshControl.add(to: self.tableNode) { [weak self] in
self?.loadThread()
}
}
func applyLink(link: Link) {
self.title = "\(link.numComments) comments"
}
private func commentIndexPathWith(tableIndexPath indexPath: IndexPath) -> IndexPath {
return IndexPath(row: indexPath.row, section: indexPath.section - 1)
}
//
// func insertCommentsFrom(adapter: CommentThreadTableAdapter) {
// let indices = 0..<adapter.numberOfComments
// let indexPaths = indices.map { (index) -> IndexPath in
// return IndexPath(row: index, section: SECTION_COMMENTS)
// }
//
// self.tableNode.performBatch(animated: false, updates: {
// self.tableNode.insertRows(at: indexPaths, with: .fade)
// }, completion: nil)
// }
func numberOfSections(in tableNode: ASTableNode) -> Int {
return 1 + (self.commentTableAdapter?.numberOfRootComments ?? 0)
}
func tableNode(_ tableNode: ASTableNode, numberOfRowsInSection section: Int) -> Int {
if section == SECTION_HEADER {
return 1
} else {
return self.commentTableAdapter?.numberOfChildrenForRootCommentAtIndex(index: section - 1) ?? 0
}
}
func tableNode(_ tableNode: ASTableNode, nodeForRowAt indexPath: IndexPath) -> ASCellNode {
if indexPath.section == SECTION_HEADER {
guard let linkType = link.linkType else {
fatalError("This link did not yield a valid link type")
}
switch linkType {
case .selfPost:
return SelfLinkDetailHeader(link: self.link)
default:
fatalError("Link type \(linkType) is not supported")
}
} else {
guard let adapter = self.commentTableAdapter else {
fatalError("Somehow got a request for a comment node even though we have no comments...")
}
let comment = adapter.commentAt(indexPath: commentIndexPathWith(tableIndexPath: indexPath))
if let rawComment = comment.comment as? Comment {
let isCollapsed = self.commentTableAdapter?.isCommentHidden(rawComment) ?? false
let commentContent = CommentCellContentWrapperNode(comment: rawComment, collapsed: isCollapsed)
return CommentCell(contentNode: commentContent, depth: comment.depth)
} else if let more = comment.comment as? More {
let textNode = ASTextCellNode()
textNode.text = "\(more.count) more comments"
return CommentCell(contentNode: textNode, depth: comment.depth)
}
}
return ASCellNode()
}
func tableNode(_ tableNode: ASTableNode, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
if indexPath.section == SECTION_HEADER {
return false
}
return true
}
func tableNode(_ tableNode: ASTableNode, didSelectRowAt indexPath: IndexPath) {
tableNode.deselectRow(at: indexPath, animated: true)
guard let changesets = self.commentTableAdapter?.toggleHidingForCommentAt(indexPath: commentIndexPathWith(tableIndexPath: indexPath)) else {
return
}
tableNode.performBatch(animated: true, updates: {
for changeset in changesets {
let adjustedIndexPaths = changeset.indexPaths.map({ (indexPath) -> IndexPath in
return IndexPath(row: indexPath.row, section: indexPath.section + 1)
})
switch changeset.type {
case .delete: tableNode.deleteRows(at: adjustedIndexPaths, with: .fade)
case .insert: tableNode.insertRows(at: adjustedIndexPaths, with: .fade)
case .update: tableNode.reloadRows(at: adjustedIndexPaths, with: .fade)
}
}
}, completion: nil)
}
}
<file_sep>/Snooball/Link Detail View/CommentTreeTableAdapter.swift
//
// CommentThreadTableAdapter.swift
// Snooball
//
// Created by <NAME> on 3/18/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import reddift
struct CommentWrapper {
let comment: Thing
let depth: Int
let indexPath: IndexPath
init(comment: Thing, indexPath: IndexPath, depth: Int = 0) {
self.depth = depth
self.comment = comment
self.indexPath = indexPath
}
}
class CommentThreadTableAdapter {
enum ChangeType {
case delete
case insert
case update
}
struct ChangeSet: CustomStringConvertible {
let type: ChangeType
let indexPaths: [IndexPath]
init(type: ChangeType, indexPaths: [IndexPath]) {
self.type = type
self.indexPaths = indexPaths
}
var description: String {
get {
return "\(self.type): \(self.indexPaths)"
}
}
}
var flattenedComments: [[CommentWrapper]]
let comments: [Thing]
private var hiddenCommentIds = Set<String>()
init(comments: [Thing]) {
self.comments = comments
self.flattenedComments = []
var commentTrees = [[CommentWrapper]]()
for comment in comments {
if let comment = comment as? Comment {
commentTrees.append(self.commentTreeFor(rootComment: comment, sectionNumber: commentTrees.count))
}
}
self.flattenedComments = commentTrees
}
private func commentTreeFor(rootComment comment: Comment, sectionNumber: Int) -> [CommentWrapper] {
var commentTree = [CommentWrapper(comment: comment, indexPath: IndexPath(row: 0, section: sectionNumber))]
if !self.hiddenCommentIds.contains(comment.id) {
commentTree.append(contentsOf: self.flattenedComments(with: comment.replies.children, hiddenPaths: nil, depth: 1, indexOffset: 1))
}
return commentTree
}
private func flattenedComments(with comments: [Thing], hiddenPaths: Set<IndexPath>? = nil, depth: Int = 0, indexOffset: Int = 0) -> [CommentWrapper] {
var flattened = [CommentWrapper]()
for (index, comment) in comments.enumerated() {
flattened.append(CommentWrapper(comment: comment, indexPath: IndexPath(indexes: [index + indexOffset]), depth: depth))
if let comment = comment as? Comment, !self.hiddenCommentIds.contains(comment.id) {
flattened.append(contentsOf: flattenedComments(with: comment.replies.children, hiddenPaths: hiddenPaths, depth: depth + 1))
}
}
return flattened
}
private func numberOfVisibleDescendantsInSubtree(root: Comment) -> Int {
var visibleDescendants = 0
for child in root.replies.children {
if let child = child as? Comment, !self.hiddenCommentIds.contains(child.id) {
visibleDescendants += 1
visibleDescendants += self.numberOfVisibleDescendantsInSubtree(root: child)
} else if child is More {
visibleDescendants += 1
}
}
return visibleDescendants
}
var numberOfRootComments: Int {
get { return self.flattenedComments.count }
}
func numberOfChildrenForRootCommentAtIndex(index: Int) -> Int {
return self.flattenedComments[index].count
}
func commentAt(indexPath: IndexPath) -> CommentWrapper {
return self.flattenedComments[indexPath.section][indexPath.row]
}
func isCommentHidden(_ comment: Comment) -> Bool {
return self.hiddenCommentIds.contains(comment.id)
}
func toggleHidingForCommentAt(indexPath: IndexPath) -> [ChangeSet] {
guard let rootComment = self.commentAt(indexPath: IndexPath(row: 0, section: indexPath.section)).comment as? Comment else {
assertionFailure("Couldn't find the root comment for the comment we're meant to toggle")
return []
}
var changesets = [
ChangeSet(type: .update, indexPaths: [indexPath])
]
guard let comment = self.commentAt(indexPath: indexPath).comment as? Comment else {
return []
}
if self.hiddenCommentIds.contains(comment.id) {
self.hiddenCommentIds.remove(comment.id)
} else {
self.hiddenCommentIds.insert(comment.id)
}
let numberOfAffectedChildren = self.numberOfVisibleDescendantsInSubtree(root: comment)
if numberOfAffectedChildren > 0 {
let indexOfFirstChild = indexPath.row + 1
let indexPathRange = (indexOfFirstChild..<indexOfFirstChild + numberOfAffectedChildren).map { (row) -> IndexPath in
return IndexPath(row: row, section: indexPath.section)
}
if self.hiddenCommentIds.contains(comment.id) {
changesets.append(ChangeSet(type: .delete, indexPaths: indexPathRange))
} else {
changesets.append(ChangeSet(type: .insert, indexPaths: indexPathRange))
}
}
self.flattenedComments[indexPath.section] = self.commentTreeFor(rootComment: rootComment, sectionNumber: indexPath.section)
return changesets
}
}
<file_sep>/Snooball/Utilities/UIColor+Extensions.swift
//
// UIColor+Extensions.swift
// Snooball
//
// Created by <NAME> on 4/9/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
extension UIColor {
func darkened(byPercent percent: CGFloat) -> UIColor {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
func darken(_ component: CGFloat, _ percent: CGFloat) -> CGFloat {
return component - ((percent * 100) / 255)
}
return UIColor(red: darken(red, percent), green: darken(green, percent), blue: darken(blue, percent), alpha: alpha)
}
}
<file_sep>/.travis.yml
language: objective-c
osx_image: xcode8.2
xcode_workspace: Snooball.xcworkspace
xcode_scheme: Snooball
before_install: pod repo update master --silent && pod install
script: xcodebuild -workspace Snooball.xcworkspace -scheme Snooball build CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO PROVISIONING_PROFILE="" | xcpretty && exit ${PIPESTATUS[0]}
<file_sep>/Snooball/ListingFetcher.swift
//
// ListingFetcher.swift
// Snooball
//
// Created by <NAME> on 3/12/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
import reddift
fileprivate let SERIAL_QUEUE_LABEL = "com.justinhill.snooball.listing_fetcher"
class ListingFetcher<T: Thing>: NSObject {
var paginator: Paginator? = Paginator()
let subreddit: Subreddit
let sortOrder: LinkSortType
private(set) var things = [T]()
private var _fetching = false
var fetching: Bool {
get {
return self.serialQueue.sync {
return _fetching
}
}
}
private var _moreAvailable = true
var moreAvailable: Bool {
get {
return self.serialQueue.sync {
return _moreAvailable
}
}
}
let serialQueue = DispatchQueue(label: SERIAL_QUEUE_LABEL)
init(subreddit: Subreddit, sortOrder: LinkSortType) {
self.subreddit = subreddit
self.sortOrder = sortOrder
super.init()
}
func fetchMore(completion outerCompletion: @escaping (_ error: Error?, _ newThings: Int) -> Void) {
do {
guard let paginator = self.paginator else {
outerCompletion(NSError(domain: "ListingFetcher", code: 0, userInfo: [NSLocalizedDescriptionKey: "Some unknown error happened"]), 0)
return
}
self.serialQueue.sync {
self._fetching = true
}
try AppDelegate.shared.session?.getList(paginator, subreddit: subreddit, sort: self.sortOrder, timeFilterWithin: .all, completion: { (result) in
guard let things = result.value?.children as? [T] else {
DispatchQueue.main.async {
outerCompletion(NSError(domain: "ListingFetcher", code: 0, userInfo: [NSLocalizedDescriptionKey: "Some unknown error happened"]), 0)
}
return
}
self.serialQueue.sync {
self.things = (self.things + things)
self._fetching = false
self._moreAvailable = result.value?.paginator.isVacant == false
self.paginator = result.value?.paginator
}
DispatchQueue.main.async {
outerCompletion(nil, things.count)
}
})
} catch {
DispatchQueue.main.async {
outerCompletion(error, 0)
}
}
}
}
<file_sep>/Snooball/Utilities/UIImage+Extensions.swift
//
// UIImage+Extensions.swift
// Snooball
//
// Created by <NAME> on 4/9/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
extension UIImage {
class func transparentImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, 0)
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
fatalError("ಠ_ಠ")
}
UIGraphicsEndImageContext()
return image
}
}
<file_sep>/Snooball/AppDelegate.swift
//
// AppDelegate.swift
// Snooball
//
// Created by <NAME> on 2/25/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
import reddift
/// Posted when the OAuth2TokenRepository object succeed in saving a token successfully into Keychain.
public let OAuth2TokenRepositoryDidSaveTokenName = Notification.Name(rawValue: "OAuth2TokenRepositoryDidSaveToken")
/// Posted when the OAuth2TokenRepository object failed to save a token successfully into Keychain.
public let OAuth2TokenRepositoryDidFailToSaveTokenName = Notification.Name(rawValue: "OAuth2TokenRepositoryDidFailToSaveToken")
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var session: Session?
class var shared: AppDelegate { get { return UIApplication.shared.delegate as! AppDelegate } }
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
window?.rootViewController = UINavigationController(rootViewController: LinkListViewController())
window?.makeKeyAndVisible()
if let name = UserDefaults.standard.string(forKey: "name") {
do {
let token = try OAuth2TokenRepository.token(of: name)
session = Session(token: token)
} catch { print(error) }
} else {
do {
try OAuth2Authorizer.sharedInstance.challengeWithAllScopes()
} catch {
print(error)
}
}
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return OAuth2Authorizer.sharedInstance.receiveRedirect(url, completion: {(result) -> Void in
switch result {
case .failure(let error):
print(error)
case .success(let token):
DispatchQueue.main.async(execute: { [weak self] () -> Void in
do {
try OAuth2TokenRepository.save(token: token, of: token.name)
UserDefaults.standard.set(token.name, forKey: "name")
self?.session = Session(token: token)
NotificationCenter.default.post(name: OAuth2TokenRepositoryDidSaveTokenName, object: nil, userInfo: nil)
} catch {
NotificationCenter.default.post(name: OAuth2TokenRepositoryDidFailToSaveTokenName, object: nil, userInfo: nil)
print(error)
}
})
}
})
}
}
<file_sep>/Snooball/Link List/LinkListViewController.swift
//
// LinkListViewController.swift
// Snooball
//
// Created by <NAME> on 2/25/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
import AsyncDisplayKit
import reddift
import DRPLoadingSpinner
class LinkListViewController: ASViewController<ASDisplayNode>, UIViewControllerPreviewingDelegate, ASTableDelegate, ASTableDataSource {
var subreddit: Subreddit
var listingFetcher: ListingFetcher<Link>
var previewingContext: UIViewControllerPreviewing?
let refreshControl = DRPRefreshControl.customizedRefreshControl()
var tableNode: ASTableNode {
get { return self.node as! ASTableNode }
}
init() {
self.subreddit = Subreddit(subreddit: "popular")
self.listingFetcher = ListingFetcher(subreddit: self.subreddit, sortOrder: .hot)
super.init(node: ASTableNode())
self.tableNode.delegate = self
self.tableNode.dataSource = self
self.tableNode.view.separatorStyle = .none
self.title = self.subreddit.displayName
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.refreshControl.add(to: self.tableNode) { [weak self] in
self?.reloadThread()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let selectedIndexPath = self.tableNode.indexPathForSelectedRow {
self.tableNode.deselectRow(at: selectedIndexPath, animated: false)
}
}
private func reloadThread() {
let fetcher = ListingFetcher<Link>(subreddit: self.listingFetcher.subreddit, sortOrder: self.listingFetcher.sortOrder)
fetcher.fetchMore { [weak self] (error, count) in
self?.listingFetcher = fetcher
self?.tableNode.reloadData(completion: {
self?.refreshControl.endRefreshing()
})
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if let previewingContext = self.previewingContext {
self.unregisterForPreviewing(withContext: previewingContext)
}
if self.traitCollection.forceTouchCapability == .available {
self.previewingContext = self.registerForPreviewing(with: self, sourceView: self.view)
}
}
func numberOfSections(in tableNode: ASTableNode) -> Int {
return 1
}
func tableNode(_ tableNode: ASTableNode, numberOfRowsInSection section: Int) -> Int {
return self.listingFetcher.things.count
}
func tableNode(_ tableNode: ASTableNode, nodeForRowAt indexPath: IndexPath) -> ASCellNode {
let cell = LinkCellNode(link: self.listingFetcher.things[indexPath.row])
return cell
}
func tableNode(_ tableNode: ASTableNode, didSelectRowAt indexPath: IndexPath) {
let detailVC = LinkDetailViewController(link: self.listingFetcher.things[indexPath.row])
self.navigationController?.pushViewController(detailVC, animated: true)
}
func tableNode(_: ASTableNode, willBeginBatchFetchWith context: ASBatchContext) {
let priorCount = self.listingFetcher.things.count
self.listingFetcher.fetchMore { [weak self] (error, newLinkCount) in
if let error = error {
print(error)
context.completeBatchFetching(false)
return
}
var indexPaths = [IndexPath]()
for index in (priorCount..<priorCount + newLinkCount) {
indexPaths.append(IndexPath(row: index, section: 0))
}
if priorCount == 0 {
self?.tableNode.reloadData()
} else {
self?.tableNode.insertRows(at: indexPaths, with: .none)
}
context.completeBatchFetching(true)
}
}
func shouldBatchFetch(for tableNode: ASTableNode) -> Bool {
return (self.listingFetcher.moreAvailable && !self.listingFetcher.fetching)
}
// MARK: Previewing
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = self.tableNode.indexPathForRow(at: location) else {
return nil;
}
previewingContext.sourceRect = self.tableNode.rectForRow(at: indexPath)
return LinkDetailViewController(link: self.listingFetcher.things[indexPath.row])
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
self.navigationController?.show(viewControllerToCommit, sender: self)
}
}
<file_sep>/Snooball/Constants.swift
//
// Constants.swift
// Snooball
//
// Created by <NAME> on 3/13/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
struct Constants {
static let horizontalPageMargin: CGFloat = 12.0
static let verticalPageMargin: CGFloat = 16.0
static let titleTextLineHeightMultiplier: CGFloat = 1.2
static let separatorColor = UIColor.lightGray
}
|
9f65cccecbe1e7261d75977e088e97a548d8dfff
|
[
"Swift",
"Markdown",
"Ruby",
"YAML"
] | 18 |
Swift
|
justindhill/Snooball
|
45e576491a8752e6475527fe3cd30688adcaca4b
|
974e25a42378418a5cf5327c44793da386199651
|
refs/heads/master
|
<repo_name>strananh/MyTestProject<file_sep>/MyNewSource.cpp
#include "stdio.h"
int main(int argc, char* argv[]) {
printf("Hello World!"); /* this is my new resource */
}
|
05e3e22c406d5f8af8f54e197960602ef3d6e5b4
|
[
"C++"
] | 1 |
C++
|
strananh/MyTestProject
|
88acb01622472cb3df3b393322949bc7acd57c22
|
265194f9230ec91ca9248c0fd4a0e219e318b3eb
|
refs/heads/master
|
<repo_name>paigeshin/AOS_Kotlin_function_with_function_argument_example<file_sep>/README.md
### MainActivity
```kotlin
class MainActivity : AppCompatActivity() {
val fruitsList = listOf(Fruit("Mango","Tom"), Fruit("Apple","Joe"),Fruit("Banana","Mark") , Fruit("Guava","Mike"),Fruit("Lemon","Mike"),Fruit("Pear","Frank"),Fruit("Orange","Joe"))
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
my_recycler_view.setBackgroundColor(Color.YELLOW)
my_recycler_view.layoutManager = LinearLayoutManager(this)
//4. send function argument which is defined on this activity to recyclerView
my_recycler_view.adapter = MyRecyclerViewAdapter(fruitsList, {selectedFruitItem: Fruit -> listItemClicked(selectedFruitItem)})
}
//3. define function which takes `fruit` from adapter
private fun listItemClicked(fruit: Fruit) {
Toast.makeText(this@MainActivity, "Supplier name is ${fruit.supplier}", Toast.LENGTH_LONG).show()
}
}
```
### RecyclerView Adapter
```kotlin
// 1. This RecyclerViewAdapter second argument as Function.
class MyRecyclerViewAdapter(
private val fruitsList:List<Fruit>,
private val clickListener:(Fruit) -> Unit)
: RecyclerView.Adapter<MyViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val listItem = layoutInflater.inflate(R.layout.list_item,parent,false)
return MyViewHolder(listItem)
}
override fun getItemCount(): Int {
return fruitsList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bind(fruitsList.get(position), clickListener)
}
}
class MyViewHolder(val view : View) : RecyclerView.ViewHolder(view){
// 2. ViewHolder bind function takes second argument as Function by passing `fruit` object.
fun bind(fruit: Fruit, clickListener:(Fruit) -> Unit) {
view.name_text_view.text = fruit.name
view.setOnClickListener {
clickListener(fruit)
}
}
}
```<file_sep>/app/src/main/java/com/anushka/recyclerviewdemo1/MainActivity.kt
package com.anushka.recyclerviewdemo1
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
val fruitsList = listOf(Fruit("Mango","Tom"), Fruit("Apple","Joe"),Fruit("Banana","Mark") , Fruit("Guava","Mike"),Fruit("Lemon","Mike"),Fruit("Pear","Frank"),Fruit("Orange","Joe"))
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
my_recycler_view.setBackgroundColor(Color.YELLOW)
my_recycler_view.layoutManager = LinearLayoutManager(this)
//4. send function argument which is defined on this activity to recyclerView
my_recycler_view.adapter = MyRecyclerViewAdapter(fruitsList, {selectedFruitItem: Fruit -> listItemClicked(selectedFruitItem)})
}
//3. define function which takes `fruit` from adapter
private fun listItemClicked(fruit: Fruit) {
Toast.makeText(this@MainActivity, "Supplier name is ${fruit.supplier}", Toast.LENGTH_LONG).show()
}
}
<file_sep>/settings.gradle
include ':app'
rootProject.name='RecyclerViewDemo1'
<file_sep>/app/src/main/java/com/anushka/recyclerviewdemo1/Fruit.kt
package com.anushka.recyclerviewdemo1
data class Fruit(val name:String,val supplier:String)
|
6e1458abfc3cca3e8b245b06ad069c6c30f2af2f
|
[
"Markdown",
"Gradle",
"Kotlin"
] | 4 |
Markdown
|
paigeshin/AOS_Kotlin_function_with_function_argument_example
|
2df5c9a550f544ca89baac8805e36741d68188e7
|
4ed8e6004f1774354d7553c2abd2f16aba691d3e
|
refs/heads/master
|
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';
import { JwtHelperService } from '@auth0/angular-jwt';
import { environment } from '../../environments/environment';
import { User } from '../_models/user';
@Injectable({
providedIn: 'root'
})
export class AuthService {
baseUrl = environment.apiUrl + 'auth/';
jwtHelper = new JwtHelperService();
photoUrl = new BehaviorSubject<string>('../../assets/user.png');
currentPhotoUrl = this.photoUrl.asObservable();
user: User;
constructor(private http: HttpClient) {}
changeMemberPhoto(photoUrl: string) {
this.photoUrl.next(photoUrl);
}
login(model: any) {
return this.http.post(this.baseUrl + 'login', model).pipe(
map((response: any) => {
const user = response;
if (user) {
localStorage.setItem('token', user.token);
const currentUser: User = user.user;
this.user = currentUser;
localStorage.setItem('user', JSON.stringify(currentUser));
this.changeMemberPhoto(currentUser.photoUrl);
}
})
);
}
register(user: User) {
return this.http.post(this.baseUrl + 'register', user);
}
loggedIn() {
const token = localStorage.getItem('token');
return !this.jwtHelper.isTokenExpired(token);
}
getUsername(): string {
const token = localStorage.getItem('token');
return this.jwtHelper.decodeToken(token).unique_name;
}
getUserId(): string {
const token = localStorage.getItem('token');
return this.jwtHelper.decodeToken(token).nameid;
}
getUser(): User {
const user: User = JSON.parse(localStorage.getItem('user'));
return user;
}
setUserPhoto(photoUrl: string) {
// const user: User = JSON.parse(localStorage.getItem('user'));
this.user.photoUrl = photoUrl;
localStorage.setItem('user', JSON.stringify(this.user));
}
}
|
59ccc1f6c147ddc975c22253678eb05bb8abf2b1
|
[
"TypeScript"
] | 1 |
TypeScript
|
Pranay-Sane/DatingApp
|
65a89e56ca4aa6a2daf738e7e2555764e8ed1910
|
0a96c07dbc93140c07dc4a5d9b15e8553e816770
|
refs/heads/master
|
<repo_name>samuelsnyder/rmf-todo.txt<file_sep>/README.md
# rmf-todo.txt
Plugin for todo.sh for applying the "rm" action, which either removes a specified line, or a term within that line, to any file in the todo directory
` todo.sh rmf FILENAME #ITEM [TERM]`
<file_sep>/rmf
#! /bin/bash
# rmf
# Removes specified line from specified file in todo directory
errmsg="rmf FILE [#ITEM [TERM...]]"
usage="usage: $errmsg"
# check that arg is a file
shift # $1 is file name
[[ $1 = "usage" ]] && echo $usage && exit
file="$TODO_DIR/$1"
[[ ! -f "$file" ]] && echo "No file named '$file' in $TODO_DIR" && exit
shift # $1 is item number if given
# DELETE FILE
if [ -z "$@" ]; then
# no additional arguments given, delete file
if [ $TODOTXT_FORCE = 0 ]; then
echo "Delete '$file'? (y/n)"
read ANSWER
else
ANSWER="y"
fi
if [ "$ANSWER" = "y" ]; then
rm $file
echo "'$file' deleted."
fi
exit
fi
# check that arg is a number
[[ ! $1 =~ [0-9]+ ]] && echo $usage && exit
item=$1
shift # $@, if given, is search term
# get the todo
getTodo "$item" $file
if [ -z "$@" ]; then
# DELETE TASK ITEM
# no search terms given
if [ $TODOTXT_FORCE = 0 ]; then
echo "Delete '$todo'? (y/n)"
read ANSWER
else
ANSWER="y"
fi
if [ "$ANSWER" = "y" ]; then
if [ $TODOTXT_PRESERVE_LINE_NUMBERS = 0 ]; then
# delete line (changes line numbers)
sed -i.bak -e $item"d" -e '/./!d' "$file"
else
# leave blank line behind (preserves line numbers)
# sed -i.bak -e $item"c\\" "$file"
sed -i.bak -e $item"c\\" "$file"
fi
if [ $TODOTXT_VERBOSE -gt 0 ]; then
echo "$item $todo"
echo "$(getPrefix $file): $item deleted."
fi
else
echo "$(getPrefix $file): No tasks were deleted."
fi
else
# DELETE TERM FROM ITASK ITEM
sed -i.bak \
-e $item"s/^\((.) \)\{0,1\} *$@ */\1/g" \
-e $item"s/ *$@ *\$//g" \
-e $item"s/ *$@ */ /g" \
-e $item"s/ *$@ */ /g" \
-e $item"s/$@//g" \
"$TODO_FILE"
getNewtodo "$item"
if [ "$todo" = "$newtodo" ]; then
[ $TODOTXT_VERBOSE -gt 0 ] && echo "$item $todo"
die "TODO: '$@' not found; no removal done."
fi
if [ $TODOTXT_VERBOSE -gt 0 ]; then
echo "$item $todo"
echo "TODO: Removed '$@' from task."
echo "$item $newtodo"
fi
fi
|
457dca79e51ecfb292709823ca9fc1d08517a38e
|
[
"Markdown",
"Shell"
] | 2 |
Markdown
|
samuelsnyder/rmf-todo.txt
|
04d13d51b59e35a45863702e14e0941c0d6b261c
|
b714effaf28f24fc146a7c1a905771ffbace102f
|
refs/heads/master
|
<file_sep>from django.db import models
# Create your models here.
class Todo(models.Model):
todo_id = models.CharField(unique=True, max_length=5)
title = models.CharField(max_length=50)
keyword = models.CharField(max_length=50)
main_text = models.CharField(max_length=2000)
split_text1 = models.CharField(max_length=300,blank=True)
split_text2 = models.CharField(max_length=300,blank=True)
split_text3 = models.CharField(max_length=300 ,blank=True)
split_text4 = models.CharField(max_length=300 ,blank=True)
split_text5 = models.CharField(max_length=300 ,blank=True)
split_text6 = models.CharField(max_length=300 ,blank=True)
split_text7 = models.CharField(max_length=300 ,blank=True)
split_text8 = models.CharField(max_length=300 ,blank=True)
split_text9 = models.CharField(max_length=300 ,blank=True)
split_text10 = models.CharField(max_length=300 ,blank=True)
split_text11 = models.CharField(max_length=300 ,blank=True)
update_date = models.DateTimeField('date published')
<file_sep>import MeCab
text = '今日は晴れかな?'
#天気の関連語をまとめたgazetteer
weather_set = set(['晴れ','天気','雨'])
weather_set2 = ['ラジオ','ゲーム','アニメ']
mecab = MeCab.Tagger("-Ochasen") #MeCabの取得
tokens = mecab.parse(text) #分かち書きを行う
token = tokens.split("\n")
list = list(weather_set2)
#以下、分かち書き後の単語を抽出
for ele in token:
element = ele.split("\t")
if element[0] == "EOS":
break
# 単語の表層を取得
surface = element[0]
if text.find(weather_set2[0])>=0 or text.find(weather_set2[1])>=0 or text.find(weather_set2[2])>=0:
break
else:
if surface in weather_set:
print(text)
<file_sep>import re
def delete_ha(s):
"""
括弧と括弧内文字列を削除
"""
""" brackets to zenkaku """
table = {
"(": "(",
")": ")",
"<": "<",
">": ">",
"{": "{",
"}": "}",
"[": "[",
"]": "]"
}
for key in table.keys():
s = s.replace(key, table[key])
""" delete zenkaku_brackets """
l = ['([^(|^)]*)', '【[^【|^】]*】', '<[^<|^>]*>', '[[^[|^]]*]',
'「[^「|^」]*」', '{[^{|^}]*}', '〔[^〔|^〕]*〕', '〈[^〈|^〉]*〉']
for l_ in l:
s = re.sub(l_, "", s)
""" recursive processing """
return s
<file_sep>from django import forms
from.models import Todo
class TodoForm(forms.ModelForm):
class Meta:
model = Todo
fields = ['todo_id','keyword', 'title', 'main_text', 'update_date']
exclude = ['todo_id', 'update_date']
<file_sep>asn1crypto==1.2.0
beautifulsoup4==4.8.1
certifi==2019.9.11
cffi==1.13.1
chardet==3.0.4
Click==7.0
cryptography==2.8
cssselect==1.0.3
dj-database-url==0.5.0
dj-static==0.0.6
Django==2.1.5
django-heroku==0.3.1
django-toolbelt==0.0.1
Flask==1.1.1
gunicorn==20.0.0
idna==2.8
itsdangerous==1.1.0
Jinja2==2.10.3
lxml==4.3.3
MarkupSafe==1.1.1
parsel==1.5.1
psycopg2==2.8.4
pycparser==2.19
PyDispatcher==2.0.5
PyHamcrest==1.9.0
pyOpenSSL==19.0.0
PySocks==1.7.1
pytz==2019.3
queuelib==1.5.0
requests==2.22.0
Scrapy==1.6.0
six==1.13.0
soupsieve==1.9.3
static3==0.7.0
urllib3==1.24.2
w3lib==1.20.0
Werkzeug==0.16.0
whitenoise==4.1.4
win-inet-pton==1.1.0
wincertstore==0.2
<file_sep># -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from BeautifulSoup import BeautifulSoup
file_path = '/tutorial/jawiki-latest-abstract.xml'
line_count = 17522478
def file_read_generator():
"""
XMLをパースして<doc> 〜 </doc>を読み込み返却するgenerator
:rtype: str
"""
separate = '</doc>'
f = open(file_path, 'r')
count = 0
txt = ''
# Fileを1行ずつ読む
for line in f:
txt += line
count += 1
if separate in line:
result = txt
txt = ''
yield result
if count % 1000 == 0:
print '{}/{}'.format(count, line_count)
for body in file_read_generator():
# parseする
soup = BeautifulSoup(body)
print soup.title
print soup.abstract
# print soup.findAll('anchor')
print 'finish'
<file_sep>var data4=[
['オペレーティングシステム','コンピュータのオペレーション(操作・運用・運転)を司るシステムソフトウェアである。'],
['共有メモリ','情報処理において複数のプログラムが同時並行的にアクセスするメモリ'],
['データベース','検索や蓄積が容易にできるよう整理された情報の集まり。'],
['プロセス間通信','コンピュータの動作において、複数プロセス(の複数スレッド)間でデータをやりとりする仕組み。通信プロセスは、同一コンピュータ内で帰結するローカル、ネットワーク接続された別のコンピュータと相互にリモート、などのほかに多様な観点で分類され、スレッド間の通信帯域幅とレイテンシや扱うデータの種類も多種多様である。'],
['IPアドレス(アイピーアドレス)','「Internet Protocol Address」の略称,インターネット上でパソコンなどの通信機器を識別するための番号'],
['アクセスポイント','事業者が提供するネットワークに接続するための接続点。多くの事業者が全国複数箇所にアクセスポイントを用意している。ユーザーは、専用線や電話回線などを使って近くのアクセスポイントに接続し、事業者の提供するネットワークサービスを利用する。'],
['OSI(Open System Interconnection)','コンピュータの持つべき通信機能を階層構造に分割したモデルである。 国際標準化機構(ISO)によって策定された。 OSI基本参照モデル、OSIモデルなどとも呼ばれ、通信機能(通信プロトコル)を7つの階層に分けて定義している。'],['データリンク層','通信プロトコル(通信手順/通信規約)の機能や役割を階層構造で整理したモデルを構成する層の一つで、回線やネットワークで物理的に繋がれた二台の機器の間でデータの受け渡しを行うもの。'],
['アプリケーション層','通信ネットワークにおいてホストが用いる共用のプロトコルとインターフェースメソッドを示す抽象化レイヤーである。この抽象概念はコンピュータネットワークの標準的なモデルであるインターネット・プロトコル・スイート( TCP/IP参照モデル)および開放型システム間相互接続モデル(OSI参照モデル)の両方で使われている。 '],
['プレゼンテーション層','OSI参照モデルにおける七階層の内の第六層である。これはアプリケーション層からのサービス要求に応じ、またセッション層に対してサービス要求を行う。'],
['セッション層','OSI参照モデルにおける七階層の内の第五層である。そこではプレゼンテーション層からのサービス要求に応じ、またトランスポート層に対してサービス要求を行う'],
['トランスポート層','コンピュータと電気通信では、TCP/IP参照モデルにおけるの4階層の内の第3層の事である。上位のアプリケーション層からのサービス要求に応じ、また下位のインターネット層に対してサービス要求を行う。'],
['ネットワーク層','OSI参照モデルにおける7階層の内の下から第3層の事である。TCP/IP参照モデルにおける4階層に対応付ける場合は、下から第2層のインターネット層に割り当てる。'],
['物理層','OSI参照モデルにおける第一層で、伝送媒体(電気信号や光)上にてビット転送を行うための物理コネクションを確立・維持・解放する電気・機械・機能・手続き的な手段を定義する。 '],
['Local Area Network(ローカル・エリア・ネットワーク)','広くても一施設内程度の規模で用いられるコンピュータネットワークのこと。その頭文字をつづったLAN(ラン)と書かれる場合も多い。一般家庭、企業のオフィスや研究所、工場等で広く使用されている。'],
['インターネット・プロトコル・スイート','インターネットおよびインターネットに接続する大多数の商用ネットワークで利用できる通信規約(通信プロトコル)一式である。インターネット・プロトコル・スイートは、インターネットの黎明期に定義され、現在でも標準的に用いられている2つのプロトコル'],
['ティム・バーナーズ=リー','ロバート・カイリューとともにWorld Wide Web(WWW)を考案し、ハイパーテキストシステムを実装・開発した人物である。またURL、HTTP、HTML の最初の設計は彼によるものである。 '],
['World Wide Web','インターネット上で提供されているハイパーテキストシステムである。'],
['モデム(modem)','デジタル通信の送受信装置である。デジタル信号を伝送路の特性に合わせたアナログ信号にデジタル変調して送信するとともに、伝送路からのアナログ信号をデジタル信号に復調して受信するデータ回線終端装置の機能部分であり、通信方式は、ITU-Tにより標準化されている。'],
['イーサネット','コンピューターネットワークの規格の1つ。世界中のオフィスや家庭で一般的に使用されている有線のLAN (Local Area Network) で最も使用されている技術規格で、OSI参照モデルの下位2つの層である物理層とデータリンク層に関して規定している。'],
['10GBASE-T','UTPによる10ギガビット・イーサネット《10GbE》)規格'],
['DHCP','UDP/IPネットワークで使用されるネットワーク管理プロトコルであり、コンピュータがネットワークに接続する際に必要な設定情報を自動的に割り当てるために使用する。'],
['Domain Name System(ドメイン・ネーム・システム、DNS)','インターネットを使った階層的な分散型データベースシステムである。1983年にInformation Sciences Institute (ISI) のポール・モカペトリスとジョン・ポステルにより開発された。現在では主にインターネット上のホスト名や電子メールに使われるドメイン名と、IPアドレスとの対応づけ(正引き、逆引き)を管理するために使用されている。 '],
['FTP','コンピュータネットワーク上のクライアントとサーバの間でファイル転送を行うための通信プロトコルの一つである。 '],
['HTTP','HTMLなどのコンテンツの送受信に用いられる通信プロトコルである。主としてWorld Wide Webにおいて、WebブラウザとWebサーバとの間での転送に用いられる。日本標準仕様書ではハイパテキスト転送プロトコルとも呼ばれる。'],
['Internet Message Access Protocol(インターネット メッセージ アクセス プロトコル、IMAP(アイマップ)','メールサーバ上の電子メールにアクセスし操作するためのプロトコル。クライアントとサーバがTCPを用いて通信する場合、通常サーバー側はIMAP4ではポート番号143番、IMAP over SSL(IMAPS)では993番を利用する。 '],
['Internet Relay Chat(インターネット・リレー・チャット、略称 : IRC)','サーバを介してクライアントとクライアントが会話をする枠組みの名称である。インスタントメッセンジャーのプロトコルの一つに分類される。また、これに基づいて実装されるソフトをIRCクライアントと呼び、しばし略してクライアントもIRCと呼ばれる事がある。文章のみをやり取りして会話を行い、DCCなどを利用することでファイル転送も対応する。'],
['Network Time Protocol(ネットワーク・タイム・プロトコル、略称NTP','ネットワークに接続される機器において、機器が持つ時計を正しい時刻へ同期するための通信プロトコルである。 '],
['Simple Network Time Protocol(シンプルネットワークタイムプロトコル、SNTP','NTPパケットを利用した、簡単な時計補正プロトコルである。'],
['Post Office Protocol(ポスト オフィス プロトコル、POP','電子メールで使われるプロトコル(通信規約)のひとつ。ユーザがメールサーバから自分のメールを取り出す時に使用する、メール受信用プロトコル。現在は、改良されたPOP3 (POP Version 3) が使用されている。 '],
['Simple Mail Transfer Protocol(シンプル メール トランスファー プロトコル、SMTP','簡易メール転送プロトコルは、インターネットで電子メールを転送するプロトコルである。通常 ポート番号 25 を利用する。 転送先のサーバを特定するために、DNS の MXレコードが使われる。RFC 5321 で標準化されている。'],
['Secure Shell(セキュアシェル、SSH)','暗号や認証の技術を利用して、安全にリモートコンピュータと通信するためのプロトコル。パスワードなどの認証部分を含むすべてのネットワーク上の通信が暗号化される。 '],
['Telnet(テルネット Teletype network)','IPネットワークにおいて、遠隔地にあるサーバやルーター等を端末から操作する通信プロトコル、またはそのプロトコルを利用するソフトウェアである。RFC 854で規定されている。 '],
['Extensible Messaging and Presence Protocol (XMPP)','オープンソースのインスタントメッセンジャーのプロトコルおよび、クライアント、サーバの総称である。'],
['Transmission Control Protocol(トランスミッション コントロール プロトコル、TCP)','伝送制御プロトコルといわれ、インターネット・プロトコル・スイートの中核プロトコルのひとつ。'],
['User Datagram Protocol(ユーザ データグラム プロトコル、UDP','主にインターネットで使用されるインターネット・プロトコル・スイートの中核プロトコルの一つ。'],
['Internet Control Message Protocol(インターネット制御通知プロトコル、ICMP','通信処理で使われるプロトコルのひとつで、Internet Protocolのデータグラム処理における誤りの通知や通信に関する情報の通知などのために使用される。'],['Point-to-Point Protocol','2点間を接続してデータ通信を行うための通信プロトコルである。 ']
];
var n = 30;//問題数
ar = new Array(n);
for (y2=0; y2<ar.length; y2++){
ar[y2] = new Array(n);
}
function shuffle(array) {
var n = array.length, t, i;
while (n) {
i = Math.floor(Math.random() * n--);
t = array[n];
array[n] = array[i];
array[i] = t;
}
return array;
}
function randomSelect(array, num){
let newArray = [];
while(newArray.length < num && array.length > 0){
// 配列からランダムな要素を選ぶ
const rand = Math.floor(Math.random() * array.length);
// 選んだ要素を別の配列に登録する
newArray.push(array[rand]);
// もとの配列からは削除する
array.splice(rand, 2);
}
return newArray;
}
var ary = new Array();
for (y3=0; y3<ary.length; y3++){
ary[y3] = new Array();
}
var test_array = [ 1, 2, 3];
function select_quiz_gene(){
for(var st = 0; st <ar.length ; st++){
ary = data4;
rand=Math.floor(Math.random() * ary.length);
var random = ary[rand];
// もとの配列からは削除する
ary.splice(rand, 1);
//random2 = new Array(ary.length);
random2 = ary;
const selected = randomSelect(random2.slice(), 2);
var randomNumber = Math.floor( Math.random() * (4 - 1) + 1 );
//ary = ary_origin;
// 配列arrayからランダムにnum個の要素を取り出す
//ary.push(ary[rand]);
t = shuffle(test_array);
ar[st][0] = random[0];
ar[st][t[0]] = random[1];
ar[st][t[1]] = selected[0][1];
ar[st][t[2]] = selected[1][1];
ar[st][4] = t[0];
}
return ar;
}
function getCol(matrix, col){
var column = [];
for(var i=0; i<matrix.length; i++){
column.push(matrix[i][col]);
}
return column;
}
var array = [
['光ファイバー','光ファイバの説明'],
['OSI参照モデル','OSI参照モデルの説明'],
['インターネット層','インターネット層の説明'],
['アプリケーション層','アプリケーション層の説明'],
['ルーター','ルーターの説明']
]; //..your 3x20 array
var a1 = getCol(array, 0); //Get first column
var qa = select_quiz_gene();
//count = 0; //問題番号
q_sel = 3; //選択肢の数
setReady();
//最初の問題
//quiz();
//初期設定
function setReady() {
count = 0; //問題番号
ansers = new Array(); //解答記録
ans_count = 0;
//最初の問題
quiz();
}
//問題表示
function quiz() {
var s, n;
//問題
document.getElementById("text_q").innerHTML = (count + 1) + "問目:" + qa[count][0]+"の説明で正しいのを選べ";
//選択肢
s = "";
for (n=1;n<=q_sel;n++) {
s += "【<a href='javascript:anser(" + n + ")'>" + n + ":" + qa[count][n] + "</a>】"+"<br>"+"<br>";
}
document.getElementById("text_s").innerHTML = s;
}
//解答表示
function anser(num) {
var s;
s = (count + 1) + "問目:";
//答え合わせ
if (num == qa[count][q_sel + 1]) {
//正解
ans_count++;
s += "○" + qa[count][num]+"正解数"+ans_count;
} else {
s += "×" + qa[count][num]+"正解数"+ans_count;
}
document.getElementById("text_a").innerHTML = s;
//次の問題を表示
count++;
if (count < qa.length) {
quiz();
}
else {
//終了
document.getElementById("text_q").innerHTML = "";
document.getElementById("text_s").innerHTML = "";
}
}
//解答表示
function anser(num) {
var s;
s = (count + 1) + "問目:";
//答え合わせ
if (num == qa[count][q_sel + 1]) {
//正解
ans_count++;
s += "○" + qa[count][num]+"正解数"+ans_count;
ansers[count] = "○";
} else {
s += "×" + qa[count][num]+"正解数"+ans_count;
ansers[count] = "×";
}
document.getElementById("text_a").innerHTML = s;
//次の問題を表示
count++;
if (count < qa.length) {
quiz();
} else {
//終了
s = "<table border='2'><caption>成績発表</caption>";
//1行目
s += "<tr><th>問題</th>";
for (n=0;n<qa.length;n++) {
s += "<th>" + (n+1) + "</th>";
}
s += "</tr>";
//2行目
s += "<tr><th>成績</th>";
for (n=0;n<qa.length;n++) {
s += "<td>" + ansers[n] + "</td>";
}
s += "</tr>";
s += "</table>";
document.getElementById("text_q").innerHTML = "";
//次の選択肢
s = "【<a href='javascript:history.back()'>前のページに戻る</a>】";
s += "【<a href='javascript:setReady()'>同じ問題を最初から</a>】";
s += "【<a href=''>次の問題に進む</a>】";
document.getElementById("text_s").innerHTML = s;
}
}
var qaa= data4;
var length = 20;
var ar_ox = new Array(1);
for(let y = 0; y < qaa.length; y++) {
ar_ox[y] = new Array(1).fill(0);
}
var ans_ox = new Array(1);
for(let y = 0; y < qaa.length; y++) {
ans_ox[y] = new Array(1).fill(0);
}
function dig_quest(){
for(var z = 0; z<ar_ox.length-1 ; z++){
var aryq = qaa;
randq=Math.floor(Math.random() * aryq.length);
var randomq = aryq[randq];
aryq.splice(randq, 1);
randomq2 = aryq;
var a_ox= randomq[0]
const selectedq = randomSelect(randomq2.slice(), 1);
rand2_1 = Math.floor(Math.random()*2 + 1) ;
if(rand2_1==2){
var b_ox = selectedq[0][1];
ans_ox[z][0] = selectedq[0][0];
ans_ox[z][1] = selectedq[0][1]
var c_ox = a_ox + 'とは' + b_ox;
ar_ox[z][0] = c_ox;
ar_ox[z][1] = 2 ;
}
else if(rand2_1==1){
var d_ox = selectedq[0][0] + 'とは' +selectedq[0][1];
ar_ox[z][0] = d_ox;
ar_ox[z][1] = 1;
}
}
}
dig_quest();
var qa_ox = [
['「テトリス(ゲーム)」を開発したのは、日本人だ。', 2],
['生きている間は、有名な人であっても広辞苑に載ることはない。 ', 1],
['現在、2000円札は製造を停止している。', 1],
['パトカーは、取り締まっている最中であれば、どこでも駐車違反になることはない。', 2],
['昆虫の中には、口で呼吸する昆虫もいる。 ', 2],
['一般的に体の水分は、男性より女性のほうが多く含まれている。', 2],
['たとえ1cmの高さであっても、地震によって起こるのは全て「津波」である。', 1],
['1円玉の直径は、ちょうど1cmになっている。', 2],
['塩はカロリー0である。 ', 1],
['「小中学校は、PTAを作らなければならない」と法律で定められている。', 2]
];
var count_ox = 0;
var correctNum_ox = 0;
var ans_count2=0;
window.onload = function() {
// 最初の問題を表示
var question_ox = document.getElementById('question_ox');
question_ox.innerHTML = (count_ox + 1) + '問目:' + ar_ox[count_ox][0]+ '〇か×か?';
};
// クリック時の答え判定
function hantei(btnNo) {
if (ar_ox[count_ox][1] == btnNo) {
correctNum_ox++;
}
if (count_ox == ar_ox.length-1) {
alert('あなたの正解数は' + correctNum_ox + '問です!');
}
// 次の問題表示
count_ox++;
var question_ox = document.getElementById('question_ox');
question_ox.innerHTML = (count_ox + 1) + '問目:' + ar_ox[count_ox][0]+ '〇か×か?';
if(btnNo==1){
if(ar_ox[count_ox-1][1]==2){
s = '不正解!' + ar_ox[count_ox-1][0] + 'は不正解.' +'<br><br>'+ '正解は'+ans_ox[count_ox-1][0]+'とは'+ ans_ox[count_ox-1][1]+'<br><br>'+'現在の正解数は'+ans_count2;
}
else if(ar_ox[count_ox-1][1]==1){
ans_count2++;
s ='正解!' + ar_ox[count_ox-1][0] + 'は正解'+'<br><br>'+'現在の正解数は'+ans_count2;
}
}
if(btnNo==2){
if(ar_ox[count_ox-1][1]==2){
ans_count2++;
s = '正解!' + ar_ox[count_ox-1][0] + 'は不正解.' +'<br><br>'+ '正解は'+ans_ox[count_ox-1][0]+'とは'+ ans_ox[count_ox-1][1]+'<br><br>'+'現在の正解数は'+ans_count2;
}
else if(ar_ox[count_ox-1][1]==1){
s ='不正解!' + ar_ox[count_ox-1][0] + 'は正解'+'<br><br>'+'現在の正解数は'+ans_count2;
}
}
document.getElementById("text_ans").innerHTML = s;
}
var quizzes = data4;
var quiz2;
init();
function init(){
var ra = Math.floor(Math.random() * quizzes.length);
quiz2 = quizzes[ra];
//問題用のフォームに表示する
document.getElementById("questionana").innerHTML = quiz2[1];
}
function doAnswer(){
//回答用のフォームに入力した値を取得
var answerForm = document.querySelector("#answerana");
var answer = answerForm.value;
//回答用フォームで入力した内容を削除する
answerForm.value = "";
//入力した内容が正しいか調べる
if (answer == quiz2[0]) {
//入力した内容が正解の時
right();
} else {
//入力した内容が不正解の時
wrong();
}
}
//正解の時に実行する関数
function right(){
alert("正解です");
init();
}
//不正解の時に実行する関数
function wrong(){
alert("不正解です");
}
<file_sep>from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('quest/', views.quest, name='quest'),
path('quest2/', views.quest2, name='quest2'),
path('quest3/', views.quest3, name='quest3'),
path('quest4/', views.quest4, name='quest4'),
path('new/', views.new, name='new'),
path('add/', views.add, name='add'),
path('<int:todo_id>/', views.detail, name='detail'),
path('add/<int:todo_id>/', views.update, name='update'),
path('delete/<int:todo_id>/', views.delete, name='delete'),
]
<file_sep>
import urllib.request as req
import sys
import io
import xml.etree.cElementTree as ET
import csv
import pprint
import numpy as np
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding=sys.stdout.encoding, errors="backslashreplace")
import MeCab
import sakujo
kaedetoneko=[]
with open('data1.csv',encoding='UTF-8') as f:
reader = csv.reader(f)
l = [row for row in reader]
ln = len(l)
print(l[1][1])
print(ln)
for a in range(ln-1):
s=a+1
l_y=l[s][0]
#print(l_y)
unko=l_y.replace('Wikipedia: ', '')
print(unko)
l_r=l[s][1]
l_y=str(l[s][0])
l_r=sakujo.delete_brackets(l_r)
#print(l_y)
tinko=l_r.replace(unko, '□')
tinko=tinko.replace('□は、', '')
tinko=tinko.replace('□とは、', '')
tinko=tinko.replace('□とは', '')
tinko=tinko.replace('とは', '')
tinko=tinko.replace('□は', '')
tinko=tinko.replace('□または', '')
tinko=tinko.replace('『□』は、', '')
tinko=tinko.replace('□,', '')
tinko=tinko.replace('□ ,', '')
tinko=tinko.replace('□、', '')
tinko=tinko.replace('□ 、', '')
tinko=tinko.replace('□。', '')
tinko=tinko.replace('□ ', '')
kaedetoneko.append([unko,tinko])
#print(l)
print(type('a'))
print(kaedetoneko)
with open('data2.csv', 'w', newline='',encoding='UTF-8') as f:
writer = csv.writer(f)
writer.writerows(kaedetoneko)
<file_sep>
import urllib.request as req
import sys
import io
import xml.etree.cElementTree as ET
import csv
import pprint
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding=sys.stdout.encoding, errors="backslashreplace")
import MeCab
#これ辞書↓
internet_set1 = set(['離散数学','応用数学','ケーブル','2次元配列','メモリ','オペレーティングシステム','ハードウェア','マルチメディア技術','フレーム','LAN','ゲートウェイ','アルゴリズム',
'プロトコル','TCP','IP','インターネット層','トランスポート層','DHCP','DNS','プロトコル','ルーター','イーサネット','イーサーネット','レイヤ2','スイッチング','レイヤ','トランザクション処理','セキュリティ','データベース','ネットワーク','ネットワーク','トポロジ','ケーブル','OSI参照モデル','2進数','16進数','ファイバ','0BASE','コリジョン','クロスサイトスクリプティング','Webサーバ','エンジニアリングシステム','クラスタ分析法',])
internet_set2 = set(['ネットワーク','トポロジ','ケーブル','OSI参照モデル','2進数','16進数','ファイバ','0BASE','コリジョン',])
internet_set3 = set(['イーサネット','イーサーネット','レイヤ2','スイッチング','レイヤ',])
internet_set4 = set(['TCP','IP','インターネット層','トランスポート層','DHCP','DNS','プロトコル','ルーター',])
anime_set = set(['アニメ','ラジオ','番組','テレビ','ゲーム','漫画','テレビジョン',])
internet_set = internet_set1
with open(r"C:\Users\hansa\Desktop\mysite\tutorial\jawiki-latest-abstract.xml",'r',encoding="utf-8_sig") as source:
# get an iterable
context_set = ET.iterparse(source, events=("start", "end"))
list =[
[]
]
#print(list)
for event, root in context_set:
# do something with elem
#elem.get('Wikipedia')
#child = root[0]
#context_list = list(root)
#child = context_list[2]
#print(child.tag,child.text)
#print(child.tag,child.text)
#for value,title in root.iter('abstract'),root.iter('title'):
#print(value.text,title.text)
##for result in root.findall('./doc/abstract'):
# print(result.text)
for solt in root.findall('title'):
#print(solt.text)
for result in root.findall('abstract'):
#list.append([solt.text,result.text])
#print(result.text)
text = result.text
mecab = MeCab.Tagger("-Ochasen") #MeCabの取得
tokens = mecab.parse(text) #分かち書きを行う
if type(tokens) is str:
token = tokens.split("\n")
for ele in token:
element = ele.split("\t")
if element[0] == "EOS":
break
# 単語の表層を取得
surface = element[0]
if surface in internet_set:
if surface not in anime_set:
list.append([solt.text,result.text])
#print(list)
#for child in root:
# print(child.tag,child.text)
# get rid of the elements after processing
root.clear()
def get_unique_list(seq):
seen = []
return [x for x in seq if x not in seen and not seen.append(x)]
list_copy=get_unique_list(list)
print(list_copy,sep='\n')
print(len(list))
print(len(list_copy))
with open('data6.csv', 'w', newline='',encoding='UTF-8') as f:
writer = csv.writer(f)
writer.writerows(list_copy)
<file_sep># -*- coding: utf-8 -*-
import scrapy
from tutorial.items import WikiItem
class QuotesSpider(scrapy.Spider):
name = 'wiki'
allowed_domains = ['www.nw-siken.com']
start_urls = ['https://www.nw-siken.com/kakomon/30_aki/']
def parse(self, response):
time.sleep(4)
item = WikiItem()
for i in response.xpath('//table/tbody/tr'):
item['name'] = i.xpath('td[2]/text()').extract_first()
item['context'] = i.xpath('td[3]/text()').extract()
print(i.xpath('td[2]/text()').extract_first())
print(i.xpath('td[3]/text()').extract())
yield item
<file_sep> for result in root.findall('title'):
if result.text == "Wikipedia: インターネット":
print(result.text)
for result in root.findall('title'):
print(result.text)
for result in root.findall('abstract'):
print(result.text)
if solt.text == "Wikipedia: 言語":
print(list)
break
import MeCab
text = '今日は晴れかな?'
#天気の関連語をまとめたgazetteer
weather_set = set(['晴れ','天気','雨'])
mecab = MeCab.Tagger("-Ochasen") #MeCabの取得
tokens = mecab.parse(text) #分かち書きを行う
token = tokens.split("\n")
#以下、分かち書き後の単語を抽出
for ele in token:
element = ele.split("\t")
if element[0] == "EOS":
break
# 単語の表層を取得
surface = element[0]
if surface in weather_set:
print(surface)
['離散数学','応用数学','ケーブル','2次元配列','メモリ','オペレーティングシステム','ハードウェア','マルチメディア技術','フレーム','LAN','ゲートウェイ','アルゴリズム',
'プロトコル','トランザクション処理','セキュリティ','データベース','ネットワーク','クロスサイトスクリプティング','Webサーバ','エンジニアリングシステム','クラスタ分析法',]
list_a = []
list_b = []
kaede=np.array(list_a)
toneko=np.array(list_b)
c = np.concatenate((kaede.T,toneko), axis = 0)
print(c)
unko=l_y.replace('Wikipedia: ', '').replace(' ','')
<file_sep># myapp/views.py
from django.shortcuts import render
import re
from django.http import HttpResponse, HttpResponseRedirect
from django.utils import timezone
from polls.models import Todo
from django.urls import reverse
from polls.forms import TodoForm
from flask import json
def index(request):
logged_in = False
name = None
if 'name' in request.POST and 'passwd' in request.POST:
request.session['name'] = request.POST['name']
request.session['passwd'] = request.POST['passwd']
if 'logout' in request.POST:
request.session.clear()
if 'name' in request.session and 'passwd' in request.session:
name = request.session['name']
logged_in = True
txt = 'ウィキ(ハワイ語: wiki)とは、不特定多数のユーザーが共同してウェブブラウザから直接コンテンツを編集するウェブサイトである。一般的なウィキにおいては、コンテンツはマークアップ言語によって記述されるか、リッチテキストエディタによって編集される[1]。ウィキはウィキソフトウェア(ウィキエンジンとも呼ばれる)上で動作する。ウィキソフトウェアはコンテンツ管理システムの一種であるが、サイト所有者や特定のユーザーによってコンテンツが作られるわけではないという点において、ブログソフトウェアなど他のコンテンツ管理システムとは異なる。またウィキには固まったサイト構造というものはなく、サイトユーザーのニーズに沿って様々にサイト構造を作り上げることことが可能であり、そうした点でも他のシステムとは異なっている[2]。 '
txt2 = re.sub(r'(?<=。)', "\t", txt)
sen = re.split(r'\t', txt2)
names = ['太郎', '次郎', '三郎', '四郎']
english_scores = [81, 72, 63, 94]
math_scores = [61, 70, 85, 80]
eng_key = '英語'
math_key = '数学'
d = {k : {eng_key : v1, math_key : v2} for k,v1,v2 in zip(names, english_scores, math_scores)}
todo_list = Todo.objects.all()
appt = [
["イルカを漢字で書くとどれ?","海豚","海牛","河豚",1],
["クラゲを漢字で書くとどれ?","水浮","水母","水星",2],
["カタツムリを漢字で書くとどれ?","禍牛","鍋牛","蝸牛",3],
["バッタを漢字で書くとどれ?","飛蝗","飛蟻","飛脚",1],
["タツノオトシゴを英語にするとどれ?","sea fish","sea horse","sea dragon",2],
["マグロを英語にするとどれ?","funa","suna","tuna",3],
["トンボを英語にするとどれ?","fly","dragonfly","butterfly",2],
["ヒトデを英語にするとどれ?","starfish","starshell","starmine",1],
["恒星の中で最も明るい星は?","デネブ","スピカ","シリウス",3],
["惑星の中で最も重たいのはどれ?","太陽","木星","天王星",2]
]
appt = json.dumps(appt)
params = {
'todo_list':todo_list,
'loggedIn':logged_in,
'name':name,
'sentence':sen,
'origin_sentence':txt,
'appt':appt,
}
return render(request, "polls/index.html", params)
def quest2(request):
return render(request, 'polls/quest2.html')
def quest3(request):
return render(request, 'polls/quest3.html')
def quest4(request):
return render(request, 'polls/quest4.html')
def quest(request):
return render(request, 'polls/quest.html')
def new(request):
return render(request, 'polls/new.html')
def add(request):
t1 = Todo()
t1.todo_id = len(Todo.objects.order_by('-todo_id'))+1
t1.update_date = timezone.now()
t = TodoForm(request.POST, instance=t1)
t.save()
return HttpResponseRedirect(reverse('index'))
def detail(request, todo_id):
todo = Todo.objects.get(todo_id=todo_id)
context = {'todo': todo}
return render(request, 'polls/new.html', context)
def update(request, todo_id):
t1 = Todo.objects.get(todo_id=todo_id)
t = TodoForm(request.POST, instance=t1)
t.save()
return HttpResponseRedirect(reverse('index'))
def delete(request, todo_id):
t = Todo.objects.get(todo_id=todo_id)
t.delete()
return HttpResponseRedirect(reverse('index'))
<file_sep>
import urllib.request as req
import sys
import io
import xml.etree.cElementTree as ET
import csv
import pprint
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding=sys.stdout.encoding, errors="backslashreplace")
import MeCab
text =''
#天気の関連語をまとめたgazetteer
weather_set = set(['晴れ','天気','雨'])
mecab = MeCab.Tagger("-Ochasen") #MeCabの取得
tokens = mecab.parse(text) #分かち書きを行う
token = tokens.split("\n")
#以下、分かち書き後の単語を抽出
for ele in token:
element = ele.split("\t")
if element[0] == "EOS":
break
# 単語の表層を取得
surface = element[0]
<file_sep>import re
def delete_brackets(s):
"""
括弧と括弧内文字列を削除
"""
""" brackets to zenkaku """
table = {
"(": "(",
")": ")",
"<": "<",
">": ">",
"{": "{",
"}": "}",
"[": "[",
"]": "]"
}
for key in table.keys():
s = s.replace(key, table[key])
""" delete zenkaku_brackets """
l = ['([^(|^)]*)', '【[^【|^】]*】', '<[^<|^>]*>', '[[^[|^]]*]',
'「[^「|^」]*」', '{[^{|^}]*}', '〔[^〔|^〕]*〕', '〈[^〈|^〉]*〉']
for l_ in l:
s = re.sub(l_, "", s)
""" recursive processing """
return delete_brackets(s) if sum([1 if re.search(l_, s) else 0 for l_ in l]) > 0 else s
<file_sep>var data4;
getCSVFile('/static/data2.csv');
function getCSVFile(url) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
createArray(xhr.responseText);
};
xhr.open("get", url, false);
xhr.send(null);
}
function createXMLHttpRequest() {
var XMLhttpObject = null;
XMLhttpObject = new XMLHttpRequest();
return XMLhttpObject;
}
function createArray(csvData) {
var tempArray = csvData.split("\r\n");
var csvArray = new Array();
for(var i = 0; i<tempArray.length;i++){
csvArray[i] = tempArray[i].split(",");
}
data4=csvArray;
}
var n = 2000//問題数
ar = new Array(n);
for (y2=0; y2<ar.length; y2++){
ar[y2] = new Array(n);
}
function shuffle(array) {
var n = array.length, t, i;
while (n) {
i = Math.floor(Math.random() * n--);
t = array[n];
array[n] = array[i];
array[i] = t;
}
return array;
}
function randomSelect(array, num){
let newArray = [];
while(newArray.length < num && array.length > 0){
// 配列からランダムな要素を選ぶ
const rand = Math.floor(Math.random() * array.length);
// 選んだ要素を別の配列に登録する
newArray.push(array[rand]);
// もとの配列からは削除する
array.splice(rand, 2);
}
return newArray;
}
var ary = new Array();
for (y3=0; y3<ary.length; y3++){
ary[y3] = new Array();
}
var test_array = [ 1, 2, 3];
for(var st = 0; st <ar.length ; st++){
ary = data4;
rand=Math.floor(Math.random() * ary.length);
var random = ary[rand];
// もとの配列からは削除する
ary.splice(rand, 1);
//random2 = new Array(ary.length);
random2 = ary;
const selected = randomSelect(random2.slice(), 2);
var randomNumber = Math.floor( Math.random() * (4 - 1) + 1 );
//ary = ary_origin;
// 配列arrayからランダムにnum個の要素を取り出す
//ary.push(ary[rand]);
t = shuffle(test_array);
ar[st][0] = random[0];
ar[st][t[0]] = random[1];
ar[st][t[1]] = selected[0][1];
ar[st][t[2]] = selected[1][1];
ar[st][4] = t[0];
}
function getCol(matrix, col){
var column = [];
for(var i=0; i<matrix.length; i++){
column.push(matrix[i][col]);
}
return column;
}
var array = [
['光ファイバー','光ファイバの説明'],
['OSI参照モデル','OSI参照モデルの説明'],
['インターネット層','インターネット層の説明'],
['アプリケーション層','アプリケーション層の説明'],
['ルーター','ルーターの説明']
]; //..your 3x20 array
var a1 = getCol(array, 0); //Get first column
var qa = ar;
//count = 0; //問題番号
q_sel = 3; //選択肢の数
setReady();
//最初の問題
//quiz();
//初期設定
function setReady() {
count = 0; //問題番号
ansers = new Array(); //解答記録
//最初の問題
quiz();
}
//問題表示
function quiz() {
var s, n;
//問題
document.getElementById("text_q").innerHTML = (count + 1) + "問目:" + qa[count][0]+"の説明で正しいのを選べ";
//選択肢
s = "";
for (n=1;n<=q_sel;n++) {
s += "【<a href='javascript:anser(" + n + ")'>" + n + ":" + qa[count][n] + "</a>】"+"<br>"+"<br>";
}
document.getElementById("text_s").innerHTML = s;
}
//解答表示
function anser(num) {
var s;
s = (count + 1) + "問目:";
//答え合わせ
if (num == qa[count][q_sel + 1]) {
//正解
s += "○" + qa[count][num];
} else {
s += "×" + qa[count][num];
}
document.getElementById("text_a").innerHTML = s;
//次の問題を表示
count++;
if (count < qa.length) {
quiz();
}
else {
//終了
document.getElementById("text_q").innerHTML = "";
document.getElementById("text_s").innerHTML = "";
}
}
//解答表示
function anser(num) {
var s;
s = (count + 1) + "問目:";
//答え合わせ
if (num == qa[count][q_sel + 1]) {
//正解
s += "○" + qa[count][num];
ansers[count] = "○";
} else {
s += "×" + qa[count][num];
ansers[count] = "×";
}
document.getElementById("text_a").innerHTML = s;
//次の問題を表示
count++;
if (count < qa.length) {
quiz();
} else {
//終了
s = "<table border='2'><caption>成績発表</caption>";
//1行目
s += "<tr><th>問題</th>";
for (n=0;n<qa.length;n++) {
s += "<th>" + (n+1) + "</th>";
}
s += "</tr>";
//2行目
s += "<tr><th>成績</th>";
for (n=0;n<qa.length;n++) {
s += "<td>" + ansers[n] + "</td>";
}
s += "</tr>";
s += "</table>";
document.getElementById("text_q").innerHTML = "";
//次の選択肢
s = "【<a href='javascript:history.back()'>前のページに戻る</a>】";
s += "【<a href='javascript:setReady()'>同じ問題を最初から</a>】";
s += "【<a href=''>次の問題に進む</a>】";
document.getElementById("text_s").innerHTML = s;
}
}
var qaa= data4;
var length = 20;
var ar_ox = new Array(1);
for(let y = 0; y < qaa.length; y++) {
ar_ox[y] = new Array(1).fill(0);
}
var ans_ox = new Array(1);
for(let y = 0; y < qaa.length; y++) {
ans_ox[y] = new Array(1).fill(0);
}
for(var z = 0; z<ar_ox.length-1 ; z++){
var aryq = qaa;
randq=Math.floor(Math.random() * aryq.length);
var randomq = aryq[randq];
aryq.splice(randq, 1);
randomq2 = aryq;
var a_ox= randomq[0]
const selectedq = randomSelect(randomq2.slice(), 1);
rand2_1 = Math.floor(Math.random()*2 + 1) ;
if(rand2_1==1){
var b_ox = selectedq[0][1];
ans_ox[z][0] = selectedq[0][0];
ans_ox[z][1] = selectedq[0][1]
var c_ox = a_ox + 'とは' + b_ox;
ar_ox[z][0] = c_ox;
ar_ox[z][1] = 1 ;
}
else if(rand2_1==2){
var d_ox = selectedq[0][0] + 'とは' +selectedq[0][1];
ar_ox[z][0] = d_ox;
ar_ox[z][1] = 2;
}
}
var qa_ox = [
['「テトリス(ゲーム)」を開発したのは、日本人だ。', 2],
['生きている間は、有名な人であっても広辞苑に載ることはない。 ', 1],
['現在、2000円札は製造を停止している。', 1],
['パトカーは、取り締まっている最中であれば、どこでも駐車違反になることはない。', 2],
['昆虫の中には、口で呼吸する昆虫もいる。 ', 2],
['一般的に体の水分は、男性より女性のほうが多く含まれている。', 2],
['たとえ1cmの高さであっても、地震によって起こるのは全て「津波」である。', 1],
['1円玉の直径は、ちょうど1cmになっている。', 2],
['塩はカロリー0である。 ', 1],
['「小中学校は、PTAを作らなければならない」と法律で定められている。', 2]
];
var count_ox = 0;
var correctNum_ox = 0;
window.onload = function() {
// 最初の問題を表示
var question_ox = document.getElementById('question_ox');
question_ox.innerHTML = (count_ox + 1) + '問目:' + ar_ox[count_ox][0]+ '〇か×か?';
};
// クリック時の答え判定
function hantei(btnNo) {
if (ar_ox[count_ox][1] == btnNo) {
correctNum_ox++;
}
if (count_ox == ar_ox.length-1) {
alert('あなたの正解数は' + correctNum_ox + '問です!');
}
// 次の問題表示
count_ox++;
var question_ox = document.getElementById('question_ox');
question_ox.innerHTML = (count_ox + 1) + '問目:' + ar_ox[count_ox][0]+ '〇か×か?';
if(ar_ox[count_ox-1][1]==1){
s = '不正解!' + ar_ox[count_ox-1][0] + 'は不正解.' +'<br><br>'+ '正解は'+ans_ox[count_ox-1][0]+'とは'+ ans_ox[count_ox-1][1];
}
else if(ar_ox[count_ox-1][1]==2){
s ='正解!' + ar_ox[count_ox-1][0] + 'は正解';
}
document.getElementById("text_ans").innerHTML = s;
}
var quizzes = data4;
var quiz2;
init();
function init(){
var ra = Math.floor(Math.random() * quizzes.length);
quiz2 = quizzes[ra];
//問題用のフォームに表示する
document.getElementById("questionana").innerHTML = quiz2[1];
}
function doAnswer(){
//回答用のフォームに入力した値を取得
var answerForm = document.querySelector("#answerana");
var answer = answerForm.value;
//回答用フォームで入力した内容を削除する
answerForm.value = "";
//入力した内容が正しいか調べる
if (answer == quiz2[0]) {
//入力した内容が正解の時
right();
} else {
//入力した内容が不正解の時
wrong();
}
}
//正解の時に実行する関数
function right(){
alert("正解です");
init();
}
//不正解の時に実行する関数
function wrong(){
alert("不正解です");
}
|
1131ad0dfd7147ff1ffcd8d291b441cd960840a7
|
[
"Text",
"JavaScript",
"Python"
] | 16 |
Text
|
tomotaka68/my-auto
|
3f331c33f6bcaba6ae14ea6e1b788bc317fde2ed
|
1102cdec84aa8fc2b9b8c2a5fe3fd2eb259f05b7
|
refs/heads/master
|
<file_sep>const { app, BrowserWindow } = require('electron');
const fs = require('fs');
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) { // eslint-disable-line global-require
app.quit();
}
// Logo
const nativeImage = require('electron').nativeImage;
var image = nativeImage.createFromPath(__dirname + '/images/logo.png');
// where public folder on the root dir
image.setTemplateImage(true);
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
const createWindow = () => {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
height: 600,
frame: false,
icon: image,
webPreferences: {
nodeIntegration: true
}
});
mainWindow.webContents.on('did-finish-load', function() {
// custom titlebar script
mainWindow.webContents.executeJavaScript(`
const titlebar = require("custom-electron-titlebar");
new titlebar.Titlebar({
backgroundColor: titlebar.Color.fromHex('#2b2e3b'),
shadow: true,
icon: false,
menu: null
});
`)
//Inject our css to fix text and sizing
fs.readFile(__dirname+ '/index.css', "utf-8", function(error, data) {
if(!error){
var formatedData = data.replace(/\s{2,10}/g, ' ').trim()
mainWindow.webContents.insertCSS(formatedData)
}
})
})
// and load the index.html of the app.
//mainWindow.loadURL(`file://${__dirname}/index.html`);
mainWindow.loadURL(`https://explorer.decentraland.org`);
// Emitted when the window is closed.
mainWindow.on('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
// Discord RPC
const client = require('discord-rich-presence')('618606658331082783');
timethen = Date.now()
setInterval(function(){
let currentURL = mainWindow.webContents.getURL();
currentURL = currentURL.replace('https://explorer.decentraland.org/?position=','');
currentCoords = currentURL.replace('%2C',',')
if (currentCoords.includes('https://explorer.decentraland.org') == true) {
client.updatePresence({
state: 'Currently Loading into Decentraland...',
details: 'In Decentraland',
startTimestamp: timethen,
largeImageKey: 'logo',
instance: true,
});
} else {
client.updatePresence({
state: 'Currently @ ' + currentCoords,
details: 'In Decentraland',
startTimestamp: timethen,
largeImageKey: 'logo',
instance: true,
});
}
}, 600);
};
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);
app.setAsDefaultProtocolClient("decentraclient");
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});
<file_sep># Decentraland Electron Client
[](https://greenkeeper.io/)
An electron client for the Decentraland Network
This is essentially the Decentraland website within an electron container with some CSS injected and discord RPC support
## Why did you do this?
I did this because decentraland doesn't work correctly on firefox at the time, and I didn't want to use chrome since it's annoying switching between browsers for things such as lastpass, adblock and other things. So instead I created an standalone client on electron which worked really well for me.
Feel free to fork and make changes and build on this.
It's MIT Licence anyway.
## Built on...
+ Webpack
+ Electron-Forge
+ discord-rich-presence
<file_sep>const titlebar = require("custom-electron-titlebar");
new titlebar.Titlebar({
backgroundColor: titlebar.Color.fromHex('#2b2e3b'),
shadow: true,
icon: false,
menu: null
});
|
7f7339349d5105ba685d31750d8a876a1c957804
|
[
"Markdown",
"JavaScript"
] | 3 |
Markdown
|
PineappleIOnic/Decentraland-Electron-Client
|
a85a898c181b30bf4dea6773484fc8777b083065
|
23e92fedb4a4c5ad35971a3d3594b5fa9f777aac
|
refs/heads/main
|
<repo_name>TJvanderWalt/Proj_ID3<file_sep>/README.md
# Proj_ID3
WebDev voorbeelde vanuit RealPython Part2
|
b1c72459688301b6e268dc31b4825260d632a7b9
|
[
"Markdown"
] | 1 |
Markdown
|
TJvanderWalt/Proj_ID3
|
bfe5f76244b2caabc6a5f709f9ad78a7512ed2b0
|
649ff13e4fe9a6fc38b642f2dcdbe4f085406c1c
|
refs/heads/master
|
<file_sep># ex003_Infra_docker - Nginx_Mysql
>>Atividade
Subir dois contêineres, nginx e mysql, mapeando a porta 80 do nginx para acesso pelo host e permitir que o contêiner do nginx tenha comunicação de rede no contêiner mysql.
Enviar sequência de comandos na linha de comando ou o Docker-compose com os arquivos necessários para que a solução funcione.
## Instalar:
> $ docker-compose up
<file_sep>version: "3.3"
services:
mysql_server:
image: mysql:8.0
command: --default-authentication-plugin=mysql_native_password
restart: always
ports:
- "3306:3306"
volumes:
- ./mysql/db-data:/var/lib/mysql
environment:
MYSQL_USER: docker
MYSQL_PASSWORD: <PASSWORD>
MYSQL_DATABASE: docker
MYSQL_ROOT_PASSWORD: <PASSWORD>
nginx:
image: nginx:1.19
ports:
- "80:80"
|
7da52c671cf083332dcbc43030be79a8bea07aca
|
[
"Markdown",
"YAML"
] | 2 |
Markdown
|
DaFerrestos/ex003_Infra_docker
|
a02ad1ae17abe704ac3d10f1dbf436be56b24a77
|
05b22ced480a996802ce9fdcdf1588f510f9341d
|
refs/heads/main
|
<file_sep>#include <stdlib.h>
#include <chrono>
#include <iostream>
#include <igl/readPLY.h>
#include <igl/knn.h>
#include <igl/octree.h>
#include <igl/opengl/glfw/Viewer.h>
#include <igl/get_seconds.h>
#include "gnuplot_i.h"
#include <math.h>
#include <random>
/*
* This .cpp file is for experimenting the behaviour of the ICP
* algorithm's convergence rate based on the extremity of the
* rotation of M1 points
*/
using namespace std;
Eigen::MatrixXd V1;
Eigen::MatrixXi F1;
int point_size = 10;
int displaying = 0;
int frame = 0;
vector<Eigen::MatrixXd> iterations;
vector<vector<Eigen::MatrixXd>> iterTransformations;
vector<double> sqrDiff;
vector<int>convergenceRate;
vector<int>degreesSeq;
//Function prototypes
void addMeanZeroNoise(Eigen::MatrixXd& outputM, Eigen::MatrixXd& inputM, double sd);
void makeRigidHomo(Eigen::MatrixXd& rigidTransform, Eigen::MatrixXd& R, Eigen::RowVector3d& t){
/*
*Assembles the Rigid transformation using homogenous coordinates
*/
Eigen::MatrixXd rigidHomo = Eigen::MatrixXd ::Zero(4, 4);
rigidHomo.block(0, 0, 3, 3) = R;
rigidHomo.block(0, 3, 3, 1) = t.transpose();
rigidHomo(3, 3) = 1;
rigidTransform = rigidHomo;
}
void makeHomo(Eigen::MatrixXd& homoPts, Eigen::MatrixXd& pts){
Eigen::MatrixXd homo = Eigen::MatrixXd::Zero(pts.rows()+1, pts.cols());
homo.block(0, 0, pts.rows(), pts.cols()) = pts;
homo.block(homo.rows()-1, 0, 1, homo.cols()) = Eigen::RowVectorXd::Ones(homo.cols());
homoPts = homo;
}
void makeCart(Eigen::MatrixXd& cartPts, Eigen::MatrixXd& homoPts){
Eigen::MatrixXd cart = Eigen::MatrixXd::Zero(homoPts.rows()-1, homoPts.cols());
cart = homoPts.block(0, 0, cart.rows(), cart.cols());
cartPts = cart;
}
bool key_down(igl::opengl::glfw::Viewer& viewer, unsigned char key, int modifier){
if(key == '1'){
point_size++;
viewer.data().point_size = point_size;
}else if(key == '2'){
if(point_size > 0){
point_size--;
viewer.data().point_size = point_size;
}
}else if(key == '3'){
if(displaying != 0){
displaying--;
cout << "displaying iteration: " << displaying << endl;
viewer.data().clear();
viewer.data().add_points(V1, Eigen::RowVector3d(1, 0, 0.5));
viewer.data().add_points(iterations[displaying], Eigen::RowVector3d(0.4, 0.5, 0.1));
for(int p = 0; p < 20; p++){
viewer.data().add_points(Eigen::RowVector3d(0,0,p), Eigen::RowVector3d(0, 1, 0));
viewer.data().add_points(Eigen::RowVector3d(0,p,0), Eigen::RowVector3d(0, 0, 1));
viewer.data().add_points(Eigen::RowVector3d(p,0,0), Eigen::RowVector3d(1, 0, 0));
}
}
}else if(key == '4') {
if (displaying != (iterations.size() - 1)) {
displaying++;
cout << "displaying iteration: " << displaying << endl;
viewer.data().clear();
viewer.data().add_points(V1, Eigen::RowVector3d(1, 0, 0.5));
viewer.data().add_points(iterations[displaying], Eigen::RowVector3d(0.4, 0.5, 0.1));
for (int p = 0; p < 20; p++) {
viewer.data().add_points(Eigen::RowVector3d(0, 0, p), Eigen::RowVector3d(0, 1, 0));
viewer.data().add_points(Eigen::RowVector3d(0, p, 0), Eigen::RowVector3d(0, 0, 1));
viewer.data().add_points(Eigen::RowVector3d(p, 0, 0), Eigen::RowVector3d(1, 0, 0));
}
}
}
return false;
}
void getSamples(Eigen::MatrixXd& ptSamples, Eigen::MatrixXd& points, int numberOfSamples){
/*
* Here we will return a random set of samples and output them into matrix passed
* through the ptSamples matrix reference
*/
if(ptSamples.rows() != numberOfSamples){
cout << "Number of samples does not match output Matrix rows" << endl;
exit(0);
}
if(numberOfSamples == points.rows()){
//If the number of samples required is the same number as all the points
//Then we will just copy the points matrix into ptSamples
ptSamples << points;
return;
}
//TODO::Implement a random sampler and return the sample in ptSamples
Eigen::VectorXi sampledIndices(numberOfSamples);
for(int sample = 0; sample < numberOfSamples; sample++){
int index;
int unique = 0;
while(!unique){
index = rand() % points.rows();
unique = 1;
int sampledIndex = 0;
while(sampledIndex <= sample){
if(sampledIndices(sampledIndex) == index){
unique = 0;
break;
}
sampledIndex++;
}
}
ptSamples.row(sample) = points.row(index);
}
}
void computeRt(Eigen::MatrixXd& R, Eigen::RowVector3d& t, Eigen::MatrixXd& sampledPts, Eigen::MatrixXd& sampledPtsNN){
//Alignment phase
/*
* 1. Compute the barycenters for each point sets. There are 2 point sets I have:
* The sampled points P and the nn of the sampled points Q
* 2. Compute the new pointsets P_hat and Q_hat
* 3. Compute matrix A
* 4. Compute SVD of matrix A = ULV'
* 5. Compute R = VU'
* 6. Compute t = p_barycenter - R*q_barycenter
*/
//Computing barycenters for samples and its nn
Eigen::RowVector3d samplesBC = sampledPts.colwise().sum()/sampledPts.rows();
Eigen::RowVector3d samplesNNBC = sampledPtsNN.colwise().sum()/sampledPtsNN.rows();
//Compute the recentered points
Eigen::MatrixXd hatSamples = sampledPts.rowwise() - samplesBC;
Eigen::MatrixXd hatSamplesNN = sampledPtsNN.rowwise() - samplesNNBC;
/*
Eigen::MatrixXd hatSamples = Eigen::MatrixXd::Zero(sampledPts.rows(), sampledPts.cols());
Eigen::MatrixXd hatSamplesNN = Eigen::MatrixXd::Zero(sampledPtsNN.rows(), sampledPtsNN.cols());
for(int rowId = 0; rowId < sampledPts.rows(); rowId++){
hatSamples.row(rowId) = sampledPts.row(rowId) - samplesBC;
hatSamplesNN.row(rowId) = sampledPtsNN.row(rowId) - samplesNNBC;
}
*/
//Assemble matrix A
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(3, 3);
for(int rowId = 0; rowId < sampledPts.rows(); rowId++){
A = A + (hatSamples.row(rowId).transpose() * hatSamplesNN.row(rowId));
}
//Compute the SVD of A then assemble R and t
Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);
R = svd.matrixV() * svd.matrixU().transpose();
t = samplesNNBC - ((R*samplesBC.transpose()).transpose());
}
double computeAbsDiff(Eigen::MatrixXd& samples, Eigen::MatrixXd& samplesNN){
double sqrDiff = (samples - samplesNN).cwiseAbs().sum();
return sqrDiff;
}
void wait_for_key ()
{
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__TOS_WIN__) // every keypress registered, also arrow keys
cout << endl << "Press any key to continue..." << endl;
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
_getch();
#elif defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
cout << endl << "Press ENTER to continue..." << endl;
std::cin.clear();
std::cin.ignore(std::cin.rdbuf()->in_avail());
std::cin.get();
#endif
return;
}
void computeRotationZ(Eigen::MatrixXd& rotationM, double degrees){
double radians = (degrees / 180) * M_PI;
Eigen::MatrixXd rotationZ = Eigen::MatrixXd::Zero(3, 3);
rotationZ << cos(radians), -sin(radians), 0,
sin(radians), cos(radians), 0,
0, 0, 1;
cout << rotationZ << endl;
rotationM = rotationZ;
}
void computeRotationX(Eigen::MatrixXd& rotationM, double degrees){
double radians = (degrees / 180) * M_PI;
Eigen::MatrixXd rotationX = Eigen::MatrixXd::Zero(3, 3);
rotationX << 1, 0, 0,
0, cos(radians), -sin(radians),
0, sin(radians), cos(radians);
cout << rotationX << endl;
rotationM = rotationX;
}
void computeRotationY(Eigen::MatrixXd& rotationM, double degrees){
double radians = (degrees / 180) * M_PI;
Eigen::MatrixXd rotationY = Eigen::MatrixXd::Zero(3, 3);
rotationY << cos(radians), 0, sin(radians),
0, 1, 0,
-sin(radians), 0, cos(radians);
cout << rotationY << endl;
rotationM = rotationY;
}
void addZeroMeanNoise(Eigen::MatrixXd& outputM, Eigen::MatrixXd& inputM, double sd){
std::default_random_engine generator;
std::normal_distribution<double> distribution(0, sd);
Eigen::MatrixXd rndMatrix = Eigen::MatrixXd::Ones(inputM.rows(), inputM.cols());
for(int rowId = 0; rowId < inputM.rows(); rowId++){
rndMatrix.row(rowId) = rndMatrix.row(rowId) * (distribution(generator));
}
rndMatrix = rndMatrix + inputM;
outputM = rndMatrix;
}
void computeBoundaryBox(Eigen::MatrixXd& boundaryPoints, Eigen::MatrixXd& mesh){
//Finds the boundary box coordinates of a mesh
Eigen::MatrixXd pts = Eigen::MatrixXd::Zero(8, 3);
//Min and Max of X-axis
double minX = mesh.col(0).minCoeff();
double maxX = mesh.col(0).maxCoeff();
//Min and Max of Y-axis
double minY = mesh.col(1).minCoeff();
double maxY = mesh.col(1).maxCoeff();
//Min and Max of Z-axis
double minZ = mesh.col(2).minCoeff();
double maxZ = mesh.col(2).maxCoeff();
pts.row(0) = Eigen::RowVector3d(minX, minY, minZ);
pts.row(1) = Eigen::RowVector3d(minX, maxY, minZ);
pts.row(2) = Eigen::RowVector3d(maxX, maxY, minZ);
pts.row(3) = Eigen::RowVector3d(maxX, minY, minZ);
pts.row(4) = Eigen::RowVector3d(minX, minY, maxZ);
pts.row(5) = Eigen::RowVector3d(minX, maxY, maxZ);
pts.row(6) = Eigen::RowVector3d(maxX, maxY, maxZ);
pts.row(7) = Eigen::RowVector3d(maxX, minY, maxZ);
boundaryPoints = pts;
}
void computeBoundaryEdges(Eigen::MatrixXd& edgePts1, Eigen::MatrixXd& edgePt2, Eigen::MatrixXd& boundaryPts){
Eigen::MatrixXd pts = Eigen::MatrixXd::Zero(12, 3);
Eigen::MatrixXd matchingPts = Eigen::MatrixXd::Zero(12, 3);
pts.block(0, 0, 8, 3) = boundaryPts;
pts.block(8, 0, 4, 3) = boundaryPts.block(0, 0, 4, 3);
matchingPts.row(0) = boundaryPts.row(1);
matchingPts.row(1) = boundaryPts.row(2);
matchingPts.row(2) = boundaryPts.row(3);
matchingPts.row(3) = boundaryPts.row(0);
matchingPts.row(4) = boundaryPts.row(5);
matchingPts.row(5) = boundaryPts.row(6);
matchingPts.row(6) = boundaryPts.row(7);
matchingPts.row(7) = boundaryPts.row(4);
matchingPts.row(8) = boundaryPts.row(4);
matchingPts.row(9) = boundaryPts.row(5);
matchingPts.row(10) = boundaryPts.row(6);
matchingPts.row(11) = boundaryPts.row(7);
edgePts1 = pts;
edgePt2 = matchingPts;
}
int main(int argc, char* args[]){
Eigen::MatrixXd V2;
Eigen::MatrixXi F2;
Eigen::MatrixXd V3;
Eigen::MatrixXi F3;
Eigen::MatrixXd V4;
Eigen::MatrixXi F4;
Eigen::MatrixXd V5;
Eigen::MatrixXi F5;
Eigen::MatrixXd V6;
Eigen::MatrixXi F6;
//Load in the non transformed bunny
igl::readPLY("../bunny_v2/bun000_v2.ply", V1, F1);
igl::readPLY("../bunny_v2/bun045_v2.ply", V2, F2);
igl::readPLY("../bunny_v2/bun090_v2.ply", V3, F3);
igl::readPLY("../bunny_v2/bun180_v2.ply", V4, F4);
igl::readPLY("../bunny_v2/bun270_v2.ply", V5, F5);
igl::readPLY("../bunny_v2/bun315_v2.ply", V6, F6);
//Rotate extreme bunnies closer to center bunny
//Create viewer for displaying the file
igl::opengl::glfw::Viewer viewer;
//Testing rotation method
/*
* Displaying axis and centering bunny
Eigen::RowVector3d v1Centroid = V1.colwise().sum() / V1.rows();
Eigen::MatrixXd centeredV1 = V1.rowwise() - v1Centroid;
V1 = centeredV1;
Eigen::MatrixXd rotation;
Eigen::MatrixXd currV2 = centeredV1;
//Z makes it spin palm facing towards me
for(int degrees = -90; degrees < 91; degrees++) {
computeRotationZ(rotation, degrees);
currV2 = (rotation * currV2.transpose()).transpose();
iterations.push_back(currV2);
}
//X makes its spin fingers facing towards me
currV2 = V1;
for(int degrees = -90; degrees < 91; degrees++) {
computeRotationX(rotation, degrees);
currV2 = (rotation * currV2.transpose()).transpose();
iterations.push_back(currV2);
}
//Y makes its spin thumb towards me
currV2 = V1;
for(int degrees = -90; degrees < 91; degrees++) {
computeRotationY(rotation, degrees);
currV2 = (rotation * currV2.transpose()).transpose();
iterations.push_back(currV2);
}
for(int p = 0; p < 20; p++){
viewer.data().add_points(Eigen::RowVector3d(0,0,p), Eigen::RowVector3d(0, 1, 0));
viewer.data().add_points(Eigen::RowVector3d(0,p,0), Eigen::RowVector3d(0, 0, 1));
viewer.data().add_points(Eigen::RowVector3d(p,0,0), Eigen::RowVector3d(1, 0, 0));
}
viewer.data().add_points(Eigen::RowVector3d(0, 0, 0), Eigen::RowVector3d(1, 0, 0));
viewer.data().point_size = point_size;
viewer.data().add_points(centeredV1, Eigen::RowVector3d(1, 0, 0.5)); //pink
viewer.data().add_points(iterations[0], Eigen::RowVector3d(0.4, 0.5, 0.1)); //greenish
*/
//Testing adding noise method
/*
* The following is for testing the noise function
double sd = 0.1;
if(argc > 1){
sd = std::stod(args[1]);
}
//Adding noise to V1 and storing the noised points into V2
addZeroMeanNoise(V2, V1, sd);
*/
//Testing boundary boxes
//Find the boundary box of a mesh
Eigen::MatrixXd mBoundaryV1;
Eigen::MatrixXd mBoundaryV2;
Eigen::MatrixXd mBoundaryV3;
Eigen::MatrixXd mBoundaryV4;
Eigen::MatrixXd mBoundaryV5;
Eigen::MatrixXd mBoundaryV6;
computeBoundaryBox(mBoundaryV1, V1);
computeBoundaryBox(mBoundaryV2, V2);
computeBoundaryBox(mBoundaryV3, V3);
computeBoundaryBox(mBoundaryV4, V4);
computeBoundaryBox(mBoundaryV5, V5);
computeBoundaryBox(mBoundaryV6, V6);
Eigen::MatrixXd edge1_V1;
Eigen::MatrixXd edge2_V1;
Eigen::MatrixXd edge1_V2;
Eigen::MatrixXd edge2_V2;
Eigen::MatrixXd edge1_V3;
Eigen::MatrixXd edge2_V3;
Eigen::MatrixXd edge1_V4;
Eigen::MatrixXd edge2_V4;
computeBoundaryEdges(edge1_V1, edge2_V1, mBoundaryV1);
computeBoundaryEdges(edge1_V2, edge2_V2, mBoundaryV2);
computeBoundaryEdges(edge1_V3, edge2_V3, mBoundaryV3);
computeBoundaryEdges(edge1_V4, edge2_V4, mBoundaryV4);
//plot the boundary box
viewer.data().add_points(mBoundaryV1, Eigen::RowVector3d(1,0,0));
viewer.data().add_points(V1, Eigen::RowVector3d(0, 0.8, 0.2));
viewer.data().add_edges(edge1_V1, edge2_V1, Eigen::RowVector3d(1, 0, 0));
viewer.data().add_points(mBoundaryV2, Eigen::RowVector3d(0,0,1));
viewer.data().add_points(V2, Eigen::RowVector3d(1, 0.8, 0.2));
viewer.data().add_edges(edge1_V2, edge2_V2, Eigen::RowVector3d(1, 0, 0));
viewer.data().add_points(mBoundaryV3, Eigen::RowVector3d(0,1,1));
viewer.data().add_points(V3, Eigen::RowVector3d(1, 0.5, 1));
viewer.data().add_edges(edge1_V3, edge2_V3, Eigen::RowVector3d(0, 1, 1));
viewer.data().add_points(mBoundaryV4, Eigen::RowVector3d(0, 1, 1));
viewer.data().add_points(V4, Eigen::RowVector3d(0.3, 0.3, 1));
viewer.data().add_edges(edge1_V4, edge2_V4, Eigen::RowVector3d(0, 1, 1));
viewer.callback_key_down = &key_down;
viewer.launch();
return 0;
}
<file_sep>#include <stdlib.h>
#include <chrono>
#include <iostream>
#include <igl/readPLY.h>
#include <igl/knn.h>
#include <igl/octree.h>
#include <igl/opengl/glfw/Viewer.h>
#include <igl/get_seconds.h>
#include "gnuplot_i.h"
using namespace std;
Eigen::MatrixXd V1;
Eigen::MatrixXi F1;
int point_size = 10;
int displaying = 0;
vector<Eigen::MatrixXd> iterations;
vector<double> sqrDiff;
bool key_down(igl::opengl::glfw::Viewer& viewer, unsigned char key, int modifier){
if(key == '1'){
point_size++;
viewer.data().point_size = point_size;
}else if(key == '2'){
if(point_size > 0){
point_size--;
viewer.data().point_size = point_size;
}
}else if(key == '3'){
if(displaying != 0){
displaying--;
cout << "displaying iteration: " << displaying << endl;
viewer.data().clear();
viewer.data().add_points(V1, Eigen::RowVector3d(1, 0, 0.5));
viewer.data().add_points(iterations[displaying], Eigen::RowVector3d(0.4, 0.5, 0.1));
}
}else if(key == '4'){
if(displaying != (iterations.size()-1)){
displaying++;
cout << "displaying iteration: " << displaying << endl;
viewer.data().clear();
viewer.data().add_points(V1, Eigen::RowVector3d(1, 0, 0.5));
viewer.data().add_points(iterations[displaying], Eigen::RowVector3d(0.4, 0.5, 0.1));
}
}
return false;
}
void getSamples(Eigen::MatrixXd& ptSamples, Eigen::MatrixXd& points, int numberOfSamples){
/*
* Here we will return a random set of samples and output them into matrix passed
* through the ptSamples matrix reference
*/
if(ptSamples.rows() != numberOfSamples){
cout << "Number of samples does not match output Matrix rows" << endl;
exit(0);
}
if(numberOfSamples == points.rows()){
//If the number of samples required is the same number as all the points
//Then we will just copy the points matrix into ptSamples
ptSamples << points;
return;
}
//TODO::Implement a random sampler and return the sample in ptSamples
Eigen::VectorXi sampledIndices(numberOfSamples);
for(int sample = 0; sample < numberOfSamples; sample++){
int index;
int unique = 0;
while(!unique){
index = rand() % points.rows();
unique = 1;
int sampledIndex = 0;
while(sampledIndex <= sample){
if(sampledIndices(sampledIndex) == index){
unique = 0;
break;
}
sampledIndex++;
}
}
ptSamples.row(sample) = points.row(index);
}
}
void computeRt(Eigen::MatrixXd& R, Eigen::RowVector3d& t, Eigen::MatrixXd& sampledPts, Eigen::MatrixXd& sampledPtsNN){
//Alignment phase
/*
* 1. Compute the barycenters for each point sets. There are 2 point sets I have:
* The sampled points P and the nn of the sampled points Q
* 2. Compute the new pointsets P_hat and Q_hat
* 3. Compute matrix A
* 4. Compute SVD of matrix A = ULV'
* 5. Compute R = VU'
* 6. Compute t = p_barycenter - R*q_barycenter
*/
//Computing barycenters for samples and its nn
Eigen::RowVector3d samplesBC = sampledPts.colwise().sum()/sampledPts.rows();
Eigen::RowVector3d samplesNNBC = sampledPtsNN.colwise().sum()/sampledPtsNN.rows();
//Compute the recentered points
Eigen::MatrixXd hatSamples = sampledPts.rowwise() - samplesBC;
Eigen::MatrixXd hatSamplesNN = sampledPtsNN.rowwise() - samplesNNBC;
/*
Eigen::MatrixXd hatSamples = Eigen::MatrixXd::Zero(sampledPts.rows(), sampledPts.cols());
Eigen::MatrixXd hatSamplesNN = Eigen::MatrixXd::Zero(sampledPtsNN.rows(), sampledPtsNN.cols());
for(int rowId = 0; rowId < sampledPts.rows(); rowId++){
hatSamples.row(rowId) = sampledPts.row(rowId) - samplesBC;
hatSamplesNN.row(rowId) = sampledPtsNN.row(rowId) - samplesNNBC;
}
*/
//Assemble matrix A
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(3, 3);
for(int rowId = 0; rowId < sampledPts.rows(); rowId++){
A = A + (hatSamples.row(rowId).transpose() * hatSamplesNN.row(rowId));
}
//Compute the SVD of A then assemble R and t
Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);
R = svd.matrixV() * svd.matrixU().transpose();
t = samplesNNBC - ((R*samplesBC.transpose()).transpose());
}
double computeSqrDiff(Eigen::MatrixXd& samples, Eigen::MatrixXd& samplesNN){
double sqrDiff = (samples - samplesNN).cwiseAbs2().sum();
return sqrDiff;
}
void wait_for_key ()
{
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__TOS_WIN__) // every keypress registered, also arrow keys
cout << endl << "Press any key to continue..." << endl;
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
_getch();
#elif defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
cout << endl << "Press ENTER to continue..." << endl;
std::cin.clear();
std::cin.ignore(std::cin.rdbuf()->in_avail());
std::cin.get();
#endif
return;
}
int main(int argc, char* args[]){
//parameters
double acceptanceThreshold = 3;
int iter = 200;
int numOfSamples = 5000;
if(argc > 1)
{
iter = stoi(args[1]);
acceptanceThreshold = stoi(args[2]);
numOfSamples = stoi(args[3]);
}
//Load in the files
Eigen::MatrixXd V2;
Eigen::MatrixXi F2;
igl::readPLY("../bunny_v2/bun000_v2.ply", V1, F1);
if(argc > 1){
igl::readPLY(args[4], V2, F2);
}else{
igl::readPLY("../bunny_v2/bun045_v2.ply", V2, F2);
}
//Create viewer for displaying the file
igl::opengl::glfw::Viewer viewer;
//Construct our octree out of our Q Points (that we are trying to map to)
//Initialize Octree properties
std::vector<std::vector<int>> O_PI; //Points inside each Octree cell
Eigen::MatrixXi O_CH; //Children of each node in the Octree
Eigen::MatrixXd O_CN; //Mid point of each node in the Octree
Eigen::VectorXd O_W; //Width of each node in the Octree
//Compute Octree
igl::octree(V1, O_PI, O_CH, O_CN, O_W);
Eigen::MatrixXd currV2 = V2;
iterations.push_back(V2);
for(int i = 0; i < iter; i++) {
//Take samples from V2 (which change every iteration)
Eigen::MatrixXd samples(numOfSamples, 3);
getSamples(samples, currV2, numOfSamples);
//We have our set of points P
//Next we need to find the closest point for each p in Q
//Set up results matrix for kNN
Eigen::MatrixXi kNNResults; //This will hold the kNN for each point we give to the algorithm
int numNN = 1;
double tic = igl::get_seconds();
igl::knn(samples, V1, numNN, O_PI, O_CH, O_CN, O_W, kNNResults);
printf("%0.4f secs\n",igl::get_seconds()-tic);
//Collect the V1 points found
Eigen::MatrixXd samplesNN(samples.rows(), samples.cols());
for (int sample = 0; sample < numOfSamples; sample++) {
int rowIndex = kNNResults.row(sample)(0);
samplesNN.row(sample) = V1.row(rowIndex);
}
cout << "passed collecting points" << endl;
//TODO::Create a outlier rejection phase
Eigen::MatrixXd sampleDists = (samples - samplesNN).cwiseAbs2().rowwise().sum();
std::vector<int> keepers;
double averageDist = sampleDists.sum() / numOfSamples;
for(int sample=0; sample < numOfSamples; sample++){
if(sampleDists(sample) < (averageDist * acceptanceThreshold)){
keepers.push_back(sample);
}
}
Eigen::MatrixXd keptSamples = Eigen::MatrixXd::Zero(keepers.size(), 3);
Eigen::MatrixXd keptSamplesNN = Eigen::MatrixXd::Zero(keepers.size(), 3);
for(int keeperIndex = 0; keeperIndex < keepers.size(); keeperIndex++){
int index = keepers[keeperIndex];
keptSamples.row(keeperIndex) = samples.row(index);
keptSamplesNN.row(keeperIndex) = samplesNN.row(index);
}
//Alignment phase
Eigen::MatrixXd R;
Eigen::RowVector3d t;
computeRt(R, t, keptSamples, keptSamplesNN);
currV2 = (R*currV2.transpose()).transpose().rowwise() + t;
iterations.push_back(currV2);
cout << "Iteration number: " << i << endl;
double epsilon = computeSqrDiff(currV2, V1);
sqrDiff.push_back(epsilon);
if(i != 0 && abs(sqrDiff[i-1] - epsilon) < 0.001){
Gnuplot g1("lines");
//g1.set_title("Convergence");
g1.plot_x(sqrDiff, "Convergence");
g1.showonscreen();
wait_for_key();
break;
}
}
viewer.data().point_size = point_size;
viewer.data().add_points(V1, Eigen::RowVector3d(1, 0, 0.5)); //pink
viewer.data().add_points(currV2, Eigen::RowVector3d(0.4, 0.5, 0.1)); //greenish
viewer.callback_key_down = &key_down;
viewer.launch();
return 0;
}
<file_sep>#include <stdlib.h>
#include <chrono>
#include <iostream>
#include <igl/readPLY.h>
#include <igl/knn.h>
#include <igl/octree.h>
#include <igl/opengl/glfw/Viewer.h>
#include <igl/get_seconds.h>
#include "gnuplot_i.h"
#include <math.h>
#include <random>
/*
* This .cpp file is for experimenting the behaviour of the ICP
* algorithm's convergence rate based on the extremity of the
* rotation of M1 points
*/
using namespace std;
Eigen::MatrixXd V1;
Eigen::MatrixXi F1;
int point_size = 10;
int displaying = 0;
int frame = 0;
vector<Eigen::MatrixXd> iterations;
vector<vector<Eigen::MatrixXd>> iterTransformations;
vector<double> sqrDiff;
vector<int>convergenceRate;
vector<int>degreesSeq;
void makeRigidHomo(Eigen::MatrixXd& rigidTransform, Eigen::MatrixXd& R, Eigen::RowVector3d& t){
/*
*Assembles the Rigid transformation using homogenous coordinates
*/
Eigen::MatrixXd rigidHomo = Eigen::MatrixXd ::Zero(4, 4);
rigidHomo.block(0, 0, 3, 3) = R;
rigidHomo.block(0, 3, 3, 1) = t.transpose();
rigidHomo(3, 3) = 1;
rigidTransform = rigidHomo;
}
void makeHomo(Eigen::MatrixXd& homoPts, Eigen::MatrixXd& pts){
Eigen::MatrixXd homo = Eigen::MatrixXd::Zero(pts.rows()+1, pts.cols());
homo.block(0, 0, pts.rows(), pts.cols()) = pts;
homo.block(homo.rows()-1, 0, 1, homo.cols()) = Eigen::RowVectorXd::Ones(homo.cols());
homoPts = homo;
}
void makeCart(Eigen::MatrixXd& cartPts, Eigen::MatrixXd& homoPts){
Eigen::MatrixXd cart = Eigen::MatrixXd::Zero(homoPts.rows()-1, homoPts.cols());
cart = homoPts.block(0, 0, cart.rows(), cart.cols());
cartPts = cart;
}
bool key_down(igl::opengl::glfw::Viewer& viewer, unsigned char key, int modifier){
if(key == '1'){
point_size++;
viewer.data().point_size = point_size;
}else if(key == '2'){
if(point_size > 0){
point_size--;
viewer.data().point_size = point_size;
}
}else if(key == '3'){
if(displaying != 0){
displaying--;
cout << "displaying iteration: " << displaying << endl;
viewer.data().clear();
viewer.data().add_points(V1, Eigen::RowVector3d(1, 0, 0.5));
viewer.data().add_points(iterations[displaying], Eigen::RowVector3d(0.4, 0.5, 0.1));
for(int p = 0; p < 20; p++){
viewer.data().add_points(Eigen::RowVector3d(0,0,p), Eigen::RowVector3d(0, 1, 0));
viewer.data().add_points(Eigen::RowVector3d(0,p,0), Eigen::RowVector3d(0, 0, 1));
viewer.data().add_points(Eigen::RowVector3d(p,0,0), Eigen::RowVector3d(1, 0, 0));
}
}
}else if(key == '4'){
if(displaying != (iterations.size()-1)){
displaying++;
cout << "displaying iteration: " << displaying << endl;
viewer.data().clear();
viewer.data().add_points(V1, Eigen::RowVector3d(1, 0, 0.5));
viewer.data().add_points(iterations[displaying], Eigen::RowVector3d(0.4, 0.5, 0.1));
for(int p = 0; p < 20; p++){
viewer.data().add_points(Eigen::RowVector3d(0,0,p), Eigen::RowVector3d(0, 1, 0));
viewer.data().add_points(Eigen::RowVector3d(0,p,0), Eigen::RowVector3d(0, 0, 1));
viewer.data().add_points(Eigen::RowVector3d(p,0,0), Eigen::RowVector3d(1, 0, 0));
}
}
}
return false;
}
void getSamples(Eigen::MatrixXd& ptSamples, Eigen::MatrixXd& points, int numberOfSamples){
/*
* Here we will return a random set of samples and output them into matrix passed
* through the ptSamples matrix reference
*/
if(ptSamples.rows() != numberOfSamples){
cout << "Number of samples does not match output Matrix rows" << endl;
exit(0);
}
if(numberOfSamples == points.rows()){
//If the number of samples required is the same number as all the points
//Then we will just copy the points matrix into ptSamples
ptSamples = points;
return;
}
//TODO::Implement a random sampler and return the sample in ptSamples
Eigen::VectorXi sampledIndices(numberOfSamples);
for(int sample = 0; sample < numberOfSamples; sample++){
int index;
int unique = 0;
while(!unique){
index = rand() % points.rows();
unique = 1;
int sampledIndex = 0;
while(sampledIndex <= sample){
if(sampledIndices(sampledIndex) == index){
unique = 0;
break;
}
sampledIndex++;
}
}
ptSamples.row(sample) = points.row(index);
}
}
void computeRt(Eigen::MatrixXd& R, Eigen::RowVector3d& t, Eigen::MatrixXd& sampledPts, Eigen::MatrixXd& sampledPtsNN){
//Alignment phase
/*
* 1. Compute the barycenters for each point sets. There are 2 point sets I have:
* The sampled points P and the nn of the sampled points Q
* 2. Compute the new pointsets P_hat and Q_hat
* 3. Compute matrix A
* 4. Compute SVD of matrix A = ULV'
* 5. Compute R = VU'
* 6. Compute t = p_barycenter - R*q_barycenter
*/
//Computing barycenters for samples and its nn
Eigen::RowVector3d samplesBC = sampledPts.colwise().sum()/sampledPts.rows();
Eigen::RowVector3d samplesNNBC = sampledPtsNN.colwise().sum()/sampledPtsNN.rows();
//Compute the recentered points
Eigen::MatrixXd hatSamples = sampledPts.rowwise() - samplesBC;
Eigen::MatrixXd hatSamplesNN = sampledPtsNN.rowwise() - samplesNNBC;
/*
Eigen::MatrixXd hatSamples = Eigen::MatrixXd::Zero(sampledPts.rows(), sampledPts.cols());
Eigen::MatrixXd hatSamplesNN = Eigen::MatrixXd::Zero(sampledPtsNN.rows(), sampledPtsNN.cols());
for(int rowId = 0; rowId < sampledPts.rows(); rowId++){
hatSamples.row(rowId) = sampledPts.row(rowId) - samplesBC;
hatSamplesNN.row(rowId) = sampledPtsNN.row(rowId) - samplesNNBC;
}
*/
//Assemble matrix A
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(3, 3);
for(int rowId = 0; rowId < sampledPts.rows(); rowId++){
A = A + (hatSamples.row(rowId).transpose() * hatSamplesNN.row(rowId));
}
//Compute the SVD of A then assemble R and t
Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);
R = svd.matrixV() * svd.matrixU().transpose();
t = samplesNNBC - ((R*samplesBC.transpose()).transpose());
}
double computeSqrDiff(Eigen::MatrixXd& samples, Eigen::MatrixXd& samplesNN){
double sqrDiff = (samples - samplesNN).cwiseAbs2().sum();
return sqrDiff;
}
void wait_for_key ()
{
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__TOS_WIN__) // every keypress registered, also arrow keys
cout << endl << "Press any key to continue..." << endl;
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
_getch();
#elif defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
cout << endl << "Press ENTER to continue..." << endl;
std::cin.clear();
std::cin.ignore(std::cin.rdbuf()->in_avail());
std::cin.get();
#endif
return;
}
void computeRotationZ(Eigen::MatrixXd& rotationM, double degrees){
double radians = (degrees / 180) * M_PI;
Eigen::MatrixXd rotationZ = Eigen::MatrixXd::Zero(3, 3);
rotationZ << cos(radians), -sin(radians), 0,
sin(radians), cos(radians), 0,
0, 0, 1;
cout << rotationZ << endl;
rotationM = rotationZ;
}
void computeRotationX(Eigen::MatrixXd& rotationM, double degrees){
double radians = (degrees / 180) * M_PI;
Eigen::MatrixXd rotationX = Eigen::MatrixXd::Zero(3, 3);
rotationX << 1, 0, 0,
0, cos(radians), -sin(radians),
0, sin(radians), cos(radians);
cout << rotationX << endl;
rotationM = rotationX;
}
void computeRotationY(Eigen::MatrixXd& rotationM, double degrees){
double radians = (degrees / 180) * M_PI;
Eigen::MatrixXd rotationY = Eigen::MatrixXd::Zero(3, 3);
rotationY << cos(radians), 0, sin(radians),
0, 1, 0,
-sin(radians), 0, cos(radians);
cout << rotationY << endl;
rotationM = rotationY;
}
void addZeroMeanNoise(Eigen::MatrixXd& outputM, Eigen::MatrixXd& inputM, double sd){
if(sd == 0){
outputM = inputM;
return;
}
std::default_random_engine generator;
std::normal_distribution<double> distribution(0, sd);
Eigen::MatrixXd rndMatrix = Eigen::MatrixXd::Ones(inputM.rows(), inputM.cols());
for(int rowId = 0; rowId < inputM.rows(); rowId++){
rndMatrix.row(rowId) = rndMatrix.row(rowId) * (distribution(generator));
}
rndMatrix = rndMatrix + inputM;
outputM = rndMatrix;
}
/*
* This program is used for experimenting how sampling affects the
* accurary of the ICP convergence
*/
int main(int argc, char* args[]){
Eigen::MatrixXd V2_OG;
Eigen::MatrixXi F2;
//Load in the non transformed bunny
igl::readPLY("../bunny_v2/bun000_v2.ply", V1, F1);
igl::readPLY("../bunny_v2/bun045_v2.ply", V2_OG, F2);
//Parameters for running this added noise model
vector<double> RESNORM;
vector<int> samplesTaken;
vector<int> iterationsDone; //Vector holding the number of iterations per added noise model
int icpIter = 100; //Number of iterations ICP algorithm will run for
int numOfSamples = 500; //Number of samples used in the ICP algorithm
double acceptanceThreshold = 0.8; //Outlier elimination thresholding parameter
int maxSamples = 1500;
if(argc > 1){
icpIter = stoi(args[1]);
acceptanceThreshold = stod(args[2]);
maxSamples = stoi(args[3]);
}
//Construct our octree out of our Q Points (that we are trying to map to)
//Initialize Octree properties
std::vector<std::vector<int>> O_PI; //Points inside each Octree cell
Eigen::MatrixXi O_CH; //Children of each node in the Octree
Eigen::MatrixXd O_CN; //Mid point of each node in the Octree
Eigen::VectorXd O_W; //Width of each node in the Octree
//Compute Octree
igl::octree(V1, O_PI, O_CH, O_CN, O_W);
for(int s = 500; s <= maxSamples; s+=500){
numOfSamples = s;
Eigen::MatrixXd V2 = V2_OG;
for(int i = 0; i < icpIter; i++) {
//Take samples from V2 (which change every iteration)
Eigen::MatrixXd samples(numOfSamples, 3);
getSamples(samples, V2, numOfSamples);
//We have our set of points P
//Next we need to find the closest point for each p in Q
//Set up results matrix for kNN
Eigen::MatrixXi kNNResults; //This will hold the kNN for each point we give to the algorithm
//double tic = igl::get_seconds();
igl::knn(samples, V1, 1, O_PI, O_CH, O_CN, O_W, kNNResults);
//printf("%0.4f secs\n",igl::get_seconds()-tic);
//Collect the V1 points found
Eigen::MatrixXd samplesNN(samples.rows(), samples.cols());
for (int sample = 0; sample < numOfSamples; sample++) {
int rowIndex = kNNResults.row(sample)(0);
samplesNN.row(sample) = V1.row(rowIndex);
}
Eigen::MatrixXd sampleDists = (samples - samplesNN).cwiseAbs2().rowwise().sum();
std::vector<int> keepers;
double averageDist = sampleDists.sum() / numOfSamples;
for(int sample=0; sample < numOfSamples; sample++){
if(sampleDists(sample) < (averageDist * acceptanceThreshold)){
keepers.push_back(sample);
}
}
Eigen::MatrixXd keptSamples = Eigen::MatrixXd::Zero(keepers.size(), 3);
Eigen::MatrixXd keptSamplesNN = Eigen::MatrixXd::Zero(keepers.size(), 3);
for(int keeperIndex = 0; keeperIndex < keepers.size(); keeperIndex++){
int index = keepers[keeperIndex];
keptSamples.row(keeperIndex) = samples.row(index);
keptSamplesNN.row(keeperIndex) = samplesNN.row(index);
}
//Alignment phase
Eigen::MatrixXd R;
Eigen::RowVector3d t;
computeRt(R, t, keptSamples, keptSamplesNN);
V2 = (R*V2.transpose()).transpose().rowwise() + t;
if(i % 10 == 0) {
cout << "Iteration number: " << i << endl;
}
/*
double epsilon = computeSqrDiff(V2, V1);
sqrDiff.push_back(epsilon);
if(i != 0 && abs(sqrDiff[i-1] - epsilon) < 0.0001){
cout << "Converged at iteration num: " << i << endl;
iterations.push_back(V2);
iterationsDone.push_back(i);
break;
}
*/
if(i == (icpIter-1)){
double dSqrDiff = computeSqrDiff(V2, V1);
cout << "Sqr Difference: " << dSqrDiff << endl;
iterations.push_back(V2);
samplesTaken.push_back(s);
RESNORM.push_back(dSqrDiff);
iterationsDone.push_back(i);
}
}
}
Gnuplot g1("lines");
g1.set_xlabel("Samples Taken");
g1.set_ylabel("ERROR");
g1.plot_xy(samplesTaken,RESNORM, "ICP Accuracy");
g1.showonscreen();
/*
Gnuplot g2("lines");
g2.set_xlabel("Samples Taken");
g2.set_ylabel("SQR ERROR");
g2.plot_xy(samplesTaken, RESNORM, "ICP Accuracy");
g2.showonscreen();
*/
wait_for_key();
//Create viewer for displaying the file
igl::opengl::glfw::Viewer viewer;
viewer.data().point_size = point_size;
viewer.data().add_points(V1, Eigen::RowVector3d(1, 0, 0.5)); //pink
viewer.data().add_points(iterations[0], Eigen::RowVector3d(0.4, 0.5, 0.1)); //greenish
viewer.callback_key_down = &key_down;
viewer.launch();
return 0;
}
<file_sep>#include <stdlib.h>
#include <chrono>
#include <iostream>
#include <igl/readPLY.h>
#include <igl/knn.h>
#include <igl/octree.h>
#include <igl/opengl/glfw/Viewer.h>
#include <igl/get_seconds.h>
#include "gnuplot_i.h"
#include <math.h>
#include <random>
/*
* This .cpp file is for experimenting the behaviour of the ICP
* algorithm's convergence rate based on the extremity of the
* rotation of M1 points
*/
using namespace std;
int nNumBuns = 2;
int point_size = 2;
int displaying = 0;
std::vector<Eigen::MatrixXd> iterations;
std::vector<Eigen::MatrixXd> vBunPts;
std::vector<Eigen::MatrixXi> vBunFaces;
std::vector<Eigen::RowVector3d> vColours;
bool key_down(igl::opengl::glfw::Viewer& viewer, unsigned char key, int modifier){
if(key == '1'){
point_size++;
viewer.data().point_size = point_size;
}else if(key == '2'){
if(point_size > 0){
point_size--;
viewer.data().point_size = point_size;
}
}else if(key == '3'){
if(displaying != 0){
displaying-=nNumBuns;
cout << "displaying iteration: " << displaying << endl;
viewer.data().clear();
for(int nBunId = 0; nBunId < nNumBuns; nBunId++){
viewer.data().add_points(iterations[displaying+nBunId], vColours[nBunId]);
}
}
}else if(key == '4'){
if(displaying != (iterations.size()/nNumBuns)){
displaying+=nNumBuns;
cout << "displaying iteration: " << displaying << endl;
viewer.data().clear();
for(int nBunId = 0; nBunId < nNumBuns; nBunId++){
viewer.data().add_points(iterations[displaying+nBunId], vColours[nBunId]);
}
}
}
return false;
}
void getSamples(Eigen::MatrixXd& ptSamples, Eigen::MatrixXd& points, int numberOfSamples){
/*
* Here we will return a random set of samples and output them into matrix passed
* through the ptSamples matrix reference
*/
if(ptSamples.rows() != numberOfSamples){
cout << "Number of samples does not match output Matrix rows" << endl;
exit(0);
}
if(numberOfSamples == points.rows()){
//If the number of samples required is the same number as all the points
//Then we will just copy the points matrix into ptSamples
ptSamples = points;
return;
}
//TODO::Implement a random sampler and return the sample in ptSamples
Eigen::VectorXi sampledIndices(numberOfSamples);
for(int sample = 0; sample < numberOfSamples; sample++){
int index;
int unique = 0;
while(!unique){
index = rand() % points.rows();
unique = 1;
int sampledIndex = 0;
while(sampledIndex <= sample){
if(sampledIndices(sampledIndex) == index){
unique = 0;
break;
}
sampledIndex++;
}
}
ptSamples.row(sample) = points.row(index);
}
}
void computeRt(Eigen::MatrixXd& R, Eigen::RowVector3d& t, Eigen::MatrixXd& sampledPts, Eigen::MatrixXd& sampledPtsNN){
//Alignment phase
/*
* 1. Compute the barycenters for each point sets. There are 2 point sets I have:
* The sampled points P and the nn of the sampled points Q
* 2. Compute the new pointsets P_hat and Q_hat
* 3. Compute matrix A
* 4. Compute SVD of matrix A = ULV'
* 5. Compute R = VU'
* 6. Compute t = p_barycenter - R*q_barycenter
*/
//Computing barycenters for samples and its nn
Eigen::RowVector3d samplesBC = sampledPts.colwise().sum()/sampledPts.rows();
Eigen::RowVector3d samplesNNBC = sampledPtsNN.colwise().sum()/sampledPtsNN.rows();
//Compute the recentered points
Eigen::MatrixXd hatSamples = sampledPts.rowwise() - samplesBC;
Eigen::MatrixXd hatSamplesNN = sampledPtsNN.rowwise() - samplesNNBC;
/*
Eigen::MatrixXd hatSamples = Eigen::MatrixXd::Zero(sampledPts.rows(), sampledPts.cols());
Eigen::MatrixXd hatSamplesNN = Eigen::MatrixXd::Zero(sampledPtsNN.rows(), sampledPtsNN.cols());
for(int rowId = 0; rowId < sampledPts.rows(); rowId++){
hatSamples.row(rowId) = sampledPts.row(rowId) - samplesBC;
hatSamplesNN.row(rowId) = sampledPtsNN.row(rowId) - samplesNNBC;
}
*/
//Assemble matrix A
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(3, 3);
for(int rowId = 0; rowId < sampledPts.rows(); rowId++){
A = A + (hatSamples.row(rowId).transpose() * hatSamplesNN.row(rowId));
}
//Compute the SVD of A then assemble R and t
Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);
R = svd.matrixV() * svd.matrixU().transpose();
t = samplesNNBC - ((R*samplesBC.transpose()).transpose());
}
double computeSqrDiff(Eigen::MatrixXd& samples, Eigen::MatrixXd& samplesNN){
double sqrDiff = (samples - samplesNN).cwiseAbs2().sum();
return sqrDiff;
}
void wait_for_key ()
{
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__TOS_WIN__) // every keypress registered, also arrow keys
cout << endl << "Press any key to continue..." << endl;
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
_getch();
#elif defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
cout << endl << "Press ENTER to continue..." << endl;
std::cin.clear();
std::cin.ignore(std::cin.rdbuf()->in_avail());
std::cin.get();
#endif
return;
}
void computeRotationZ(Eigen::MatrixXd& rotationM, double degrees){
double radians = (degrees / 180) * M_PI;
Eigen::MatrixXd rotationZ = Eigen::MatrixXd::Zero(3, 3);
rotationZ << cos(radians), -sin(radians), 0,
sin(radians), cos(radians), 0,
0, 0, 1;
cout << rotationZ << endl;
rotationM = rotationZ;
}
void computeRotationX(Eigen::MatrixXd& rotationM, double degrees){
double radians = (degrees / 180) * M_PI;
Eigen::MatrixXd rotationX = Eigen::MatrixXd::Zero(3, 3);
rotationX << 1, 0, 0,
0, cos(radians), -sin(radians),
0, sin(radians), cos(radians);
cout << rotationX << endl;
rotationM = rotationX;
}
void computeRotationY(Eigen::MatrixXd& rotationM, double degrees){
double radians = (degrees / 180) * M_PI;
Eigen::MatrixXd rotationY = Eigen::MatrixXd::Zero(3, 3);
rotationY << cos(radians), 0, sin(radians),
0, 1, 0,
-sin(radians), 0, cos(radians);
cout << rotationY << endl;
rotationM = rotationY;
}
void addZeroMeanNoise(Eigen::MatrixXd& outputM, Eigen::MatrixXd& inputM, double sd){
if(sd == 0){
outputM = inputM;
return;
}
std::default_random_engine generator;
std::normal_distribution<double> distribution(0, sd);
Eigen::MatrixXd rndMatrix = Eigen::MatrixXd::Ones(inputM.rows(), inputM.cols());
for(int rowId = 0; rowId < inputM.rows(); rowId++){
rndMatrix.row(rowId) = rndMatrix.row(rowId) * (distribution(generator));
}
rndMatrix = rndMatrix + inputM;
outputM = rndMatrix;
}
/*
* This program is used for experimenting how sampling affects the
* accurary of the ICP convergence
*/
int main(int argc, char* args[]){
//Load in the non transformed bunny
std::vector<std::string> filepaths;
filepaths.push_back("../bunny_v2/bun000_v2.ply");
filepaths.push_back("../bunny_v2/bun045_v2.ply");
//filepaths.push_back("../bunny_v2/bun090_v2.ply");
//filepaths.push_back("../bunny_v2/bun180_v2.ply");
filepaths.push_back("../bunny_v2/bun270_v2.ply");
filepaths.push_back("../bunny_v2/bun315_v2.ply");
nNumBuns = 4;
//Specify colours for each bunny
vColours.push_back(Eigen::RowVector3d(1, 0, 0));
vColours.push_back(Eigen::RowVector3d(0, 1, 0));
vColours.push_back(Eigen::RowVector3d(0, 0, 1));
vColours.push_back(Eigen::RowVector3d(1, 1, 0));
vColours.push_back(Eigen::RowVector3d(1, 0, 1));
vColours.push_back(Eigen::RowVector3d(0, 1, 1));
for(int i = 0; i < filepaths.size(); i++){
Eigen::MatrixXd V;
Eigen::MatrixXi F;
igl::readPLY(filepaths[i], V, F);
vBunPts.push_back(V);
vBunFaces.push_back(F);
}
//Making adjustments to the 270 mesh
Eigen::MatrixXd R;
computeRotationY(R, -50);
vBunPts[2] = (R*vBunPts[2].transpose()).transpose();
//Create viewer for displaying the file
igl::opengl::glfw::Viewer viewer;
/*Display all the bunnies together
for(auto &pts : vBunPts){
viewer.data().add_points(pts, Eigen::RowVector3d(1, 0, 1));
}
/*
/*
* Global registration algorithm
* 1. Pick one bunny to be subject bunny
* 2. Build new Octree out of picked bunny
* 3. Build point cloud out of other bunnies, we denote BigBunny
* 4. Sample from BigBunny
* 5. Find corresponding points in subject bunny
* 6. Compute R and t and shift the subject bunny
* 7.Iterate 1 - 7
*/
//Parameters for q5
double dConvergeThreshold = 0.001;
int iters = 1;
if(argc > 1){
iters = std::stoi(args[1]);
}
int nMaxBunSelection = vBunPts.size() * iters;
double dAcceptThreshold = 0.8;
int aSqrDiff[nNumBuns];
//Loop for picking the subject bunny
for(int bunNum = 0; bunNum < nMaxBunSelection; bunNum++){
int bunPicked = bunNum % vBunPts.size();
//int bunPicked = 0;
cout << "Bun picked: " << bunPicked << endl;
double tic = igl::get_seconds();
//Build new octree out of the picked bunny
std::vector<std::vector<int>> O_PI;
Eigen::MatrixXi O_CH;
Eigen::MatrixXd O_CN;
Eigen::MatrixXd O_W;
igl::octree(vBunPts[bunPicked], O_PI, O_CH, O_CN, O_W);
//Build BigBunny
//First we need to find out the size of bunBunny
int nBigBunnyRows = 0;
for(int bunId = 0; bunId < vBunPts.size(); bunId++){
if(bunId != bunPicked){
nBigBunnyRows += vBunPts[bunId].rows();
}
}
Eigen::MatrixXd mBigBunnyPts(nBigBunnyRows, 3);
int nBigBunnyNextRow = 0;
for(int bunId = 0; bunId < vBunPts.size(); bunId++){
if(bunId != bunPicked){
mBigBunnyPts.block(nBigBunnyNextRow, 0, vBunPts[bunId].rows(), 3) = vBunPts[bunId];
nBigBunnyNextRow += vBunPts[bunId].rows();
}
}
//Sample from mBigBunny pts
int nNumSamples = mBigBunnyPts.rows()*0.1;
cout << "Sample size: " << nNumSamples << endl;
Eigen::MatrixXd samples(nNumSamples, 3);
getSamples(samples, mBigBunnyPts, nNumSamples);
//Find corresponding points
Eigen::MatrixXi mKNNResults;
igl::knn(samples, vBunPts[bunPicked], 1, O_PI, O_CH, O_CN, O_W, mKNNResults);
//Produce sampleNN
Eigen::MatrixXd samplesNN(nNumSamples, 3);
for(int s = 0; s < nNumSamples; s++){
int nRowIndex = mKNNResults.row(s)(0);
samplesNN.row(s) = vBunPts[bunPicked].row(nRowIndex);
}
//Reject outliers that are too far apart
Eigen::MatrixXd mSampleDists = (samples - samplesNN).cwiseAbs2().rowwise().sum();
std::vector<int> vKeepers;
double dAvgDist = mSampleDists.sum() / nNumSamples;
for(int s = 0; s < nNumSamples; s++){
if(mSampleDists(s) < (dAvgDist * dAcceptThreshold)){
vKeepers.push_back(s);
}
}
Eigen::MatrixXd mKeptSamples = Eigen::MatrixXd::Zero(vKeepers.size(), 3);
Eigen::MatrixXd mKeptSamplesNN = Eigen::MatrixXd::Zero(vKeepers.size(), 3);
for(int nKeeperId = 0; nKeeperId < vKeepers.size(); nKeeperId++){
int rowIndex = vKeepers[nKeeperId];
mKeptSamples.row(nKeeperId) = samples.row(rowIndex);
mKeptSamplesNN.row(nKeeperId) = samplesNN.row(rowIndex);
}
//Align the two point clouds
Eigen::MatrixXd R;
Eigen::RowVector3d t;
//ComputeRt is a R, t, fromPts, toPts
//In the previous programs we would use KeptSamples to KeptSamplesNN because we were
//after to keep a single mesh fixed. But in global registration, we need to adjust every
//mesh.
computeRt(R, t, mKeptSamplesNN, mKeptSamples);
vBunPts[bunPicked] = (R*vBunPts[bunPicked].transpose()).transpose().rowwise() + t;
cout << "adjusted bunnyNo: " << bunPicked << endl;
printf("%0.4f secs\n",igl::get_seconds()-tic);
for(auto &pts : vBunPts) {
iterations.push_back(pts);
}
/*
* We need some kind of exit condition. Previous we would use the sqr difference between
* to different meshes. Now that we have multiple meshes it could be possible that some meshes
* are adjusting greater amounts compared to other. So my exit condition is going to measure the
* difference between a subject bunny compared to the bigbunny. This means we can only terminate
* after adjusting every bunny. I.e. the number of iterations will be constrained to a multiple of
* nNumBuns
*/
//Transform the the sampled points and see how well they have converged.
Eigen::MatrixXd mKeptSamplesNNTransformed = (R*mKeptSamplesNN.transpose()).transpose().rowwise() + t;
double dSmolBunToBigBun = computeSqrDiff(mKeptSamplesNNTransformed, mKeptSamples);
aSqrDiff[bunPicked] = dSmolBunToBigBun;
}
cout << "Number of pt matrix saved: " << iterations.size() << endl;
viewer.data().clear();
for(int nBunId = 0; nBunId < vBunPts.size(); nBunId++){
viewer.data().add_points(vBunPts[nBunId], vColours[nBunId]);
}
viewer.data().point_size = point_size;
viewer.callback_key_down = &key_down;
viewer.launch();
return 0;
}
<file_sep>#include <stdlib.h>
#include <iostream>
#include <igl/readPLY.h>
#include <igl/knn.h>
#include <igl/octree.h>
#include <igl/opengl/glfw/Viewer.h>
#include <igl/get_seconds.h>
#include "gnuplot_i.h"
#include <math.h>
#include <random>
/*
* This .cpp file is for experimenting the behaviour of the ICP
* algorithm's convergence rate based on the extremity of the
* rotation of M1 points
*/
using namespace std;
int nNumBuns = 1;
int point_size = 2;
int displaying = 0;
std::vector<Eigen::MatrixXd> iterations;
std::vector<Eigen::MatrixXd> vBunPts;
std::vector<Eigen::MatrixXi> vBunFaces;
std::vector<Eigen::RowVector3d> vColours;
bool key_down(igl::opengl::glfw::Viewer& viewer, unsigned char key, int modifier){
if(key == '1'){
point_size++;
viewer.data().point_size = point_size;
}else if(key == '2'){
if(point_size > 0){
point_size--;
viewer.data().point_size = point_size;
}
}else if(key == '3'){
if(displaying != 0){
displaying-=nNumBuns;
cout << "displaying iteration: " << displaying << endl;
viewer.data().clear();
viewer.data().add_points(iterations[displaying], vColours[1]);
viewer.data().add_points(vBunPts[0], vColours[0]);
}
}else if(key == '4'){
if(displaying < iterations.size()){
displaying+=nNumBuns;
cout << "displaying iteration: " << displaying << endl;
viewer.data().clear();
viewer.data().add_points(iterations[displaying], vColours[1]);
viewer.data().add_points(vBunPts[0], vColours[0]);
}
}
return false;
}
void getSamples(Eigen::MatrixXd& ptSamples, Eigen::MatrixXd& points, int numberOfSamples){
/*
* Here we will return a random set of samples and output them into matrix passed
* through the ptSamples matrix reference
*/
if(ptSamples.rows() != numberOfSamples){
cout << "Number of samples does not match output Matrix rows" << endl;
exit(0);
}
if(numberOfSamples == points.rows()){
//If the number of samples required is the same number as all the points
//Then we will just copy the points matrix into ptSamples
ptSamples = points;
return;
}
//TODO::Implement a random sampler and return the sample in ptSamples
Eigen::VectorXi sampledIndices(numberOfSamples);
for(int sample = 0; sample < numberOfSamples; sample++){
int index;
int unique = 0;
while(!unique){
index = rand() % points.rows();
unique = 1;
int sampledIndex = 0;
while(sampledIndex <= sample){
if(sampledIndices(sampledIndex) == index){
unique = 0;
break;
}
sampledIndex++;
}
}
ptSamples.row(sample) = points.row(index);
}
}
void computeRt(Eigen::MatrixXd& R, Eigen::RowVector3d& t, Eigen::MatrixXd& sampledPts, Eigen::MatrixXd& sampledPtsNN){
//Alignment phase
/*
* 1. Compute the barycenters for each point sets. There are 2 point sets I have:
* The sampled points P and the nn of the sampled points Q
* 2. Compute the new pointsets P_hat and Q_hat
* 3. Compute matrix A
* 4. Compute SVD of matrix A = ULV'
* 5. Compute R = VU'
* 6. Compute t = p_barycenter - R*q_barycenter
*/
//Computing barycenters for samples and its nn
Eigen::RowVector3d samplesBC = sampledPts.colwise().sum()/sampledPts.rows();
Eigen::RowVector3d samplesNNBC = sampledPtsNN.colwise().sum()/sampledPtsNN.rows();
//Compute the recentered points
Eigen::MatrixXd hatSamples = sampledPts.rowwise() - samplesBC;
Eigen::MatrixXd hatSamplesNN = sampledPtsNN.rowwise() - samplesNNBC;
/*
Eigen::MatrixXd hatSamples = Eigen::MatrixXd::Zero(sampledPts.rows(), sampledPts.cols());
Eigen::MatrixXd hatSamplesNN = Eigen::MatrixXd::Zero(sampledPtsNN.rows(), sampledPtsNN.cols());
for(int rowId = 0; rowId < sampledPts.rows(); rowId++){
hatSamples.row(rowId) = sampledPts.row(rowId) - samplesBC;
hatSamplesNN.row(rowId) = sampledPtsNN.row(rowId) - samplesNNBC;
}
*/
//Assemble matrix A
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(3, 3);
for(int rowId = 0; rowId < sampledPts.rows(); rowId++){
A = A + (hatSamples.row(rowId).transpose() * hatSamplesNN.row(rowId));
}
//Compute the SVD of A then assemble R and t
Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);
R = svd.matrixV() * svd.matrixU().transpose();
t = samplesNNBC - ((R*samplesBC.transpose()).transpose());
}
double computeSqrDiff(Eigen::MatrixXd& samples, Eigen::MatrixXd& samplesNN){
double sqrDiff = (samples - samplesNN).cwiseAbs2().sum();
return sqrDiff;
}
void wait_for_key ()
{
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__TOS_WIN__) // every keypress registered, also arrow keys
cout << endl << "Press any key to continue..." << endl;
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
_getch();
#elif defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
cout << endl << "Press ENTER to continue..." << endl;
std::cin.clear();
std::cin.ignore(std::cin.rdbuf()->in_avail());
std::cin.get();
#endif
return;
}
void computeRotationZ(Eigen::MatrixXd& rotationM, double degrees){
double radians = (degrees / 180) * M_PI;
Eigen::MatrixXd rotationZ = Eigen::MatrixXd::Zero(3, 3);
rotationZ << cos(radians), -sin(radians), 0,
sin(radians), cos(radians), 0,
0, 0, 1;
cout << rotationZ << endl;
rotationM = rotationZ;
}
void computeRotationX(Eigen::MatrixXd& rotationM, double degrees){
double radians = (degrees / 180) * M_PI;
Eigen::MatrixXd rotationX = Eigen::MatrixXd::Zero(3, 3);
rotationX << 1, 0, 0,
0, cos(radians), -sin(radians),
0, sin(radians), cos(radians);
cout << rotationX << endl;
rotationM = rotationX;
}
void computeRotationY(Eigen::MatrixXd& rotationM, double degrees){
double radians = (degrees / 180) * M_PI;
Eigen::MatrixXd rotationY = Eigen::MatrixXd::Zero(3, 3);
rotationY << cos(radians), 0, sin(radians),
0, 1, 0,
-sin(radians), 0, cos(radians);
cout << rotationY << endl;
rotationM = rotationY;
}
void addZeroMeanNoise(Eigen::MatrixXd& outputM, Eigen::MatrixXd& inputM, double sd){
if(sd == 0){
outputM = inputM;
return;
}
std::default_random_engine generator;
std::normal_distribution<double> distribution(0, sd);
Eigen::MatrixXd rndMatrix = Eigen::MatrixXd::Ones(inputM.rows(), inputM.cols());
for(int rowId = 0; rowId < inputM.rows(); rowId++){
rndMatrix.row(rowId) = rndMatrix.row(rowId) * (distribution(generator));
}
rndMatrix = rndMatrix + inputM;
outputM = rndMatrix;
}
void computePseudoInverse(Eigen::MatrixXd& mOutputM, Eigen::MatrixXd& A){
//std::cout << "A" << std::endl;
//std::cout << A << std::endl;
Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);
Eigen::VectorXd vSingularValues = svd.singularValues();
Eigen::MatrixXd mInvertedSigma = Eigen::MatrixXd::Zero(A.cols(), A.rows());
for(int nValID = 0; nValID < vSingularValues.size(); nValID++){
double dCoeff = 1 / vSingularValues(nValID);
mInvertedSigma(nValID, nValID) = dCoeff;
}
Eigen::MatrixXd mPInv = Eigen::MatrixXd::Zero(A.cols(), A.rows());
mPInv = svd.matrixV() * mInvertedSigma * svd.matrixU().transpose();
//std::cout << "Pseudo Inverse" << std::endl;
//std::cout << mPInv << std::endl;
mOutputM = mPInv;
}
/*
* This program is used for experimenting how sampling affects the
* accurary of the ICP convergence
*/
int main(int argc, char* args[]){
/*
* q6 - point to plane ICP implementation
* This code's intention is to use the approximation to the minimum least squares
* solution of the point to plane ICP implementation. I am using the derivation
* from the literation referece: [1] <NAME>, “Linear Least-squares Optimization for
* Point-to-plane ICP Surface Registration,” Chapel Hill, Univ. North Carolina, no.
* February, pp. 2–4, 2004, [Online].
* Available: https://www.iscs.nus.edu.sg/~lowkl/publications/lowk_point-to-plane_icp_techrep.pdf.
*
* Impementation overview:
* 1. Define subject bunny and target bunny
* 2. target bunny will remain static and so we will create the Octree from the target bunny
* 3. Sample the subject bunny
* 4. Find corresponding points from samples and get the corresponding point's normals
* 5. Reject outliers
* 6. Construct design matrix A
* 7. Construct matrix b
* 8. Compute SVD of A
* 9. Compute Pseudo inverse of A using SVD results
* 10. Find the optimal parameters by multiplying Pseudo inverse of A with B
* 11. Construct Rotation matrix R and translation vector t
* 12. Apply transformation on subject bunny
* 13. Repeat
*/
//1.Define the subject bunny and target bunny
//Load in the non transformed bunny
std::vector<std::string> filepaths;
filepaths.push_back("../bunny_v2/bun000_v2.ply");
filepaths.push_back("../bunny_v2/bun045_v2.ply");
//filepaths.push_back("../bunny_v2/bun090_v2.ply");
//filepaths.push_back("../bunny_v2/bun180_v2.ply");
//filepaths.push_back("../bunny_v2/bun270_v2.ply");
//filepaths.push_back("../bunny_v2/bun315_v2.ply");
nNumBuns = 1;
//Specify colours for each bunny
vColours.push_back(Eigen::RowVector3d(1, 0, 0));
vColours.push_back(Eigen::RowVector3d(0, 1, 0));
for(int i = 0; i < filepaths.size(); i++){
Eigen::MatrixXd V;
Eigen::MatrixXi F;
igl::readPLY(filepaths[i], V, F);
vBunPts.push_back(V);
vBunFaces.push_back(F);
}
int nTargetBunny = 0;
int nSubjectBunny = 1;
iterations.push_back(vBunPts[nSubjectBunny]);
//Get the normals of the Target Bunny
Eigen::MatrixXd mTargetNormals;
igl::per_vertex_normals(vBunPts[nTargetBunny], vBunFaces[nTargetBunny], mTargetNormals);
//2.Construct Octree of the static TargetBunny
std::vector<std::vector<int>> O_PI;
Eigen::MatrixXi O_CH;
Eigen::MatrixXd O_CN;
Eigen::MatrixXd O_W;
igl::octree(vBunPts[nTargetBunny], O_PI, O_CH, O_CN, O_W);
//Parameters for the iterations
int nNumSamp = 1000;
int nMaxIter = 100;
double dAcceptThreshold = 0.8;
double dConvergenceThreshold = 0.0001;
double dLastDiff = 999999999;
if(argc > 1){
nMaxIter = std::stoi(args[1]);
dConvergenceThreshold = std::stod(args[2]);
}
//3.Sample SubjectBunny and Get each sample's normal as well
for(int iter = 0; iter < nMaxIter; iter++) {
Eigen::MatrixXd mSamples = Eigen::MatrixXd::Zero(nNumSamp, 3);
getSamples(mSamples, vBunPts[nSubjectBunny], nNumSamp);
//4.Find the corresponding points
Eigen::MatrixXi mKNNResults;
igl::knn(mSamples, vBunPts[nTargetBunny], 1, O_PI, O_CH, O_CN, O_W, mKNNResults);
//Construct mSampleNN (The corresponding samples from target bunny)
//Also construct mSampleNormals (The normals of the corresponding samples from target bunny)
Eigen::MatrixXd mSamplesNN(nNumSamp, 3);
Eigen::MatrixXd mSampleNormals(nNumSamp, 3);
for (int s = 0; s < nNumSamp; s++) {
int nRowIndex = mKNNResults.row(s)(0);
mSamplesNN.row(s) = vBunPts[nTargetBunny].row(nRowIndex);
mSampleNormals.row(s) = mTargetNormals.row(nRowIndex);
}
//5.Reject outliers that are too far apart
Eigen::MatrixXd mSampleDists = (mSamples - mSamplesNN).cwiseAbs2().rowwise().sum();
std::vector<int> vKeepers;
double dAvgDist = mSampleDists.sum() / nNumSamp;
for (int s = 0; s < nNumSamp; s++) {
if (mSampleDists(s) < (dAvgDist * dAcceptThreshold)) {
if (!isnan(mSampleNormals.row(s)(0))) {
vKeepers.push_back(s);
}
}
}
Eigen::MatrixXd mKeptSamples = Eigen::MatrixXd::Zero(vKeepers.size(), 3);
Eigen::MatrixXd mKeptSamplesNN = Eigen::MatrixXd::Zero(vKeepers.size(), 3);
Eigen::MatrixXd mKeptSampleNormals = Eigen::MatrixXd::Zero(vKeepers.size(), 3);
for (int nKeeperId = 0; nKeeperId < vKeepers.size(); nKeeperId++) {
int rowIndex = vKeepers[nKeeperId];
mKeptSamples.row(nKeeperId) = mSamples.row(rowIndex);
mKeptSamplesNN.row(nKeeperId) = mSamplesNN.row(rowIndex);
mKeptSampleNormals.row(nKeeperId) = mSampleNormals.row(rowIndex);
}
//6. Build the Design Matrix A
Eigen::MatrixXd mA = Eigen::MatrixXd::Zero(vKeepers.size(), 6);
for (int rowId = 0; rowId < vKeepers.size(); rowId++) {
Eigen::RowVector3d rvSi = mKeptSamples.row(rowId);
Eigen::RowVector3d rvNi = mKeptSampleNormals.row(rowId);
int x = 0;
int y = 1;
int z = 2;
double dCol1 = rvNi(z) * rvSi(y) - rvNi(y) * rvSi(z); // NizSiy - NiySiz
double dCol2 = rvNi(x) * rvSi(z) - rvNi(z) * rvSi(x); // NixSiz - NizSix
double dCol3 = rvNi(y) * rvSi(x) - rvNi(x) * rvSi(y); // NiySix - NixSiy
double dCol4 = rvNi(x);
double dCol5 = rvNi(y);
double dCol6 = rvNi(z);
Eigen::RowVectorXd rvA(6);
rvA << dCol1, dCol2, dCol3, dCol4, dCol5, dCol6;
mA.row(rowId) = rvA;
}
//7. Build vector B - Keep in mind that this is not a RowVector (its a column vector)
Eigen::VectorXd vB = Eigen::VectorXd::Zero(vKeepers.size());
for (int rowId = 0; rowId < vKeepers.size(); rowId++) {
Eigen::RowVector3d rvSi = mKeptSamples.row(rowId);
Eigen::RowVector3d rvDi = mKeptSamplesNN.row(rowId);
Eigen::RowVector3d rvNi = mKeptSampleNormals.row(rowId);
int x = 0;
int y = 1;
int z = 2;
double dRow =
rvNi(x) * rvDi(x) + rvNi(y) * rvDi(y) + rvNi(z) * rvDi(z) - rvNi(x) * rvSi(x) - rvNi(y) * rvSi(y) -
rvNi(z) * rvSi(z);
vB(rowId) = dRow;
}
//8 & 9 Compute SVD and then construct the pseudo inverse of A
Eigen::MatrixXd mPInv;
computePseudoInverse(mPInv, mA);
//10. Find optimal parameters
Eigen::VectorXd vParams = Eigen::VectorXd::Zero(6);
vParams = mPInv * vB;
double x = vParams(3);
double y = vParams(4);
double z = vParams(5);
Eigen::RowVector3d t(x, y, z);
Eigen::Matrix3d R;
double alpha = vParams(0);
double beta = vParams(1);
double gamma = vParams(2);
R << 1, alpha*beta-gamma, alpha*gamma+beta,
gamma, alpha*beta*gamma+1, beta*gamma-alpha,
-beta, alpha, 1;
vBunPts[nSubjectBunny] = (R * vBunPts[nSubjectBunny].transpose()).transpose().rowwise() + t;
iterations.push_back(vBunPts[nSubjectBunny]);
cout << "Completed Iteration: " << iter << endl;
double dThisDiff = computeSqrDiff(mKeptSamples, mKeptSamplesNN);
if(abs(dThisDiff - dLastDiff) < dConvergenceThreshold){
cout << "Converged with error: " << dThisDiff << endl;
cout << "Last diff: " << dLastDiff << endl;
cout << "Iteration diff: " << abs(dThisDiff-dLastDiff) << endl;
break;
}
dLastDiff = dThisDiff;
}
//Create viewer for displaying the file
igl::opengl::glfw::Viewer viewer;
//FUN: Playing with Vertex normal generated edges
/*
* //Get the vertex normals
Eigen::MatrixXd V1_N;
igl::per_vertex_normals(vBunPts[0], vBunFaces[0], V1_N);
Eigen::MatrixXd V1_N_edges = Eigen::MatrixXd::Zero(vBunPts[0].rows(), 3);
double normal_length = 0.001;
if(argc > 1){
normal_length = std::stod(args[1]);
}
V1_N_edges = vBunPts[0] + (V1_N * normal_length);
viewer.data().add_edges(vBunPts[0], V1_N_edges, V1_N);
*/
viewer.data().add_points(vBunPts[nTargetBunny], vColours[0]);
viewer.data().add_points(vBunPts[nSubjectBunny], vColours[1]);
viewer.data().point_size = point_size;
viewer.callback_key_down = &key_down;
viewer.launch();
return 0;
}
<file_sep>cmake_minimum_required(VERSION 3.10)
#specifies the project name
project(cw1_ICP)
#What is the cmake module path?
#listfiles are files that have cmake code in them and usually have the
#file extension .cmake
#CMAKE_MODULE_PATH defines where to look for more of these .cmake files
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake)
message(CMAKE_MODULE_PATH=${CMAKE_MODULE_PATH})
#libigl
option(LIBIGL_WITH_OPENGL "Use OpenGL" ON)
option(LIBIGL_WITH_OPENGL_GLFW "Use GLFW" ON)
option(LIBIGL_WITH_OPENGL_GLFW_IMGUI "Use GLFW_IMGUI" ON)
find_package(LIBIGL REQUIRED)
#Add in my project files
file(GLOB SRCFILES *.cpp)
file(GLOB INCLUDEFILES *.h)
#Set binary name (the executable file name)
set(EXE_NAME ${PROJECT_NAME}_bin)
set(CMAKE_CXX_STANDARD 11)
#add binary
add_executable(${EXE_NAME} ./main.cpp ${INCLUDEFILES})
add_executable(${EXE_NAME}_test ./knn_test.cpp ${INCLUDEFILES})
add_executable(${EXE_NAME}_q2 ./q2.cpp ${INCLUDEFILES})
add_executable(${EXE_NAME}_q3 ./q3.cpp ${INCLUDEFILES})
add_executable(${EXE_NAME}_test2 ./axisTest.cpp ${INCLUDEFILES})
add_executable(${EXE_NAME}_q4 ./q4.cpp ${INCLUDEFILES})
add_executable(${EXE_NAME}_q5 ./q5.cpp ${INCLUDEFILES})
add_executable(${EXE_NAME}_q6 ./q6.cpp ${INCLUDEFILES})
message(INCLUDEFILES=${INCLUDEFILES})
target_link_libraries(${EXE_NAME}
igl::core
igl::opengl
igl::opengl_glfw
igl::opengl_glfw_imgui
)
target_link_libraries(${EXE_NAME}_test
igl::core
igl::opengl
igl::opengl_glfw
igl::opengl_glfw_imgui
)
target_link_libraries(${EXE_NAME}_q2
igl::core
igl::opengl
igl::opengl_glfw
igl::opengl_glfw_imgui
)
target_link_libraries(${EXE_NAME}_q3
igl::core
igl::opengl
igl::opengl_glfw
igl::opengl_glfw_imgui
)
target_link_libraries(${EXE_NAME}_test2
igl::core
igl::opengl
igl::opengl_glfw
igl::opengl_glfw_imgui
)
target_link_libraries(${EXE_NAME}_q4
igl::core
igl::opengl
igl::opengl_glfw
igl::opengl_glfw_imgui
)
target_link_libraries(${EXE_NAME}_q5
igl::core
igl::opengl
igl::opengl_glfw
igl::opengl_glfw_imgui
)
target_link_libraries(${EXE_NAME}_q6
igl::core
igl::opengl
igl::opengl_glfw
igl::opengl_glfw_imgui
)
<file_sep>#include <stdlib.h>
#include <chrono>
#include <iostream>
#include <igl/readPLY.h>
#include <igl/knn.h>
#include <igl/octree.h>
#include <igl/opengl/glfw/Viewer.h>
#include <igl/get_seconds.h>
using namespace std;
Eigen::MatrixXd V1;
Eigen::MatrixXi F1;
int point_size = 10;
int displaying = 0;
Eigen::MatrixXd samplesG;
Eigen::MatrixXd samplesNNG;
bool key_down(igl::opengl::glfw::Viewer& viewer, unsigned char key, int modifier){
if(key == '1'){
point_size++;
viewer.data().point_size = point_size;
}else if(key == '2'){
if(point_size > 0){
point_size--;
viewer.data().point_size = point_size;
}
}else if(key == '3'){
if(displaying != 0){
displaying--;
cout << "displaying iteration: " << displaying << endl;
viewer.data().clear();
viewer.data().add_points(samplesG.row(displaying), Eigen::RowVector3d(1, 1, 1));
viewer.data().add_points(samplesNNG.row(displaying), Eigen::RowVector3d(0, 0, 0));
}
}else if(key == '4'){
if(displaying != samplesG.rows()-1){
displaying++;
cout << "displaying iteration: " << displaying << endl;
viewer.data().clear();
viewer.data().add_points(samplesG.row(displaying), Eigen::RowVector3d(1, 1, 1));
viewer.data().add_points(samplesNNG.row(displaying), Eigen::RowVector3d(00, 0, 0));
}
}
return false;
}
void getSamples(Eigen::MatrixXd& ptSamples, Eigen::MatrixXd& points, int numberOfSamples){
/*
* Here we will return a random set of samples and output them into matrix passed
* through the ptSamples matrix reference
*/
if(ptSamples.rows() != numberOfSamples){
cout << "Number of samples does not match output Matrix rows" << endl;
exit(0);
}
if(numberOfSamples == points.rows()){
//If the number of samples required is the same number as all the points
//Then we will just copy the points matrix into ptSamples
ptSamples << points;
return;
}
//TODO::Implement a random sampler and return the sample in ptSamples
Eigen::VectorXi sampledIndices(numberOfSamples);
for(int sample = 0; sample < numberOfSamples; sample++){
int index;
int unique = 0;
while(!unique){
index = rand() % points.rows();
unique = 1;
int sampledIndex = 0;
while(sampledIndex <= sample){
if(sampledIndices(sampledIndex) == index){
unique = 0;
break;
}
sampledIndex++;
}
}
ptSamples.row(sample) = points.row(index);
}
}
void computeRt(Eigen::MatrixXd& R, Eigen::RowVector3d& t, Eigen::MatrixXd& sampledPts, Eigen::MatrixXd& sampledPtsNN){
//Alignment phase
/*
* 1. Compute the barycenters for each point sets. There are 2 point sets I have:
* The sampled points P and the nn of the sampled points Q
* 2. Compute the new pointsets P_hat and Q_hat
* 3. Compute matrix A
* 4. Compute SVD of matrix A = ULV'
* 5. Compute R = VU'
* 6. Compute t = p_barycenter - R*q_barycenter
*/
//Computing barycenters for samples and its nn
Eigen::RowVector3d samplesBC = sampledPts.colwise().sum()/sampledPts.rows();
Eigen::RowVector3d samplesNNBC = sampledPtsNN.colwise().sum()/sampledPtsNN.rows();
cout << "samplesBC" << samplesBC << endl;
cout << "samplesNNBC" << samplesNNBC << endl;
//Compute the recentered points
Eigen::MatrixXd hatSamples = sampledPts.rowwise() - samplesBC;
Eigen::MatrixXd hatSamplesNN = samplesNNBC.rowwise() - samplesNNBC;
//Assemble matrix A
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(3, 3);
for(int rowId = 0; rowId < sampledPts.rows(); rowId++){
A = A + (hatSamples.row(rowId).transpose() * hatSamplesNN.row(rowId));
}
//Compute the SVD of A then assemble R and t
Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);
R = svd.matrixV() * svd.matrixU().transpose();
cout << R << endl;
t = samplesNNBC - (R * samplesBC.transpose()).transpose();
}
int main(int argc, char* args[]){
//Load in the files
Eigen::MatrixXd V2;
Eigen::MatrixXi F2;
igl::readPLY("../bunny_v2/bun000_v2.ply", V1, F1);
igl::readPLY("../bunny_v2/bun045_v2.ply", V2, F2);
//Create viewer for displaying the file
igl::opengl::glfw::Viewer viewer;
//Construct our octree out of our Q Points (that we are trying to map to)
//Initialize Octree properties
std::vector<std::vector<int>> O_PI; //Points inside each Octree cell
Eigen::MatrixXi O_CH; //Children of each node in the Octree
Eigen::MatrixXd O_CN; //Mid point of each node in the Octree
Eigen::VectorXd O_W; //Width of each node in the Octree
//Compute Octree
igl::octree(V1, O_PI, O_CH, O_CN, O_W);
Eigen::MatrixXd currV2 = V2;
//Take samples from V2 (which change every iteration)
int numOfSamples = 1000;
Eigen::MatrixXd samples(numOfSamples, 3);
getSamples(samples, currV2, numOfSamples);
//We have our set of points P
//Next we need to find the closest point for each p in Q
//Set up results matrix for kNN
Eigen::MatrixXi kNNResults; //This will hold the kNN for each point we give to the algorithm
int numNN = 1;
double tic = igl::get_seconds();
igl::knn(samples, V1, numNN, O_PI, O_CH, O_CN, O_W, kNNResults);
printf("%0.4f secs\n",igl::get_seconds()-tic);
//Collect the V1 points found
cout << "num of samples: " << numOfSamples << endl;
cout << "num of rows: " << samples.rows() << endl;
Eigen::MatrixXd samplesNN(samples.rows(), samples.cols());
for (int sample = 0; sample < numOfSamples; sample++) {
cout << sample << endl;
int rowIndex = kNNResults.row(sample)(0);
samplesNN.row(sample) = V1.row(rowIndex);
}
cout << "passed collecting points" << endl;
samplesG = samples;
samplesNNG = samplesNN;
Eigen::MatrixXd R;
Eigen::RowVector3d t;
computeRt(R, t, samples, samplesNN);
//Computing barycenters for samples and its nn
Eigen::RowVector3d samplesBC = samples.colwise().sum()/samples.rows();
Eigen::RowVector3d samplesNNBC = samplesNN.colwise().sum()/samplesNN.rows();
viewer.data().add_points(samplesBC, Eigen::RowVector3d(1, 0, 0));
viewer.data().add_points(samplesNNBC, Eigen::RowVector3d(0, 1, 0))
//Compute the recentered points
Eigen::MatrixXd hatSamples = samples.rowwise() - samplesBC;
Eigen::MatrixXd hatSamplesNN = samplesNN.rowwise() - samplesNNBC;
viewer.data().add_points(hatSamples, Eigen::RowVector3d(1,1,1));
viewer.data().add_points(hatSamplesNN, Eigen::RowVector3d(0,0,0));
viewer.data().point_size = point_size;
viewer.data().add_points(V1, Eigen::RowVector3d(1, 0, 0.5)); //pink
viewer.data().add_points(currV2, Eigen::RowVector3d(0.4, 0.5, 0.1)); //greenish
viewer.callback_key_down = &key_down;
viewer.launch();
return 0;
}
|
b7a1f77134c4b95736a61832e2f9ad2a61a55891
|
[
"C++",
"CMake"
] | 7 |
C++
|
gheylam/OrangePeel_ICP
|
2ef4b7369adc2d50cc18228de7769de27aa1d09d
|
01f1e7ef3cde61e0814bafe0d26586abf2a3c518
|
refs/heads/master
|
<repo_name>jperl/tools<file_sep>/components/Layout.tsx
import * as React from 'react'
import Link from 'next/link'
import Head from 'next/head'
import { Container, List } from 'semantic-ui-react'
type Props = {
title?: string
}
type Routing = {
icon: string
label: string
path: string
}
const routings: Routing[] = [
{ icon: 'home', label: 'Top', path: '/' },
{
icon: 'translate',
label: 'GHA BadgeMaker',
path: '/gha-badge-maker',
},
]
const Layout: React.FC<Props> = ({
children,
title = 'mini web tools by anozon',
}) => (
<div>
<Head>
<title>{title}</title>
<meta charSet="utf-8" />
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
</Head>
<header></header>
<Container>{children}</Container>
<footer>
<Container>
<hr />
<nav>
<List>
{routings.map(routing => (
<List.Item
key={routing.path}
icon={routing.icon}
content={
<Link href={routing.path}>
<a>{routing.label}</a>
</Link>
}
/>
))}
</List>
</nav>
<a href="https://anozon.me">anozon.me</a>
</Container>
</footer>
<style jsx>{`
nav {
display: flex;
div:not(:first-child) {
margin-left: 1rem;
}
}
`}</style>
</div>
)
export default Layout
<file_sep>/pages/gha-badge-maker.tsx
import * as React from 'react'
import Layout from '../components/Layout'
const GHABadgePage = () => {
const [url, setUrl] = React.useState<string>('')
return (
<Layout title="GHA BadgeMaker">
<h1>Introduction</h1>
<h3>GHA BadgeMaker</h3>
<p>Generate GitHub Actions Badge by url.</p>
<input
value={url}
onChange={({ target: { value } }) => setUrl(value)}
></input>
</Layout>
)
}
export default GHABadgePage
<file_sep>/pages/index.tsx
import * as React from 'react'
import { NextPage } from 'next'
import Layout from '../components/Layout'
const IndexPage: NextPage = () => {
return (
<Layout title="Home | Next.js + TypeScript Example">
<h1>Tools made by anozon</h1>
<p>Collection of Minimum web tools</p>
</Layout>
)
}
export default IndexPage
|
d621fe9f812f751312922e00b0a14640fffd85fc
|
[
"TSX"
] | 3 |
TSX
|
jperl/tools
|
e87626c8ba472b4635b459bf76f03cb44148a141
|
f4cfae5ee92c480fea78be3e513d68b75346127b
|
refs/heads/master
|
<file_sep>#include <iostream>
using namespace std;
int main() {
int num,i,j;
cin>>num;
for (i=0;i<num;i++){
for (j=0;j<num;j++){
if(j==i)
{cout<<"1";
}else if(i==0 && j>=1){
cout<<"1";
}else if(i==num-1 && j<=num-1){
cout<<"1";
}else if(i>0 && j==0){
cout<<"1";
}else if(i<num-1 && j==num-1){
cout<<"1";
}else {
cout<<" ";
}
}
cout<<"\n";
}
return 0;
}
<file_sep>#include <iostream>
#include <cmath>
using namespace std;
int i,num;
float promedio(){
int PC1,PC2,PC3,PC4,P1,E1,E2;
float prom;
for (i=1;i<=num;i++){
cout<<"Alumno numero "<<i;
do{
cout<<"Practica 1: ";
cin>>PC1;
}while(PC1<0 || PC1>20);
do{
cout<<"Practica 2: ";
cin>>PC2;
}while(PC2<0 || PC2>20);
do{
cout<<"Practica 3: ";
cin>>PC3;
}while(PC3<0 || PC3>20);
do{
cout<<"Practica 4: ";
cin>>PC4;
}while(PC4<0 || PC4>20);
do{
cout<<"Proyecto 1: ";
cin>>P1;
}while(P1<0 || P1>20);
do{
cout<<"Examen 1: ";
cin>>E1;
}while(E1<0 || E1>20);
do{
cout<<"Examen 2: ";
cin>>E2;
}while(E2<0 || E2>20);
prom= PC1*0.05+PC2*0.1+PC3*0.1+PC4*0.15+P1*0.2+E1*0.2+E2*0.2;
cout<<"Su promedio es "<<prom;
if(prom>=18.0 && prom<=20){
cout<<"UD asistira a ACM - ICPC International Collegiate Programming Contest";
}else if(prom>=15.0 && prom<=17.99){
cout<<"UD asistira al Imagine Cup";
}else if(prom>=12.0 && prom<=14.99){
cout<<"UD asistira al Hackaton de Miraflores";
}else if(prom < 12.0){
cout<<"Necesita mejorar";
}
}
return 0;
}
int main() {
int num;
float promedior;
do{
cout<<"Numero de alumnos: ";
cin>>num;
}while(num < 3 || num>=30);
promedior= promedio();
return promedior;
}
<file_sep>#include <iostream>
using namespace std;
int main() {
int num,max,i,min,n;
cout<<"Ingrese cuantos numeros ingresara: ";
cin>>n;
for(i=0;i<n;i++){
cout<<"Ingrese el numero: ";
cin>>num;
if (i==0){
max = num;
}
else{
if(num>max)max=num;
}
}
cout<<"el numero mayor es: "<<max;
return 0;
}
|
c0dc71f2a396cc89ec977a622df9b340c4ade9df
|
[
"C++"
] | 3 |
C++
|
cs1102-lab1-09-2019-2/estructuras-selectivas-y-repetitivas-DavidCaleb
|
103a73f4a0e37765b2fd220804b6f0053d297bab
|
a2264b9b4d9f0e76be35d979e8c44d4b7041d7a4
|
refs/heads/master
|
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
using AuthorIntrusion.Common.Commands;
using MfGames.Commands;
using MfGames.Commands.TextEditing;
using MfGames.GtkExt.TextEditor.Models;
using MfGames.GtkExt.TextEditor.Models.Buffers;
namespace AuthorIntrusion.Gui.GtkGui.Commands
{
public abstract class ProjectCommandAdapter:
ITextEditingCommand<OperationContext>
{
#region Properties
public bool CanUndo
{
get { return true; }
}
public IBlockCommand Command
{
get { return command; }
set
{
command = value;
// Wrapped commands default to not updating themselves.
command.UpdateTextPosition = DoTypes.None;
}
}
public bool IsTransient
{
get { return false; }
}
public DoTypes UpdateTextPosition
{
get { return Command.UpdateTextPosition; }
set
{
//Debug.WriteLine(
// this + ": Changeing UpdateTextPosition from " + Command.UpdateTextPosition
// + " to " + value);
Command.UpdateTextPosition = value;
}
}
public DoTypes UpdateTextSelection { get; set; }
protected Project Project { get; private set; }
#endregion
#region Methods
public virtual void Do(OperationContext context)
{
Action<BlockCommandContext> action = Command.Do;
PerformCommandAction(context, action);
}
public virtual void PostDo(OperationContext context)
{
}
public virtual void PostUndo(OperationContext context)
{
}
public void Redo(OperationContext context)
{
Action<BlockCommandContext> action = Command.Redo;
PerformCommandAction(context, action);
}
public virtual void Undo(OperationContext context)
{
Action<BlockCommandContext> action = Command.Undo;
PerformCommandAction(context, action);
}
private void PerformCommandAction(
OperationContext context,
Action<BlockCommandContext> action)
{
// Every command needs a full write lock on the blocks.
using (Project.Blocks.AcquireLock(RequestLock.Write))
{
// Create the context for the block commands.
var blockContext = new BlockCommandContext(Project);
// Execute the internal command.
action(blockContext);
// Set the operation context from the block context.
if (blockContext.Position.HasValue)
{
// Grab the block position and figure out the index.
BlockPosition blockPosition = blockContext.Position.Value;
int blockIndex = Project.Blocks.IndexOf(blockPosition.BlockKey);
var position = new TextPosition(blockIndex, (int) blockPosition.TextIndex);
// Set the context results.
context.Results = new LineBufferOperationResults(position);
}
}
}
#endregion
#region Constructors
protected ProjectCommandAdapter(Project project)
{
Project = project;
}
#endregion
#region Fields
private IBlockCommand command;
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using System.Xml;
using AuthorIntrusion.Common.Plugins;
namespace AuthorIntrusion.Common.Persistence.Filesystem
{
public class FilesystemPersistenceSettingsWriter:
PersistenceReaderWriterBase<FilesystemPersistenceSettings>
{
#region Methods
/// <summary>
/// Writes the structure file, to either the project Writer or the settings
/// file depending on the persistence settings.
/// </summary>
/// <param name="projectWriter">The project Writer.</param>
public void Write(XmlWriter projectWriter)
{
// Figure out which Writer we'll be using.
bool createdWriter;
XmlWriter writer = GetXmlWriter(
projectWriter, Macros, Settings.SettingsFilename, out createdWriter);
// Start by creating the initial element.
writer.WriteStartElement("settings", ProjectNamespace);
writer.WriteElementString("version", "1");
// Write out the project settings.
Project project = Project;
project.Settings.Flush();
project.Settings.Save(writer);
// Write out the plugin controllers.
IList<ProjectPluginController> projectControllers =
project.Plugins.Controllers;
if (projectControllers.Count != 0)
{
// We always work with sorted plugins to simplify change control.
var pluginNames = new List<string>();
foreach (ProjectPluginController controller in projectControllers)
{
pluginNames.Add(controller.Name);
}
pluginNames.Sort();
// Write out a list of plugins.
writer.WriteStartElement("plugins", ProjectNamespace);
foreach (string pluginName in pluginNames)
{
writer.WriteElementString("plugin", ProjectNamespace, pluginName);
}
writer.WriteEndElement();
}
// Finish up the blocks element.
writer.WriteEndElement();
// If we created the Writer, close it.
if (createdWriter)
{
writer.Dispose();
}
}
#endregion
#region Constructors
public FilesystemPersistenceSettingsWriter(
PersistenceReaderWriterBase<FilesystemPersistenceSettings> baseWriter)
: base(baseWriter)
{
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Commands;
using MfGames.Commands;
using MfGames.GtkExt.TextEditor.Models;
namespace AuthorIntrusion.Gui.GtkGui.Commands
{
public class ProjectCompositeCommandAdapter:
CompositeCommand<BlockCommandContext>,
IWrappedCommand
{
#region Methods
public void PostDo(OperationContext context)
{
}
public void PostUndo(OperationContext context)
{
}
protected override void Do(
IUndoableCommand<BlockCommandContext> command,
BlockCommandContext context)
{
// Perform the base command.
base.Do(command, context);
// Handle the post operation for the wrapped command.
var wrappedCommand = (IWrappedCommand) command;
wrappedCommand.PostDo(operationContext);
}
protected override void Undo(
IUndoableCommand<BlockCommandContext> command,
BlockCommandContext context)
{
// Handle the base operation.
base.Undo(command, context);
// Handle the post operation for the wrapped command.
var wrappedCommand = (IWrappedCommand) command;
wrappedCommand.PostUndo(operationContext);
}
#endregion
#region Constructors
public ProjectCompositeCommandAdapter(
ProjectCommandController projectCommandController,
CompositeCommand<OperationContext> composite,
OperationContext operationContext)
: base(true, false)
{
// Save the operation context so we can call back into the editor.
this.operationContext = operationContext;
// Go through the commands and wrap each one.
foreach (ICommand<OperationContext> command in composite.Commands)
{
IWrappedCommand wrappedCommand =
projectCommandController.WrapCommand(command, operationContext);
Commands.Add(wrappedCommand);
}
}
#endregion
#region Fields
private readonly OperationContext operationContext;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using AuthorIntrusion.Common.Blocks;
using MfGames.Commands;
using MfGames.Commands.TextEditing;
namespace AuthorIntrusion.Common.Commands
{
/// <summary>
/// Project-based manager class to handle command processing along with the undo
/// and redo functionality.
/// </summary>
public class BlockCommandSupervisor:
UndoRedoCommandController<BlockCommandContext>
{
#region Properties
/// <summary>
/// Gets the LastPosition of the last command run, if it has a non-empty
/// position. Empty positions are ignored.
/// </summary>
public BlockPosition LastPosition { get; private set; }
private Project Project { get; set; }
#endregion
#region Methods
public override void Do(
ICommand<BlockCommandContext> command,
BlockCommandContext state)
{
// Call the base implementation first.
base.Do(command, state);
// If we have a position, set it.
if (state.Position.HasValue)
{
LastPosition = state.Position.Value;
}
}
/// <summary>
/// Helper method to create and perform the InsertText command.
/// </summary>
/// <param name="block">The block to insert text.</param>
/// <param name="textIndex">Index to start the insert.</param>
/// <param name="text">The text to insert.</param>
public void InsertText(
Block block,
int textIndex,
string text)
{
InsertText(
new BlockPosition(block.BlockKey, (CharacterPosition) textIndex), text);
}
public override ICommand<BlockCommandContext> Redo(BlockCommandContext state)
{
// Call the base implementation first.
ICommand<BlockCommandContext> command = base.Redo(state);
// If we have a position, set it.
if (state.Position.HasValue)
{
LastPosition = state.Position.Value;
}
// Return the redone command.
return command;
}
public override ICommand<BlockCommandContext> Undo(BlockCommandContext state)
{
// Call the base implementation first.
ICommand<BlockCommandContext> command = base.Undo(state);
// If we have a position, set it.
if (state.Position.HasValue)
{
LastPosition = state.Position.Value;
}
// Return the undone command.
return command;
}
/// <summary>
/// Helper method to create and perform the InsertText command.
/// </summary>
/// <param name="position">The position to insert the text.</param>
/// <param name="text">The text to insert.</param>
private void InsertText(
BlockPosition position,
string text)
{
var command = new InsertTextCommand(position, text);
var context = new BlockCommandContext(Project);
Do(command, context);
}
#endregion
#region Constructors
public BlockCommandSupervisor(Project project)
{
// Make sure we have a sane state.
if (project == null)
{
throw new ArgumentNullException("project");
}
// Save the member variables so we can use them to perform actions.
Project = project;
// Set up our internal maximums.
MaximumUndoCommands = 101;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
namespace AuthorIntrusion.Common.Blocks
{
/// <summary>
/// Defines the unique key to identify a block.
/// </summary>
public struct BlockKey: IEquatable<BlockKey>
{
#region Properties
/// <summary>
/// Gets the block ID.
/// </summary>
public uint Id
{
get { return id; }
}
#endregion
#region Methods
public bool Equals(BlockKey other)
{
return id == other.id;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
return obj is BlockKey && Equals((BlockKey) obj);
}
public override int GetHashCode()
{
return (int) id;
}
/// <summary>
/// Gets the next BlockKey. This is a universal ID across the system, but the
/// ID will not be used outside of that process.
/// </summary>
/// <returns></returns>
public static BlockKey GetNext()
{
unchecked
{
var key = new BlockKey(nextId++);
return key;
}
}
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
return string.Format("BlockKey({0})", id.ToString("X8"));
}
#endregion
#region Operators
public static bool operator ==(BlockKey left,
BlockKey right)
{
return left.Equals(right);
}
public static bool operator !=(BlockKey left,
BlockKey right)
{
return !left.Equals(right);
}
#endregion
#region Constructors
/// <summary>
/// Initializes the <see cref="BlockKey"/> struct.
/// </summary>
static BlockKey()
{
nextId = 1;
}
/// <summary>
/// Initializes a new instance of the <see cref="BlockKey"/> struct.
/// </summary>
/// <param name="id">The id.</param>
public BlockKey(uint id)
: this()
{
this.id = id;
}
#endregion
#region Fields
private readonly uint id;
private static uint nextId;
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
using MfGames.Commands;
namespace AuthorIntrusion.Common.Commands
{
/// <summary>
/// A command to change the type of block to a given type.
/// </summary>
public class ChangeBlockTypeCommand: MultipleBlockKeyCommand
{
#region Properties
public BlockType BlockType { get; private set; }
#endregion
#region Methods
protected override void Do(
BlockCommandContext context,
Block block)
{
// We need to keep track of the previous block type so we can change
// it back with Undo.
previousBlockType = block.BlockType;
// Set the block type.
block.SetBlockType(BlockType);
// Save the position from this command.
if (UpdateTextPosition.HasFlag(DoTypes.Do))
{
context.Position = new BlockPosition(BlockKey, 0);
}
}
protected override void Undo(
BlockCommandContext context,
Block block)
{
// Revert the block type.
block.SetBlockType(previousBlockType);
}
#endregion
#region Constructors
public ChangeBlockTypeCommand(
BlockKey blockKey,
BlockType blockType)
: base(blockKey)
{
BlockType = blockType;
}
#endregion
#region Fields
private BlockType previousBlockType;
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using System.Linq;
using AuthorIntrusion.Plugins.Spelling.Common;
using NHunspell;
using IStringList = System.Collections.Generic.IList<string>;
namespace AuthorIntrusion.Plugins.Spelling.NHunspell
{
/// <summary>
/// Controller that uses the NHunspell to handle spell-checking.
/// </summary>
public class SpellEngineSpellingProjectPlugin: CommonSpellingProjectPlugin
{
#region Properties
private HunspellSpellingPlugin Plugin { get; set; }
#endregion
#region Methods
public override IEnumerable<SpellingSuggestion> GetSuggestions(string word)
{
// Get the checker and then get the suggestions.
SpellFactory checker = Plugin.SpellEngine["en_US"];
IStringList suggestedWords = checker.Suggest(word);
// Wrap the list in suggestions.
var suggestions = new List<SpellingSuggestion>(suggestedWords.Count);
suggestions.AddRange(
suggestedWords.Select(
suggestedWord => new SpellingSuggestion(suggestedWord)));
// Return the resulting suggestions.
return suggestions;
}
public override WordCorrectness IsCorrect(string word)
{
// Check the spelling.
SpellFactory checker = Plugin.SpellEngine["en_US"];
bool isCorrect = checker.Spell(word);
return isCorrect
? WordCorrectness.Correct
: WordCorrectness.Incorrect;
}
#endregion
#region Constructors
public SpellEngineSpellingProjectPlugin(HunspellSpellingPlugin plugin)
{
Plugin = plugin;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Xml;
using AuthorIntrusion.Common.Blocks;
namespace AuthorIntrusion.Common.Persistence.Filesystem
{
public class FilesystemPersistenceStructureReader:
PersistenceReaderWriterBase<FilesystemPersistenceSettings>
{
#region Methods
/// <summary>
/// Reads the structure file, either from the project reader or the Structure
/// file depending on the persistence settings.
/// </summary>
/// <param name="projectReader">The project reader.</param>
public void Read(XmlReader projectReader)
{
// Figure out which reader we'll be using.
bool createdReader;
XmlReader reader = GetXmlReader(
projectReader, Settings.StructureFilename, out createdReader);
// Loop through the resulting file until we get to the end of the
// XML element we care about.
bool reachedStructure = reader.NamespaceURI == XmlConstants.ProjectNamespace
&& reader.LocalName == "structure";
BlockType lastBlockType = null;
while (reader.Read())
{
// Ignore anything outside of our namespace.
if (reader.NamespaceURI != XmlConstants.ProjectNamespace)
{
continue;
}
// Check to see if we're done reading.
if (reader.NodeType == XmlNodeType.EndElement)
{
switch (reader.LocalName)
{
case "structure":
return;
case "block-type":
lastBlockType = null;
break;
}
}
// For the rest of this loop, we only deal with begin elements.
if (reader.NodeType != XmlNodeType.Element)
{
continue;
}
// If we haven't reached the Structure, we just cycle through the XML.
if (!reachedStructure)
{
// Flip the flag if we are starting to read the Structure.
if (reader.NamespaceURI == XmlConstants.ProjectNamespace
&& reader.LocalName == "structure")
{
reachedStructure = true;
}
// Continue on since we're done with this if clause.
continue;
}
// We process the remaining elements based on their local name.
switch (reader.LocalName)
{
case "block-type":
lastBlockType = new BlockType(Project.BlockTypes);
break;
case "name":
string nameValue = reader.ReadString();
if (lastBlockType != null)
{
lastBlockType.Name = nameValue;
Project.BlockTypes.BlockTypes[nameValue] = lastBlockType;
}
break;
case "is-structural":
bool structuralValue = Convert.ToBoolean(reader.ReadString());
lastBlockType.IsStructural = structuralValue;
break;
}
}
// If we created the reader, close it.
if (createdReader)
{
reader.Close();
reader.Dispose();
}
}
#endregion
#region Constructors
public FilesystemPersistenceStructureReader(
PersistenceReaderWriterBase<FilesystemPersistenceSettings> baseReader)
: base(baseReader)
{
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Mo<NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using AuthorIntrusion.Common.Plugins;
namespace AuthorIntrusion.Common.Blocks
{
/// <summary>
/// Represents a controller-influenced section of the text inside a block.
/// A text span has both range information on a block and associated data
/// for a single controller.
///
/// Like many of the range classes, a text span is read-only and has no public
/// setters.
/// </summary>
public class TextSpan: IEquatable<TextSpan>
{
#region Properties
public ITextControllerProjectPlugin Controller { get; set; }
public object Data { get; private set; }
public int Length
{
get { return StopTextIndex - StartTextIndex; }
}
public int StartTextIndex { get; set; }
public int StopTextIndex { get; set; }
#endregion
#region Methods
public bool Equals(TextSpan other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Equals(Controller, other.Controller) && Equals(Data, other.Data)
&& StartTextIndex == other.StartTextIndex
&& StopTextIndex == other.StopTextIndex;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((TextSpan) obj);
}
public override int GetHashCode()
{
unchecked
{
int hashCode = (Controller != null
? Controller.GetHashCode()
: 0);
hashCode = (hashCode * 397) ^ (Data != null
? Data.GetHashCode()
: 0);
hashCode = (hashCode * 397) ^ StartTextIndex;
hashCode = (hashCode * 397) ^ StopTextIndex;
return hashCode;
}
}
/// <summary>
/// Gets the text for the text span from the input line.
/// </summary>
/// <param name="input">The input string.</param>
/// <returns>The substring that represents the text.</returns>
public string GetText(string input)
{
string part = input.Substring(StartTextIndex, Length);
return part;
}
#endregion
#region Operators
public static bool operator ==(TextSpan left,
TextSpan right)
{
return Equals(left, right);
}
public static bool operator !=(TextSpan left,
TextSpan right)
{
return !Equals(left, right);
}
#endregion
#region Constructors
public TextSpan(
int startTextIndex,
int stopTextIndex,
ITextControllerProjectPlugin controller,
object data)
{
StartTextIndex = startTextIndex;
StopTextIndex = stopTextIndex;
Controller = controller;
Data = data;
}
public TextSpan()
{
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Commands;
using MfGames.Commands;
using MfGames.GtkExt.TextEditor.Models;
namespace AuthorIntrusion.Gui.GtkGui.Commands
{
public interface IWrappedCommand: IUndoableCommand<BlockCommandContext>
{
#region Methods
void PostDo(OperationContext context);
void PostUndo(OperationContext context);
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
using NUnit.Framework;
namespace AuthorIntrusion.Common.Tests
{
[TestFixture]
public class BlockOperationTests
{
#region Methods
[Test]
public void TestInitialState()
{
// Act
var project = new Project();
// Assert
ProjectBlockCollection blocks = project.Blocks;
Assert.AreEqual(1, blocks.Count);
Block block = blocks[0];
Assert.AreEqual(string.Empty, block.Text);
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Xml;
using AuthorIntrusion.Common.Blocks;
namespace AuthorIntrusion.Common.Persistence.Filesystem
{
/// <summary>
/// A XML-based Writer for the content part of a project, either as a separate
/// file or as part of the project file itself.
/// </summary>
public class FilesystemPersistenceContentWriter:
PersistenceReaderWriterBase<FilesystemPersistenceSettings>
{
#region Methods
/// <summary>
/// Writes the content file, to either the project Writer or the Structure
/// file depending on the persistence settings.
/// </summary>
/// <param name="projectWriter">The project Writer.</param>
public void Write(XmlWriter projectWriter)
{
// Figure out which Writer we'll be using.
bool createdWriter;
XmlWriter writer = GetXmlWriter(
projectWriter, Macros, Settings.ContentFilename, out createdWriter);
// Start by creating the initial element.
writer.WriteStartElement("content", ProjectNamespace);
writer.WriteElementString("version", "1");
// Go through the blocks in the project.
ProjectBlockCollection blocks = Project.Blocks;
foreach (Block block in blocks)
{
// Write the beginning of the block.
writer.WriteStartElement("block", ProjectNamespace);
// For this pass, we only include block elements that are
// user-entered. We'll do a second pass to include the processed
// data including TextSpans and parsing status later.
writer.WriteElementString("type", ProjectNamespace, block.BlockType.Name);
writer.WriteElementString("text", ProjectNamespace, block.Text);
writer.WriteElementString(
"text-hash", ProjectNamespace, block.Text.GetHashCode().ToString("X8"));
// Finish up the block.
writer.WriteEndElement();
}
// Finish up the blocks element.
writer.WriteEndElement();
// If we created the Writer, close it.
if (createdWriter)
{
writer.Dispose();
}
}
#endregion
#region Constructors
public FilesystemPersistenceContentWriter(
PersistenceReaderWriterBase<FilesystemPersistenceSettings> baseWriter)
: base(baseWriter)
{
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.IO;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
using AuthorIntrusion.Common.Persistence.Filesystem;
using AuthorIntrusion.Common.Plugins;
using AuthorIntrusion.Common.Projects;
using MfGames.HierarchicalPaths;
namespace AuthorIntrusion.Common.Persistence
{
/// <summary>
/// The project plugin to describe an export/save format for a project.
/// </summary>
public class FilesystemPersistenceProjectPlugin: IProjectPlugin
{
#region Properties
public string Key
{
get { return "Filesystem Persistence"; }
}
public Guid PluginId { get; private set; }
public Project Project { get; private set; }
public static HierarchicalPath RootSettingsKey { get; private set; }
/// <summary>
/// Gets the settings associated with this plugin.
/// </summary>
public FilesystemPersistenceSettings Settings
{
get
{
HierarchicalPath key = SettingsKey;
var settings = Project.Settings.Get<FilesystemPersistenceSettings>(key);
return settings;
}
}
public HierarchicalPath SettingsKey { get; private set; }
#endregion
#region Methods
/// <summary>
/// Writes out the project file to a given directory.
/// </summary>
/// <param name="directory">The directory to save the file.</param>
public void Save(DirectoryInfo directory)
{
// Set up the project macros we'll be expanding.
ProjectMacros macros = SetupMacros(directory);
// Validate the state.
string projectFilename = macros.ExpandMacros("{ProjectFilename}");
if (string.IsNullOrWhiteSpace(projectFilename))
{
throw new InvalidOperationException(
"Project filename is not defined in Settings property.");
}
// We need a write lock on the blocks to avoid changes. This also prevents
// any background tasks from modifying the blocks during the save process.
ProjectBlockCollection blocks = Project.Blocks;
using (blocks.AcquireLock(RequestLock.Write))
{
// Create a new project writer and write out the results.
var projectWriter = new FilesystemPersistenceProjectWriter(
Project, Settings, macros);
var projectFile = new FileInfo(projectFilename);
projectWriter.Write(projectFile);
}
}
/// <summary>
/// Setups the macros.
/// </summary>
/// <param name="directory">The directory.</param>
/// <returns>The populated macros object.</returns>
private ProjectMacros SetupMacros(DirectoryInfo directory)
{
// Create the macros and substitute the values.
var macros = new ProjectMacros();
macros.Substitutions["ProjectDirectory"] = directory.FullName;
macros.Substitutions["ProjectFilename"] = Settings.ProjectFilename;
macros.Substitutions["DataDirectory"] = Settings.DataDirectory;
macros.Substitutions["InternalContentDirectory"] =
Settings.InternalContentDirectory;
macros.Substitutions["ExternalSettingsDirectory"] =
Settings.ExternalSettingsDirectory;
// Return the resulting macros.
return macros;
}
#endregion
#region Constructors
static FilesystemPersistenceProjectPlugin()
{
RootSettingsKey = new HierarchicalPath("/Persistence/Filesystem/");
}
public FilesystemPersistenceProjectPlugin(Project project)
{
Project = project;
PluginId = Guid.NewGuid();
SettingsKey = RootSettingsKey;
// TODO new HierarchicalPath(PluginId.ToString(),RootSettingsKey);
}
#endregion
#region Fields
private const string ProjectNamespace = XmlConstants.ProjectNamespace;
#endregion
}
}
<file_sep>// Copyright 2012-2013 Mo<NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Plugins;
namespace AuthorIntrusion.Plugins.Spelling.LocalWords
{
public class LocalWordsPlugin: IProjectPluginProviderPlugin
{
#region Properties
public bool AllowMultiple
{
get { return false; }
}
public string Key
{
get { return "Local Words"; }
}
#endregion
#region Methods
public IProjectPlugin GetProjectPlugin(Project project)
{
return new LocalWordsProjectPlugin(project);
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Xml;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Plugins;
using MfGames.HierarchicalPaths;
namespace AuthorIntrusion.Common.Persistence.Filesystem
{
/// <summary>
/// A XML-based reader for the content data part of a project, either as a
/// separate file or as part of the project file itself.
/// </summary>
public class FilesystemPersistenceContentDataReader:
PersistenceReaderWriterBase<FilesystemPersistenceSettings>
{
#region Methods
/// <summary>
/// Reads the content file, either from the project reader or the Structure
/// file depending on the persistence settings.
/// </summary>
/// <param name="projectReader">The project reader.</param>
public void Read(XmlReader projectReader)
{
// Figure out which reader we'll be using.
bool createdReader;
XmlReader reader = GetXmlReader(
projectReader, Settings.ContentDataFilename, out createdReader);
// Loop through the resulting file until we get to the end of the
// XML element we care about.
ProjectBlockCollection blocks = Project.Blocks;
bool reachedData = reader.NamespaceURI == XmlConstants.ProjectNamespace
&& reader.LocalName == "content-data";
int blockIndex = 0;
int startTextIndex = 0;
int stopTextIndex = 0;
ITextControllerProjectPlugin plugin = null;
object pluginData = null;
bool inProject = false;
bool inBlocks = false;
while (reader.Read())
{
// Ignore anything outside of our namespace.
if (reader.NamespaceURI != XmlConstants.ProjectNamespace)
{
continue;
}
// Check to see if we're done reading.
if (reader.NodeType == XmlNodeType.EndElement)
{
switch (reader.LocalName)
{
case "content-data":
return;
case "text-span":
// Construct a text span from the gathered properties.
var textSpan = new TextSpan(
startTextIndex, stopTextIndex, plugin, pluginData);
blocks[blockIndex].TextSpans.Add(textSpan);
// Clear out the data to catch any additional errors.
plugin = null;
pluginData = null;
break;
case "block-data":
inBlocks = false;
break;
case "project":
inProject = false;
break;
}
}
// For the rest of this loop, we only deal with begin elements.
if (reader.NodeType != XmlNodeType.Element)
{
continue;
}
// If we haven't reached the Structure, we just cycle through the XML.
if (!reachedData)
{
// Flip the flag if we are starting to read the Structure.
if (reader.NamespaceURI == XmlConstants.ProjectNamespace
&& reader.LocalName == "content-data")
{
reachedData = true;
}
// Continue on since we're done with this if clause.
continue;
}
// We process the remaining elements based on their local name.
switch (reader.LocalName)
{
case "block-data":
inBlocks = true;
break;
case "project":
inProject = true;
break;
case "analyzer":
// Grab the analyzer name and find the associated plugin.
string key = reader.ReadInnerXml();
if (Project.Plugins.Contains(key))
{
var analyzer = Project.Plugins[key] as IBlockAnalyzerProjectPlugin;
if (analyzer != null)
{
blocks[blockIndex].AddAnalysis(analyzer);
}
}
break;
case "block-key":
// Grab the information to identify the block. We can't use
// block key directly so we have an index into the original
// block data and a hash of the text.
blockIndex = Convert.ToInt32(reader["block-index"]);
int textHash = Convert.ToInt32(reader["text-hash"], 16);
// Figure out if we are asking for an index that doesn't exist
// or if the hash doesn't work. If they don't, then stop
// processing entirely.
if (blockIndex >= blocks.Count
|| blocks[blockIndex].Text.GetHashCode() != textHash)
{
return;
}
break;
case "property":
{
var path = new HierarchicalPath(reader["path"]);
string value = reader.ReadString();
if (inBlocks)
{
blocks[blockIndex].Properties[path] = value;
}
if (inProject)
{
Project.Properties[path] = value;
}
break;
}
case "index":
startTextIndex = Convert.ToInt32(reader["start"]);
stopTextIndex = Convert.ToInt32(reader["stop"]);
break;
case "plugin":
string projectKey = reader.ReadString();
plugin = (ITextControllerProjectPlugin) Project.Plugins[projectKey];
break;
}
}
// If we created the reader, close it.
if (createdReader)
{
reader.Close();
reader.Dispose();
}
}
#endregion
#region Constructors
public FilesystemPersistenceContentDataReader(
PersistenceReaderWriterBase<FilesystemPersistenceSettings> baseReader)
: base(baseReader)
{
}
#endregion
}
}
<file_sep>Reworking underlying text editor to make a smoother writing experience.
# Changes
- Updated changes to use MfGames.Commands.TextEditing structures. +Changed
- Changed integer indexes to LinePosition and CharacterPosition.
# Dependencies
- MfGames.Commands 0.2.0
- MfGames.GtkExt.TextEditor 0.4.0<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using MfGames.GtkExt.TextEditor.Models.Buffers;
namespace AuthorIntrusion.Gui.GtkGui
{
public class ProjectLineIndicator: ILineIndicator
{
#region Properties
public string LineIndicatorStyle { get; private set; }
#endregion
#region Constructors
public ProjectLineIndicator(string lineIndicatorStyle)
{
LineIndicatorStyle = lineIndicatorStyle;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Text.RegularExpressions;
using MfGames;
namespace AuthorIntrusion.Dedications
{
/// <summary>
/// Contains the information about a single dedication to the program.
/// </summary>
public class Dedication
{
#region Properties
/// <summary>
/// Gets or sets the author the version is dedicated to.
/// </summary>
public string Author { get; set; }
/// <summary>
/// Gets or sets the person who wrote the dedication.
/// </summary>
public string Dedicator { get; set; }
/// <summary>
/// Gets or sets the HTML dedication.
/// </summary>
public string Html { get; set; }
public string[] Lines
{
get
{
string text = Html;
text = Regex.Replace(text, "(\\s+|<p>)+", " ").Trim();
string[] lines = Regex.Split(text, "\\s*</p>\\s*");
return lines;
}
}
/// <summary>
/// Gets or sets the version for the dedication.
/// </summary>
public ExtendedVersion Version { get; set; }
#endregion
#region Constructors
public Dedication()
{
Html = string.Empty;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using AuthorIntrusion.Common.Blocks;
using MfGames.Commands;
using MfGames.Commands.TextEditing;
namespace AuthorIntrusion.Common.Commands
{
/// <summary>
/// A command to delete text from a single block.
/// </summary>
public class DeleteTextCommand: BlockPositionCommand
{
#region Properties
public CharacterPosition End { get; set; }
#endregion
#region Methods
protected override void Do(
BlockCommandContext context,
Block block)
{
// Save the previous text so we can restore it.
previousText = block.Text;
originalPosition = context.Position;
// Figure out what the new text string would be.
startIndex = BlockPosition.TextIndex.GetCharacterIndex(
block.Text, End, WordSearchDirection.Left);
int endIndex = End.GetCharacterIndex(
block.Text, TextIndex, WordSearchDirection.Right);
int firstIndex = Math.Min(startIndex, endIndex);
int lastIndex = Math.Max(startIndex, endIndex);
string newText = block.Text.Remove(firstIndex, lastIndex - firstIndex);
// Set the new text into the block. This will fire various events to
// trigger the immediate and background processing.
block.SetText(newText);
// Set the position after the next text.
if (UpdateTextPosition.HasFlag(DoTypes.Do))
{
context.Position = new BlockPosition(BlockKey, startIndex);
}
}
protected override void Undo(
BlockCommandContext context,
Block block)
{
block.SetText(previousText);
if (UpdateTextPosition.HasFlag(DoTypes.Undo))
{
context.Position = originalPosition;
}
}
#endregion
#region Constructors
public DeleteTextCommand(
BlockPosition begin,
CharacterPosition end)
: base(begin)
{
End = end;
}
public DeleteTextCommand(SingleLineTextRange range)
: base(new TextPosition(range.LinePosition, range.BeginCharacterPosition))
{
// DREM ToTextPosition
End = range.EndCharacterPosition;
}
#endregion
#region Fields
private BlockPosition? originalPosition;
private string previousText;
private int startIndex;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Commands;
using MfGames.Commands.TextEditing;
using MfGames.GtkExt.TextEditor.Models;
namespace AuthorIntrusion.Gui.GtkGui.Commands
{
public class ProjectInsertLineCommand: ProjectCommandAdapter,
IInsertLineCommand<OperationContext>
{
#region Methods
public override void PostDo(OperationContext context)
{
lineBuffer.RaiseLineInserted(line.Index);
}
public override void PostUndo(OperationContext context)
{
lineBuffer.RaiseLineDeleted(line.Index);
}
#endregion
#region Constructors
public ProjectInsertLineCommand(
ProjectLineBuffer lineBuffer,
Project project,
LinePosition line)
: base(project)
{
// Save the line buffer for later.
this.lineBuffer = lineBuffer;
this.line = line;
// Create the project command wrapper.
var block = new Block(project.Blocks);
var command = new InsertIndexedBlockCommand(line.Index, block);
// Set the command into the adapter.
Command = command;
}
#endregion
#region Fields
private readonly LinePosition line;
private readonly ProjectLineBuffer lineBuffer;
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Commands;
using AuthorIntrusion.Common.Plugins;
using AuthorIntrusion.Common.Projects;
namespace AuthorIntrusion.Common
{
/// <summary>
/// A project encapsulates all of the text, settings, and organization of a
/// written document (novel, short story).
/// </summary>
public class Project: IPropertiesContainer
{
#region Properties
/// <summary>
/// Gets the block type Supervisor associated with this project.
/// </summary>
public BlockTypeSupervisor BlockTypes { get; private set; }
/// <summary>
/// Contains all the ordered blocks inside the project.
/// </summary>
public ProjectBlockCollection Blocks { get; private set; }
/// <summary>
/// Gets the commands supervisor for handling commands, undo, and redo.
/// </summary>
public BlockCommandSupervisor Commands { get; private set; }
/// <summary>
/// Gets the macros associated with the project.
/// </summary>
public ProjectMacros Macros { get; private set; }
/// <summary>
/// Gets the plugin supervisor associated with the project.
/// </summary>
public PluginSupervisor Plugins { get; private set; }
/// <summary>
/// Gets the current state of the processing inside the project.
/// </summary>
public ProjectProcessingState ProcessingState { get; private set; }
/// <summary>
/// Gets the properties associated with the block.
/// </summary>
public PropertiesDictionary Properties { get; private set; }
/// <summary>
/// Gets the settings associated with this project.
/// </summary>
public ProjectSettings Settings { get; private set; }
#endregion
#region Methods
/// <summary>
/// Updates the current processing state for the project.
/// </summary>
/// <param name="processingState">New processing state for the project.</param>
public void SetProcessingState(ProjectProcessingState processingState)
{
// If we are the same, we don't do anything.
if (processingState == ProcessingState)
{
return;
}
// Update the internal state so when we call the update method
// on the various supervisors, they'll be able to make the
// appropriate updates.
ProcessingState = processingState;
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Project"/> class.
/// </summary>
public Project(
ProjectProcessingState initialProcessingState =
ProjectProcessingState.Interactive)
{
// Set up the initial states.
ProcessingState = initialProcessingState;
// We need the settings set up first since it may contribute
// to the loading of other components of the project.
Settings = new ProjectSettings();
Properties = new PropertiesDictionary();
BlockTypes = new BlockTypeSupervisor(this);
Blocks = new ProjectBlockCollection(this);
Commands = new BlockCommandSupervisor(this);
Plugins = new PluginSupervisor(this);
Macros = new ProjectMacros();
}
#endregion
}
}
<file_sep># Author Intrusion
Author Intrusion is an integrated writing environment (IWE) inspired by Visual Studio.<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using System.Linq;
using AuthorIntrusion.Common.Plugins;
namespace AuthorIntrusion.Common.Blocks
{
/// <summary>
/// A specialized collection for TextSpans.
/// </summary>
public class TextSpanCollection: List<TextSpan>
{
#region Methods
/// <summary>
/// Returns true if there is text span that contains the given index.
/// </summary>
/// <param name="textIndex"></param>
/// <returns></returns>
public bool Contains(int textIndex)
{
// If we have any text span in range, then return true. Otherwise,
// return false to indicate nothing contains this range.
return
this.Any(
textSpan =>
textIndex >= textSpan.StartTextIndex && textIndex < textSpan.StopTextIndex);
}
/// <summary>
/// Retrieves all the TextSpans at a given text position.
/// </summary>
/// <param name="textIndex"></param>
/// <returns></returns>
public IEnumerable<TextSpan> GetAll(int textIndex)
{
return
this.Where(
textSpan =>
textIndex >= textSpan.StartTextIndex && textIndex < textSpan.StopTextIndex)
.ToList();
}
/// <summary>
/// Removes all the text spans of a given controller.
/// </summary>
/// <param name="controller">The controller to remove the spans for.</param>
public void Remove(IProjectPlugin controller)
{
var removeSpans = new HashSet<TextSpan>();
foreach (TextSpan textSpan in
this.Where(textSpan => textSpan.Controller == controller))
{
removeSpans.Add(textSpan);
}
foreach (TextSpan textSpan in removeSpans)
{
Remove(textSpan);
}
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
namespace AuthorIntrusion.Common.Plugins
{
/// <summary>
/// Defines the signature for a controller that integrates with other plugins
/// such as spelling.
/// </summary>
public interface IFrameworkProjectPlugin: IProjectPlugin
{
#region Methods
/// <summary>
/// Called when a new plugin controller is enabled for a project.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="controller">The controller.</param>
void HandleAddedController(
Project project,
IProjectPlugin controller);
/// <summary>
/// Called when a plugin controller is removed from a project.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="controller">The controller.</param>
void HandleRemovedController(
Project project,
IProjectPlugin controller);
/// <summary>
/// Initializes the plugin framework after it is added to the system. This will
/// always be called after the plugin is added.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="controllers">The controllers already enabled in the project. This list will not include the current controller.</param>
void InitializePluginFramework(
Project project,
IEnumerable<IProjectPlugin> controllers);
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Plugins;
namespace AuthorIntrusion.Plugins.Spelling
{
/// <summary>
/// Primary plugin for the entire spelling (spell-checking) framework. This
/// base plugin is used to register and coordinate other spelling plugins.
/// </summary>
public class SpellingFrameworkPlugin: IProjectPluginProviderPlugin
{
#region Properties
public bool AllowMultiple
{
get { return false; }
}
public string Key
{
get { return "Spelling Framework"; }
}
#endregion
#region Methods
public IProjectPlugin GetProjectPlugin(Project project)
{
return new SpellingFrameworkProjectPlugin();
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Mo<NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Plugins;
namespace AuthorIntrusion.Plugins.ImmediateCorrection
{
/// <summary>
/// Implements an immediate editor that checks for inline corrections while the
/// user is typing. This establishes the basic framework for other plugins to
/// provide the corrections.
/// </summary>
public class ImmediateCorrectionPlugin: IProjectPluginProviderPlugin
{
#region Properties
public bool AllowMultiple
{
get { return false; }
}
public string Key
{
get { return "Immediate Correction"; }
}
#endregion
#region Methods
public IProjectPlugin GetProjectPlugin(Project project)
{
var controller = new ImmediateCorrectionProjectPlugin(this, project);
return controller;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Commands;
using MfGames.Commands.TextEditing;
using MfGames.GtkExt.TextEditor.Models;
namespace AuthorIntrusion.Gui.GtkGui.Commands
{
public class ProjectInsertTextCommand: ProjectCommandAdapter,
IInsertTextCommand<OperationContext>
{
#region Constructors
public ProjectInsertTextCommand(
Project project,
TextPosition textPosition,
string text)
: base(project)
{
// Create the project command wrapper.
var command = new InsertTextCommand(textPosition, text);
// Set the command into the adapter.
Command = command;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
using MfGames.Commands;
namespace AuthorIntrusion.Common.Commands
{
public abstract class CompositeBlockPositionCommand:
CompositeCommand<BlockCommandContext>
{
#region Properties
public BlockKey BlockKey
{
get { return BlockPosition.BlockKey; }
}
public BlockPosition BlockPosition { get; set; }
#endregion
#region Constructors
protected CompositeBlockPositionCommand(
BlockPosition position,
bool isUndoable = true)
: base(isUndoable, false)
{
BlockPosition = position;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Mo<NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
namespace AuthorIntrusion.Common.Commands
{
public class ReplaceTextCommand: CompositeBlockPositionCommand
{
#region Properties
public int Length { get; set; }
public string Text { get; private set; }
#endregion
#region Constructors
public ReplaceTextCommand(
BlockPosition position,
int length,
string text)
: base(position, true)
{
// Save the text for the changes.
Length = length;
Text = text;
// Create the commands in this command.
var deleteCommand = new DeleteTextCommand(
position, (int) position.TextIndex + Length);
var insertCommand = new InsertTextCommand(position, Text);
Commands.Add(deleteCommand);
Commands.Add(insertCommand);
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using Antlr4.StringTemplate;
namespace AuthorIntrusion.Common.Projects
{
/// <summary>
/// Defines the macro storage and expansion class. This handles the various
/// macro variables
/// </summary>
public class ProjectMacros
{
#region Properties
/// <summary>
/// Gets the macros and their values.
/// </summary>
public Dictionary<string, string> Substitutions { get; private set; }
#endregion
#region Methods
/// <summary>
/// Expands the macros in the given string using the variables stored inside
/// this object. The resulting string will have the macros expanded.
/// </summary>
/// <param name="input">The input string.</param>
/// <returns>The output string with macros expanded.</returns>
public string ExpandMacros(string input)
{
// If we have a null, then just return a null.
if (string.IsNullOrWhiteSpace(input))
{
return input;
}
// We have to repeatedly run through the macros since we have macros
// that expand into other macros.
string results = input;
while (results.IndexOf('{') >= 0)
{
// Create a template with all of the variables inside it.
var template = new Template(results, '{', '}');
foreach (KeyValuePair<string, string> macro in Substitutions)
{
template.Add(macro.Key, macro.Value);
}
// Render out the template to the results.
results = template.Render();
}
// Return the resulting string.
return results;
}
#endregion
#region Constructors
public ProjectMacros()
{
Substitutions = new Dictionary<string, string>();
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
namespace AuthorIntrusion.Plugins.Counter
{
/// <summary>
/// A static class that implements a basic word counter. This is intended to
/// duplicate the word counting logic of Microsoft Words 2010.
/// </summary>
public static class WordCounter
{
#region Methods
/// <summary>
/// Counts the words in a text and returns the various counts.
/// </summary>
/// <param name="text">The text to measure.</param>
/// <param name="wordCount">The word count.</param>
/// <param name="characterCount">The character count.</param>
/// <param name="nonWhitespaceCount">The non whitespace count.</param>
public static void CountWords(
string text,
out int wordCount,
out int characterCount,
out int nonWhitespaceCount)
{
// Initialize the variables.
wordCount = 0;
characterCount = 0;
nonWhitespaceCount = 0;
// Go through the characters in the string.
bool lastWasWhitespace = true;
foreach (char c in text)
{
// Count the number of characters in the string.
characterCount++;
// If we are whitespace, then we set a flag to identify the beginning
// of the next word.
if (char.IsWhiteSpace(c))
{
lastWasWhitespace = true;
}
else
{
// This is a non-whitespace character.
nonWhitespaceCount++;
// If the last character was a whitespace, then we bump up the
// words.
if (lastWasWhitespace)
{
wordCount++;
}
lastWasWhitespace = false;
}
}
}
/// <summary>
/// Counts the words in the given text.
/// </summary>
/// <param name="text">The text.</param>
/// <returns>The number of words in the string.</returns>
public static int CountWords(string text)
{
int wordCount;
int characterCount;
int nonWhitespaceCount;
CountWords(text, out wordCount, out characterCount, out nonWhitespaceCount);
return wordCount;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.IO;
using System.Xml.Serialization;
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Commands;
using AuthorIntrusion.Common.Plugins;
using NUnit.Framework;
namespace AuthorIntrusion.Plugins.ImmediateCorrection.Tests
{
[TestFixture]
public class ImmedicateCorrectionEditorTests
{
#region Methods
[Test]
public void ActivatePlugin()
{
// Act
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
ImmediateCorrectionProjectPlugin projectPlugin;
BlockCommandContext context;
SetupCorrectionPlugin(
out context, out blocks, out commands, out projectPlugin);
// Assert
Project project = blocks.Project;
Assert.AreEqual(1, project.Plugins.Controllers.Count);
}
[Test]
public void SerializeDeserializeSettings()
{
// Arrange
var settings = new ImmediateCorrectionSettings();
settings.Substitutions.Add(
new RegisteredSubstitution("a", "b", SubstitutionOptions.WholeWord));
var serializer = new XmlSerializer(typeof (ImmediateCorrectionSettings));
var memoryStream = new MemoryStream();
// Act
serializer.Serialize(memoryStream, settings);
byte[] buffer = memoryStream.GetBuffer();
var newMemoryStream = new MemoryStream(buffer);
var newSettings =
(ImmediateCorrectionSettings) serializer.Deserialize(newMemoryStream);
// Assert
Assert.AreEqual(1, newSettings.Substitutions.Count);
Assert.AreEqual("a", newSettings.Substitutions[0].Search);
Assert.AreEqual("b", newSettings.Substitutions[0].Replacement);
Assert.AreEqual(
SubstitutionOptions.WholeWord, newSettings.Substitutions[0].Options);
}
[Test]
public void SimpleLargerWordSubstitution()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
ImmediateCorrectionProjectPlugin projectPlugin;
BlockCommandContext context;
SetupCorrectionPlugin(
out context, out blocks, out commands, out projectPlugin);
// Act
projectPlugin.AddSubstitution(
"abbr", "abbreviation", SubstitutionOptions.WholeWord);
commands.InsertText(blocks[0], 0, "abbr ");
// Assert
Assert.AreEqual("abbreviation ", blocks[0].Text);
Assert.AreEqual(
new BlockPosition(blocks[0], "abbreviation ".Length), commands.LastPosition);
}
[Test]
public void SimpleWordSubstitution()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
ImmediateCorrectionProjectPlugin projectPlugin;
BlockCommandContext context;
SetupCorrectionPlugin(
out context, out blocks, out commands, out projectPlugin);
// Act
projectPlugin.AddSubstitution("teh", "the", SubstitutionOptions.WholeWord);
commands.InsertText(blocks[0], 0, "teh ");
// Assert
Assert.AreEqual("the ", blocks[0].Text);
Assert.IsFalse(commands.CanRedo);
Assert.IsTrue(commands.CanUndo);
Assert.AreEqual(new BlockPosition(blocks[0], 4), commands.LastPosition);
}
[Test]
public void SimpleWordSubstitutionUndo()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
ImmediateCorrectionProjectPlugin projectPlugin;
BlockCommandContext context;
SetupCorrectionPlugin(
out context, out blocks, out commands, out projectPlugin);
projectPlugin.AddSubstitution("teh", "the", SubstitutionOptions.WholeWord);
commands.InsertText(blocks[0], 0, "teh ");
// Act
commands.Undo(context);
// Assert
Assert.AreEqual("teh ", blocks[0].Text);
Assert.IsTrue(commands.CanRedo);
Assert.IsTrue(commands.CanUndo);
Assert.AreEqual(new BlockPosition(blocks[0], 4), commands.LastPosition);
}
[Test]
public void SimpleWordSubstitutionUndoRedo()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
ImmediateCorrectionProjectPlugin projectPlugin;
BlockCommandContext context;
SetupCorrectionPlugin(
out context, out blocks, out commands, out projectPlugin);
projectPlugin.AddSubstitution("teh", "the", SubstitutionOptions.WholeWord);
commands.InsertText(blocks[0], 0, "teh ");
commands.Undo(context);
// Act
commands.Redo(context);
// Assert
Assert.AreEqual("the ", blocks[0].Text);
Assert.IsFalse(commands.CanRedo);
Assert.IsTrue(commands.CanUndo);
Assert.AreEqual(new BlockPosition(blocks[0], 4), commands.LastPosition);
}
[Test]
public void SimpleWordSubstitutionUndoUndo()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
ImmediateCorrectionProjectPlugin projectPlugin;
BlockCommandContext context;
SetupCorrectionPlugin(
out context, out blocks, out commands, out projectPlugin);
projectPlugin.AddSubstitution("teh", "the", SubstitutionOptions.WholeWord);
commands.InsertText(blocks[0], 0, "teh ");
commands.Undo(context);
// Act
commands.Undo(context);
// Assert
Assert.AreEqual("", blocks[0].Text);
Assert.IsTrue(commands.CanRedo);
Assert.IsFalse(commands.CanUndo);
Assert.AreEqual(new BlockPosition(blocks[0], 0), commands.LastPosition);
}
[Test]
public void SimpleWordSubstitutionUndoUndoRedo()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
ImmediateCorrectionProjectPlugin projectPlugin;
BlockCommandContext context;
SetupCorrectionPlugin(
out context, out blocks, out commands, out projectPlugin);
projectPlugin.AddSubstitution("teh", "the", SubstitutionOptions.WholeWord);
commands.InsertText(blocks[0], 0, "teh ");
commands.Undo(context);
commands.Undo(context);
// Act
commands.Redo(context);
// Assert
Assert.AreEqual("teh ", blocks[0].Text);
Assert.IsTrue(commands.CanRedo);
Assert.IsTrue(commands.CanUndo);
Assert.AreEqual(new BlockPosition(blocks[0], 4), commands.LastPosition);
}
[Test]
public void SimpleWordSubstitutionUndoUndoRedoRedo()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
ImmediateCorrectionProjectPlugin projectPlugin;
BlockCommandContext context;
SetupCorrectionPlugin(
out context, out blocks, out commands, out projectPlugin);
projectPlugin.AddSubstitution("teh", "the", SubstitutionOptions.WholeWord);
commands.InsertText(blocks[0], 0, "teh ");
commands.Undo(context);
commands.Undo(context);
commands.Redo(context);
// Act
commands.Redo(context);
// Assert
Assert.AreEqual("the ", blocks[0].Text);
Assert.IsFalse(commands.CanRedo);
Assert.IsTrue(commands.CanUndo);
Assert.AreEqual(new BlockPosition(blocks[0], 4), commands.LastPosition);
}
[Test]
public void TooShortExactLenthWholeWordTest()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
ImmediateCorrectionProjectPlugin projectPlugin;
BlockCommandContext context;
SetupCorrectionPlugin(
out context, out blocks, out commands, out projectPlugin);
projectPlugin.AddSubstitution("teh", "the", SubstitutionOptions.WholeWord);
// Act
commands.InsertText(blocks[0], 0, "teg.");
// Assert
Assert.AreEqual("teg.", blocks[0].Text);
Assert.IsFalse(commands.CanRedo);
Assert.IsTrue(commands.CanUndo);
Assert.AreEqual(new BlockPosition(blocks[0], 4), commands.LastPosition);
}
[Test]
public void TooShortExactLenthWholeWordTest2()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
ImmediateCorrectionProjectPlugin projectPlugin;
BlockCommandContext context;
SetupCorrectionPlugin(
out context, out blocks, out commands, out projectPlugin);
projectPlugin.AddSubstitution("teh", "the", SubstitutionOptions.WholeWord);
// Act
commands.InsertText(blocks[0], 0, "te.");
// Assert
Assert.AreEqual("te.", blocks[0].Text);
Assert.IsFalse(commands.CanRedo);
Assert.IsTrue(commands.CanUndo);
Assert.AreEqual(new BlockPosition(blocks[0], 3), commands.LastPosition);
}
[Test]
public void TooShortInlineTest()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
ImmediateCorrectionProjectPlugin projectPlugin;
BlockCommandContext context;
SetupCorrectionPlugin(
out context, out blocks, out commands, out projectPlugin);
projectPlugin.AddSubstitution("teh", "the", SubstitutionOptions.None);
// Act
commands.InsertText(blocks[0], 0, "t");
// Assert
Assert.AreEqual("t", blocks[0].Text);
Assert.IsFalse(commands.CanRedo);
Assert.IsTrue(commands.CanUndo);
Assert.AreEqual(new BlockPosition(blocks[0], 1), commands.LastPosition);
}
[Test]
public void TooShortWholeWordTest()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
ImmediateCorrectionProjectPlugin projectPlugin;
BlockCommandContext context;
SetupCorrectionPlugin(
out context, out blocks, out commands, out projectPlugin);
projectPlugin.AddSubstitution("teh", "the", SubstitutionOptions.WholeWord);
// Act
commands.InsertText(blocks[0], 0, "t.");
// Assert
Assert.AreEqual("t.", blocks[0].Text);
Assert.IsFalse(commands.CanRedo);
Assert.IsTrue(commands.CanUndo);
Assert.AreEqual(new BlockPosition(blocks[0], 2), commands.LastPosition);
}
/// <summary>
/// Configures the environment to load the plugin manager and verify we
/// have access to the ImmediateCorrectionPlugin.
/// </summary>
private void SetupCorrectionPlugin(
out BlockCommandContext context,
out ProjectBlockCollection blocks,
out BlockCommandSupervisor commands,
out ImmediateCorrectionProjectPlugin projectPlugin)
{
// Start getting us a simple plugin manager.
var plugin = new ImmediateCorrectionPlugin();
var pluginManager = new PluginManager(plugin);
PluginManager.Instance = pluginManager;
// Create a project and pull out the useful properties we'll use to
// make changes.
var project = new Project();
context = new BlockCommandContext(project);
blocks = project.Blocks;
commands = project.Commands;
// Load in the immediate correction editor.
if (!project.Plugins.Add("Immediate Correction"))
{
// We couldn't load it for some reason.
throw new ApplicationException("Cannot load immediate correction plugin");
}
// Pull out the controller for the correction and cast it (since we know
// what type it is).
ProjectPluginController pluginController = project.Plugins.Controllers[0];
projectPlugin =
(ImmediateCorrectionProjectPlugin) pluginController.ProjectPlugin;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using AuthorIntrusion.Plugins.Spelling.Common;
namespace AuthorIntrusion.Plugins.Spelling.NHunspell
{
public class DisabledSpellingProjectPlugin: CommonSpellingProjectPlugin
{
#region Methods
public override IEnumerable<SpellingSuggestion> GetSuggestions(string word)
{
// If the plugin is disabled, then don't do anything.
return new SpellingSuggestion[]
{
};
}
public override WordCorrectness IsCorrect(string word)
{
// Because we are disabled, we are always indeterminate.
return WordCorrectness.Indeterminate;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
namespace AuthorIntrusion.Plugins.ImmediateCorrection
{
/// <summary>
/// Identifies the options for immediate corrections and how they are handled.
/// </summary>
[Flags]
public enum SubstitutionOptions
{
/// <summary>
/// Indicates no special options are given.
/// </summary>
None = 0,
/// <summary>
/// Indicates that the substitution only applies to whole words.
/// </summary>
WholeWord = 1,
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Plugins;
namespace AuthorIntrusion.Plugins.Counter
{
/// <summary>
/// Plugin to implement an automatic word count plugin that keeps track of word
/// (and character) counting on a paragraph and structural level.
/// </summary>
public class WordCounterPlugin: IProjectPluginProviderPlugin
{
#region Properties
public bool AllowMultiple
{
get { return false; }
}
public string Key
{
get { return "Word Counter"; }
}
#endregion
#region Methods
public IProjectPlugin GetProjectPlugin(Project project)
{
return new WordCounterProjectPlugin();
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Mo<NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using NUnit.Framework;
namespace AuthorIntrusion.Plugins.Counter.Tests
{
[TestFixture]
public class WordCounterHelperTests
{
#region Methods
[Test]
public void CountBlankString()
{
// Arrange
int wordCount;
int characterCount;
int nonWhitespaceCount;
// Act
WordCounter.CountWords(
"", out wordCount, out characterCount, out nonWhitespaceCount);
// Assert
Assert.AreEqual(0, wordCount);
Assert.AreEqual(0, characterCount);
Assert.AreEqual(0, nonWhitespaceCount);
}
[Test]
public void CountSingleWord()
{
// Arrange
int wordCount;
int characterCount;
int nonWhitespaceCount;
// Act
WordCounter.CountWords(
"cheese", out wordCount, out characterCount, out nonWhitespaceCount);
// Assert
Assert.AreEqual(1, wordCount);
Assert.AreEqual(6, characterCount);
Assert.AreEqual(6, nonWhitespaceCount);
}
[Test]
public void CountSingleWordWithLeadingSpace()
{
// Arrange
int wordCount;
int characterCount;
int nonWhitespaceCount;
// Act
WordCounter.CountWords(
" cheese", out wordCount, out characterCount, out nonWhitespaceCount);
// Assert
Assert.AreEqual(1, wordCount);
Assert.AreEqual(8, characterCount);
Assert.AreEqual(6, nonWhitespaceCount);
}
[Test]
public void CountSingleWordWithTrailingSpace()
{
// Arrange
int wordCount;
int characterCount;
int nonWhitespaceCount;
// Act
WordCounter.CountWords(
"cheese ", out wordCount, out characterCount, out nonWhitespaceCount);
// Assert
Assert.AreEqual(1, wordCount);
Assert.AreEqual(8, characterCount);
Assert.AreEqual(6, nonWhitespaceCount);
}
[Test]
public void CountSplicedWords()
{
// Arrange
int wordCount;
int characterCount;
int nonWhitespaceCount;
// Act
WordCounter.CountWords(
"cheese-curds", out wordCount, out characterCount, out nonWhitespaceCount);
// Assert
Assert.AreEqual(1, wordCount);
Assert.AreEqual(12, characterCount);
Assert.AreEqual(12, nonWhitespaceCount);
}
[Test]
public void CountTwoWords()
{
// Arrange
int wordCount;
int characterCount;
int nonWhitespaceCount;
// Act
WordCounter.CountWords(
"cheese curds", out wordCount, out characterCount, out nonWhitespaceCount);
// Assert
Assert.AreEqual(2, wordCount);
Assert.AreEqual(12, characterCount);
Assert.AreEqual(11, nonWhitespaceCount);
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.IO;
using System.Runtime.CompilerServices;
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
using AuthorIntrusion.Common.Commands;
using AuthorIntrusion.Common.Persistence;
using AuthorIntrusion.Common.Plugins;
using AuthorIntrusion.Common.Projects;
using AuthorIntrusion.Common.Tests;
using AuthorIntrusion.Plugins.BlockStructure;
using AuthorIntrusion.Plugins.ImmediateBlockTypes;
using AuthorIntrusion.Plugins.ImmediateCorrection;
using AuthorIntrusion.Plugins.Spelling;
using AuthorIntrusion.Plugins.Spelling.LocalWords;
using AuthorIntrusion.Plugins.Spelling.NHunspell;
using MfGames.HierarchicalPaths;
using NUnit.Framework;
namespace AuthorIntrusion.Integration.Tests
{
[TestFixture]
public class PersistenceTests: CommonMultilineTests
{
#region Methods
[Test]
public void ActivatePlugin()
{
// Act
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
PluginSupervisor plugins;
FilesystemPersistenceProjectPlugin projectPlugin;
SetupPlugin(out blocks, out commands, out plugins, out projectPlugin);
// Assert
Assert.AreEqual(8, plugins.Controllers.Count);
}
[Test]
public void Write()
{
// Arrange: Cleanup any existing output file.
DirectoryInfo testDirectory = PrepareTestDirectory();
// Arrange: Set up the plugin.
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
PluginSupervisor plugins;
FilesystemPersistenceProjectPlugin projectPlugin;
SetupPlugin(out blocks, out commands, out plugins, out projectPlugin);
// Arrange: Create a project with some interesting data.
SetupComplexMultilineTest(blocks.Project, 10);
blocks.Project.BlockTypes.Add("Custom Type", false);
blocks[0].Properties[new HierarchicalPath("/Test")] = "Custom Property";
blocks[0].TextSpans.Add(new TextSpan(1, 3, null, null));
using (blocks[0].AcquireBlockLock(RequestLock.Write))
{
blocks[0].SetText("<NAME>");
}
plugins.WaitForBlockAnalzyers();
// Act
projectPlugin.Settings.SetIndividualDirectoryLayout();
projectPlugin.Save(testDirectory);
// Assert
string projectFilename = Path.Combine(
testDirectory.FullName, "Project.aiproj");
Assert.IsTrue(File.Exists(projectFilename));
}
[Test]
public void WriteRead()
{
// Arrange: Cleanup any existing output file.
DirectoryInfo testDirectory = PrepareTestDirectory();
// Arrange: Set up the plugin.
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
PluginSupervisor plugins;
FilesystemPersistenceProjectPlugin projectPlugin;
SetupPlugin(out blocks, out commands, out plugins, out projectPlugin);
PersistenceManager persistenceManager = PersistenceManager.Instance;
// Arrange: Create a project with some interesting data and write it out.
SetupComplexMultilineTest(blocks.Project, 10);
blocks.Project.BlockTypes.Add("Custom Type", false);
Block block = blocks[0];
block.Properties[new HierarchicalPath("/Test")] = "Custom Property";
block.TextSpans.Add(new TextSpan(1, 3, null, null));
using (block.AcquireBlockLock(RequestLock.Write))
{
block.SetText("<NAME>");
}
plugins.WaitForBlockAnalzyers();
projectPlugin.Settings.SetIndividualDirectoryLayout();
projectPlugin.Save(testDirectory);
// Act
var projectFile =
new FileInfo(Path.Combine(testDirectory.FullName, "Project.aiproj"));
Project project = persistenceManager.ReadProject(projectFile);
// Assert: Project
Assert.AreEqual(ProjectProcessingState.Interactive, project.ProcessingState);
// Assert: Block Types
block = project.Blocks[0];
BlockTypeSupervisor blockTypes = project.BlockTypes;
blocks = project.Blocks;
Assert.AreEqual(
8, project.Plugins.Controllers.Count, "Unexpected number of plugins.");
Assert.NotNull(blockTypes["Custom Type"]);
Assert.IsFalse(blockTypes["Custom Type"].IsStructural);
// Assert: Blocks
Assert.AreEqual(10, blocks.Count);
Assert.AreEqual(blockTypes.Chapter, block.BlockType);
Assert.AreEqual("<NAME>", block.Text);
Assert.AreEqual(blockTypes.Scene, blocks[1].BlockType);
Assert.AreEqual("Line 2", blocks[1].Text);
Assert.AreEqual(blockTypes.Epigraph, blocks[2].BlockType);
Assert.AreEqual("Line 3", blocks[2].Text);
Assert.AreEqual(blockTypes.EpigraphAttribution, blocks[3].BlockType);
Assert.AreEqual("Line 4", blocks[3].Text);
Assert.AreEqual(blockTypes.Paragraph, blocks[9].BlockType);
Assert.AreEqual("Line 10", blocks[9].Text);
// Assert: Verify content data.
Assert.AreEqual(1, block.Properties.Count);
Assert.AreEqual(
"Custom Property", block.Properties[new HierarchicalPath("/Test")]);
// Assert: Verify text spans.
Assert.AreEqual(4, block.TextSpans.Count);
Assert.AreEqual(1, block.TextSpans[0].StartTextIndex);
Assert.AreEqual(3, block.TextSpans[0].StopTextIndex);
Assert.IsNull(block.TextSpans[0].Controller);
Assert.IsNull(block.TextSpans[0].Data);
Assert.AreEqual(0, block.TextSpans[1].StartTextIndex);
Assert.AreEqual(5, block.TextSpans[1].StopTextIndex);
Assert.AreEqual(
project.Plugins["Spelling Framework"], block.TextSpans[1].Controller);
Assert.IsNull(block.TextSpans[1].Data);
}
/// <summary>
/// Prepares the test directory including removing any existing data
/// and creating the top-level.
/// </summary>
/// <param name="methodName">Name of the method.</param>
/// <returns>A DirectoryInfo object of the created directory.</returns>
private DirectoryInfo PrepareTestDirectory(
[CallerMemberName] string methodName = "Unknown")
{
// Figure out the directory name.
string pluginDirectory = Path.Combine(
"Unit Tests", GetType().Name, methodName);
// Clean it up if we have files already there.
if (Directory.Exists(pluginDirectory))
{
Directory.Delete(pluginDirectory, true);
}
// Create the root directory for the plugin.
var directory = new DirectoryInfo(pluginDirectory);
directory.Create();
// Return the directory so we can use it for paths.
return directory;
}
/// <summary>
/// Configures the environment to load the plugin manager and verify we
/// have access to our plugin and projectPlugin.
/// </summary>
private void SetupPlugin(
out ProjectBlockCollection blocks,
out BlockCommandSupervisor commands,
out PluginSupervisor plugins,
out FilesystemPersistenceProjectPlugin projectPlugin)
{
// Start getting us a simple plugin manager.
var persistencePlugin = new PersistenceFrameworkPlugin();
var filesystemPlugin = new FilesystemPersistencePlugin();
var spellingPlugin = new SpellingFrameworkPlugin();
var nhunspellPlugin = new HunspellSpellingPlugin();
var localWordsPlugin = new LocalWordsPlugin();
var immediateCorrectionPlugin = new ImmediateCorrectionPlugin();
var immediateBlockTypesPlugin = new ImmediateBlockTypesPlugin();
var blockStructurePlugin = new BlockStructurePlugin();
var pluginManager = new PluginManager(
persistencePlugin,
filesystemPlugin,
spellingPlugin,
nhunspellPlugin,
localWordsPlugin,
immediateCorrectionPlugin,
immediateBlockTypesPlugin,
blockStructurePlugin);
PluginManager.Instance = pluginManager;
PersistenceManager.Instance = new PersistenceManager(persistencePlugin);
// Create a project and pull out the useful properties we'll use to
// make changes.
var project = new Project();
blocks = project.Blocks;
commands = project.Commands;
plugins = project.Plugins;
// Load in the plugins we'll be using in these tests.
foreach (IPlugin plugin in pluginManager.Plugins)
{
plugins.Add(plugin.Key);
}
// Set up the local words lookup.
var localWordsProjectPlugin =
(LocalWordsProjectPlugin) plugins["Local Words"];
localWordsProjectPlugin.ReadSettings();
localWordsProjectPlugin.CaseInsensitiveDictionary.Add("teig");
localWordsProjectPlugin.CaseSensitiveDictionary.Add("Moonfire");
localWordsProjectPlugin.WriteSettings();
// Set up the immediate correction plugin.
var immediateCorrectionProjectPlugin =
(ImmediateCorrectionProjectPlugin) plugins["Immediate Correction"];
immediateCorrectionProjectPlugin.AddSubstitution(
"Grey", "Gray", SubstitutionOptions.WholeWord);
immediateCorrectionProjectPlugin.AddSubstitution(
"GWG", "Great Waryoni Garèo", SubstitutionOptions.None);
immediateCorrectionProjectPlugin.AddSubstitution(
"GWB", "Great Waryoni Bob", SubstitutionOptions.None);
// Set up the immediate block types.
var immediateBlockTypesProjectPlugin =
(ImmediateBlockTypesProjectPlugin) plugins["Immediate Block Types"];
foreach (BlockType blockType in project.BlockTypes.BlockTypes.Values)
{
string prefix = string.Format("{0}: ", blockType.Name);
immediateBlockTypesProjectPlugin.Settings.Replacements[prefix] =
blockType.Name;
}
// Pull out the projectPlugin for the correction and cast it (since we know
// what type it is).
ProjectPluginController pluginController = plugins.Controllers[1];
projectPlugin =
(FilesystemPersistenceProjectPlugin) pluginController.ProjectPlugin;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
namespace AuthorIntrusion.Common.Projects
{
/// <summary>
/// Enumerations the various states that a project can be in. This is used
/// to control batch operations.
/// </summary>
public enum ProjectProcessingState
{
/// <summary>
/// Indicates that no special processing is going on with the project.
/// </summary>
Interactive,
/// <summary>
/// Indicates that the project is in the middle of a batch operation.
/// </summary>
Batch,
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using AuthorIntrusion.Common.Blocks;
using MfGames.Commands;
using MfGames.Commands.TextEditing;
namespace AuthorIntrusion.Common.Commands
{
/// <summary>
/// Command to delete multiple lines of text from the blocks.
/// </summary>
public class DeleteMultilineTextCommand: CompositeCommand<BlockCommandContext>
{
#region Constructors
public DeleteMultilineTextCommand(
BlockCollection blocks,
BlockPosition startPosition,
BlockPosition stopPosition)
: base(true, false)
{
// Save the variables so we can set the position.
this.startPosition = startPosition;
this.stopPosition = stopPosition;
// If we are in the same line, we have a modified command.
if (startPosition.BlockKey == stopPosition.BlockKey)
{
// We have a single-line delete.
var singleDeleteCommand = new DeleteTextCommand(
startPosition, stopPosition.TextIndex);
Commands.Add(singleDeleteCommand);
return;
}
// Start by removing the text to the right of the first line.
var deleteTextCommand = new DeleteTextCommand(
startPosition, CharacterPosition.End);
Commands.Add(deleteTextCommand);
// Copy the final line text, from beginning to position, into the first
// line. This will merge the top and bottom lines.
var insertTextCommand = new InsertTextFromBlock(
startPosition,
stopPosition.BlockKey,
stopPosition.TextIndex,
CharacterPosition.End);
Commands.Add(insertTextCommand);
// Once we have a merged line, then just delete the remaining lines.
// Figure out line ranges we'll be deleting text from.
removedBlocks = new List<Block>();
Block startBlock = blocks[startPosition.BlockKey];
Block stopBlock = blocks[stopPosition.BlockKey];
int startIndex = blocks.IndexOf(startBlock);
int stopIndex = blocks.IndexOf(stopBlock);
// Go through the remaining lines.
for (int i = startIndex + 1;
i <= stopIndex;
i++)
{
// Get the block we're removing and add it to the list.
Block removeBlock = blocks[i];
removedBlocks.Add(removeBlock);
// Add in a command to remove the block.
var deleteBlockCommand = new DeleteBlockCommand(removeBlock.BlockKey);
Commands.Add(deleteBlockCommand);
}
}
#endregion
#region Fields
private readonly List<Block> removedBlocks;
private readonly BlockPosition startPosition;
private readonly BlockPosition stopPosition;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using AuthorIntrusion.Common;
using MfGames.HierarchicalPaths;
namespace AuthorIntrusion.Plugins.ImmediateCorrection
{
/// <summary>
/// A configuration settings for an immediate correction controller.
/// </summary>
[XmlRoot("immediate-correction-settings",
Namespace = XmlConstants.ProjectNamespace)]
public class ImmediateCorrectionSettings: IXmlSerializable
{
#region Properties
public static HierarchicalPath SettingsPath { get; private set; }
public List<RegisteredSubstitution> Substitutions { get; set; }
#endregion
#region Methods
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
// We are already at the starting point of this element, so read until the
// end.
string elementName = reader.LocalName;
// Read until we get to the end element.
while (reader.Read())
{
// If we aren't in our namespace, we don't need to bother.
if (reader.NamespaceURI != XmlConstants.ProjectNamespace)
{
continue;
}
// If we got to the end of the node, then stop reading.
if (reader.LocalName == elementName)
{
return;
}
// Look for a key, if we have it, set that value.
if (reader.NodeType == XmlNodeType.Element
&& reader.LocalName == "substitution")
{
// Pull out the settings.
string search = reader["search"];
string replacement = reader["replace"];
var options =
(SubstitutionOptions)
Enum.Parse(typeof (SubstitutionOptions), reader["options"]);
// Add in the substitution.
var substitution = new RegisteredSubstitution(search, replacement, options);
Substitutions.Add(substitution);
}
}
}
public void WriteXml(XmlWriter writer)
{
// Write out a version field.
writer.WriteElementString("version", "1");
// Write out all the substitutions.
foreach (RegisteredSubstitution substitution in Substitutions)
{
writer.WriteStartElement("substitution", XmlConstants.ProjectNamespace);
writer.WriteAttributeString("search", substitution.Search);
writer.WriteAttributeString("replace", substitution.Replacement);
writer.WriteAttributeString("options", substitution.Options.ToString());
writer.WriteEndElement();
}
}
#endregion
#region Constructors
static ImmediateCorrectionSettings()
{
SettingsPath = new HierarchicalPath("/Plugins/Immediate Correction");
}
public ImmediateCorrectionSettings()
{
Substitutions = new List<RegisteredSubstitution>();
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Runtime.InteropServices;
namespace AuthorIntrusion.Plugins.Spelling.NHunspell.Interop
{
/// <summary>
/// Contains the P/Invoke calls for Hunspell.
/// </summary>
public static class HunspellInterop
{
#region Methods
[DllImport("hunspell-1.2", CharSet = CharSet.Auto)]
internal static extern int Hunspell_add(
HunspellHandle handle,
string word);
[DllImport("hunspell-1.2", CharSet = CharSet.Auto)]
internal static extern int Hunspell_add_with_affix(
HunspellHandle handle,
string word,
string example);
[DllImport("hunspell-1.2", CharSet = CharSet.Auto)]
internal static extern IntPtr Hunspell_create(
string affpath,
string dpath);
[DllImport("hunspell-1.2")]
internal static extern void Hunspell_destroy(HunspellHandle handle);
[DllImport("hunspell-1.2")]
internal static extern void Hunspell_free_list(
HunspellHandle handle,
IntPtr slst,
int n);
[DllImport("hunspell-1.2", CharSet = CharSet.Auto)]
internal static extern int Hunspell_spell(
HunspellHandle handle,
string word);
[DllImport("hunspell-1.2", CharSet = CharSet.Auto)]
internal static extern int Hunspell_suggest(
HunspellHandle handle,
IntPtr slst,
string word);
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
namespace AuthorIntrusion.Common.Plugins
{
/// <summary>
/// Defines a flyweight configuration and wrapper around an IPlugin.
/// This is a project-specific controller that handles the project-specific
/// settings and also exposes methods to perform the required operations of
/// the plugin.
/// </summary>
public interface IProjectPlugin
{
#region Properties
/// <summary>
/// Gets the internal name of the plugin. This is not displayed to the
/// user and it is used to look up the plugin via a string, so it must not
/// be translated and cannot change between versions.
///
/// This should contain information to distinguish between different instances
/// of the project plugin if the plugin allows multiple instances.
/// </summary>
string Key { get; }
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
namespace AuthorIntrusion.Common.Commands
{
/// <summary>
/// Internal class to manage an undo/redo command and its plumbing for the
/// BlockCommandSupervisor.
/// </summary>
internal class UndoRedoCommand
{
#region Properties
public IBlockCommand Command { get; set; }
public IBlockCommand InverseCommand { get; set; }
#endregion
#region Methods
public override string ToString()
{
return "UndoRedo " + Command;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AuthorIntrusion.Common.Actions;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
using AuthorIntrusion.Common.Commands;
namespace AuthorIntrusion.Common.Plugins
{
/// <summary>
/// Project-based manager of plugins that are enabled and configured for a given
/// project.
/// </summary>
public class PluginSupervisor
{
#region Properties
/// <summary>
/// Gets the <see cref="IProjectPlugin"/> with the specified plugin key.
/// </summary>
/// <value>
/// The <see cref="IProjectPlugin"/>.
/// </value>
/// <param name="pluginKey">The plugin key.</param>
/// <returns>The IProjectPlugin of the given key.</returns>
/// <exception cref="System.Collections.Generic.KeyNotFoundException">Cannot find plugin with Key of + pluginKey</exception>
public IProjectPlugin this[string pluginKey]
{
get
{
foreach (ProjectPluginController controller in Controllers)
{
if (controller.ProjectPlugin.Key == pluginKey)
{
return controller.ProjectPlugin;
}
}
throw new KeyNotFoundException(
"Cannot find plugin with Key of " + pluginKey);
}
}
public IList<IBlockAnalyzerProjectPlugin> BlockAnalyzers { get; private set; }
public IList<ProjectPluginController> Controllers { get; private set; }
public IList<IImmediateEditorProjectPlugin> ImmediateEditors { get; private set; }
/// <summary>
/// Gets the PluginManager associated with the environment.
/// </summary>
public PluginManager PluginManager
{
get { return PluginManager.Instance; }
}
public Project Project { get; private set; }
#endregion
#region Methods
/// <summary>
/// Adds the specified plugin by name from the PluginManager and sets up the
/// elements inside the project.
/// </summary>
/// <param name="pluginName">Name of the plugin.</param>
/// <returns></returns>
public bool Add(string pluginName)
{
// Look up the plugin from the plugin manager.
IProjectPluginProviderPlugin plugin;
if (!PluginManager.TryGetProjectPlugin(pluginName, out plugin))
{
// We couldn't find the plugin inside the manager.
return false;
}
// If the plugin doesn't allow duplicates, then check to see if we
// already have a configuration object associated with this plugin.
if (!plugin.AllowMultiple
&& Contains(pluginName))
{
// We can't add a new one since we already have one.
return false;
}
// We can add this plugin to the project (either as a duplicate or
// as the first). In all cases, we get a flyweight wrapper around the
// plugin and add it to the ordered list of project-specific plugins.
var projectPlugin = new ProjectPluginController(this, plugin);
// See if this is a plugin framework controller. If it is, we all
// it to connect to any existing plugins.
IProjectPlugin pluginController = projectPlugin.ProjectPlugin;
var frameworkController = pluginController as IFrameworkProjectPlugin;
if (frameworkController != null)
{
var pluginControllers = new List<IProjectPlugin>();
foreach (ProjectPluginController currentPlugin in Controllers)
{
pluginControllers.Add(currentPlugin.ProjectPlugin);
}
frameworkController.InitializePluginFramework(Project, pluginControllers);
}
// Go through the list of existing plugin frameworks and see if they want to
// add this one to their internal management.
foreach (ProjectPluginController controller in Controllers)
{
frameworkController = controller.ProjectPlugin as IFrameworkProjectPlugin;
if (frameworkController != null)
{
frameworkController.HandleAddedController(Project, pluginController);
}
}
// Add the controllers to the list.
Controllers.Add(projectPlugin);
// Because we've made changes to the plugin, we need to sort and reorder it.
// This also creates some of the specialized lists required for handling
// immediate editors (auto-correct).
UpdatePlugins();
// We were successful in adding the plugin.
return true;
}
/// <summary>
/// Clears the analysis state of a block to indicate that all analysis
/// needs to be completed on the task.
/// </summary>
public void ClearAnalysis()
{
using (Project.Blocks.AcquireLock(RequestLock.Read))
{
foreach (Block block in Project.Blocks)
{
block.ClearAnalysis();
}
}
}
/// <summary>
/// Clears the analysis for a single plugin.
/// </summary>
/// <param name="plugin">The plugin.</param>
public void ClearAnalysis(IBlockAnalyzerProjectPlugin plugin)
{
using (Project.Blocks.AcquireLock(RequestLock.Read))
{
foreach (Block block in Project.Blocks)
{
block.ClearAnalysis(plugin);
}
}
}
public bool Contains(string pluginName)
{
return Controllers.Any(plugin => plugin.Name == pluginName);
}
/// <summary>
/// Gets the editor actions for a given text span.
/// </summary>
/// <param name="block">The block.</param>
/// <param name="textSpan">The text span.</param>
/// <returns></returns>
public IList<IEditorAction> GetEditorActions(
Block block,
TextSpan textSpan)
{
// Loop through all the text span controllers and add their actions to
// the list.
IEnumerable<ProjectPluginController> controllers =
Controllers.Where(
controller => controller.ProjectPlugin is ITextControllerProjectPlugin);
var actions = new List<IEditorAction>();
foreach (ProjectPluginController controller in controllers)
{
var textSpanController =
(ITextControllerProjectPlugin) controller.ProjectPlugin;
IList<IEditorAction> controllerActions =
textSpanController.GetEditorActions(block, textSpan);
actions.AddRange(controllerActions);
}
// Return the resulting list of actions.
return actions;
}
/// <summary>
/// Processes the block analysis on all the blocks in the collection.
/// </summary>
public void ProcessBlockAnalysis()
{
using (Project.Blocks.AcquireLock(RequestLock.Read))
{
foreach (Block block in Project.Blocks)
{
ProcessBlockAnalysis(block);
}
}
}
/// <summary>
/// Processes any block analysis on the given block.
/// </summary>
/// <param name="block">The block.</param>
public async void ProcessBlockAnalysis(Block block)
{
// If we don't have any analysis controllers, we don't have to do anything.
if (BlockAnalyzers.Count == 0)
{
return;
}
// Keep track of the running tasks so we can wait for them to finish
// (if needed).
Interlocked.Increment(ref tasksRunning);
try
{
// Grab information about the block inside a read lock.
int blockVersion;
HashSet<IBlockAnalyzerProjectPlugin> analysis;
using (block.AcquireBlockLock(RequestLock.Read))
{
blockVersion = block.Version;
analysis = block.GetAnalysis();
}
// Create a background task that will analyze the block. This will return
// false if the block had changed in the process of analysis (which would
// have triggered another background task).
var analyzer = new BlockAnalyzer(
block, blockVersion, BlockAnalyzers, analysis);
Task task = Task.Factory.StartNew(analyzer.Run);
// Wait for the task to complete in the background so we can then
// decrement our running counter.
await task;
}
finally
{
// Decrement the counter to keep track of running tasks.
Interlocked.Decrement(ref tasksRunning);
}
}
/// <summary>
/// Checks for immediate edits on a block. This is intended to be a blocking
/// editing that will always happen within a write lock.
/// </summary>
/// <param name="context">The context of the edit just performed.</param>
/// <param name="block">The block associated with the current changes.</param>
/// <param name="textIndex">Index of the text inside the block.</param>
public void ProcessImmediateEdits(
BlockCommandContext context,
Block block,
int textIndex)
{
foreach (
IImmediateEditorProjectPlugin immediateBlockEditor in ImmediateEditors)
{
immediateBlockEditor.ProcessImmediateEdits(context, block, textIndex);
}
}
/// <summary>
/// Waits for all running tasks to complete.
/// </summary>
public void WaitForBlockAnalzyers()
{
while (tasksRunning > 0)
{
Thread.Sleep(100);
}
}
/// <summary>
/// Sorts and prepares the plugins for use, along with putting various
/// plugins in the specialized lists for processing immediate edits and
/// block analysis.
/// </summary>
private void UpdatePlugins()
{
// Determine the immediate plugins and pull them into separate list.
ImmediateEditors.Clear();
foreach (ProjectPluginController controller in
Controllers.Where(controller => controller.IsImmediateEditor))
{
ImmediateEditors.Add(
(IImmediateEditorProjectPlugin) controller.ProjectPlugin);
}
// Determine the block analzyers and put them into their own list.
BlockAnalyzers.Clear();
foreach (ProjectPluginController controller in
Controllers.Where(controller => controller.IsBlockAnalyzer))
{
BlockAnalyzers.Add((IBlockAnalyzerProjectPlugin) controller.ProjectPlugin);
}
}
#endregion
#region Constructors
public PluginSupervisor(Project project)
{
Project = project;
Controllers = new List<ProjectPluginController>();
ImmediateEditors = new List<IImmediateEditorProjectPlugin>();
BlockAnalyzers = new List<IBlockAnalyzerProjectPlugin>();
}
#endregion
#region Fields
private int tasksRunning;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using AuthorIntrusion.Common.Projects;
namespace AuthorIntrusion.Common.Persistence.Filesystem
{
/// <summary>
/// Handles the persistence (reading and writing) of the primary project
/// files.
/// </summary>
public class FilesystemPersistenceProjectWriter:
PersistenceReaderWriterBase<FilesystemPersistenceSettings>
{
#region Methods
/// <summary>
/// Writes the project to the specified file.
/// </summary>
/// <param name="projectFile">The project file.</param>
public void Write(FileInfo projectFile)
{
// Open up an XML stream for the project.
using (XmlWriter writer = GetXmlWriter(projectFile))
{
// Start the document.
writer.WriteStartElement("project", ProjectNamespace);
// Write out the version string.
writer.WriteElementString("version", ProjectNamespace, "1");
// Write out the settings we'll be using with this project.
FilesystemPersistenceSettings settings = Settings;
var settingsSerializer = new XmlSerializer(settings.GetType());
settingsSerializer.Serialize(writer, settings);
// Write out the various components.
var settingsWriter = new FilesystemPersistenceSettingsWriter(this);
var structureWriter = new FilesystemPersistenceStructureWriter(this);
var contentWriter = new FilesystemPersistenceContentWriter(this);
var contentDataWriter = new FilesystemPersistenceContentDataWriter(this);
settingsWriter.Write(writer);
structureWriter.Write(writer);
contentWriter.Write(writer);
contentDataWriter.Write(writer);
// Finish up the project tag.
writer.WriteEndElement();
}
}
#endregion
#region Constructors
public FilesystemPersistenceProjectWriter(
Project project,
FilesystemPersistenceSettings settings,
ProjectMacros macros)
: base(project, settings, macros)
{
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
namespace AuthorIntrusion.Cli
{
/// <summary>
/// Implements a command-line interface for various functionality inside the
/// AuthorIntrusion system.
/// </summary>
public class Program
{
#region Methods
/// <summary>
/// Main entry point into the application.
/// </summary>
/// <param name="args">The arguments.</param>
private static void Main(string[] args)
{
// Create the IoC/DI resolver.
var resolver = new EnvironmentResolver();
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Actions;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
using AuthorIntrusion.Common.Commands;
using AuthorIntrusion.Common.Events;
using Gtk;
using MfGames.Commands;
using MfGames.Commands.TextEditing;
using MfGames.GtkExt;
using MfGames.GtkExt.TextEditor;
using MfGames.GtkExt.TextEditor.Events;
using MfGames.GtkExt.TextEditor.Models.Buffers;
using MfGames.GtkExt.TextEditor.Models.Extensions;
namespace AuthorIntrusion.Gui.GtkGui
{
/// <summary>
/// Encapsulates an adapter class between the text editor's line buffer and
/// the project information.
/// </summary>
public class ProjectLineBuffer: MultiplexedOperationLineBuffer,
IDisposable
{
#region Properties
public override int LineCount
{
get
{
using (blocks.AcquireLock(RequestLock.Read))
{
int results = blocks.Count;
return results;
}
}
}
public override bool ReadOnly
{
get { return false; }
}
#endregion
#region Methods
public override LineBufferOperationResults DeleteLines(
int lineIndex,
int count)
{
using (project.Blocks.AcquireLock(RequestLock.Write))
{
Block block = project.Blocks[lineIndex];
var command = new DeleteBlockCommand(block.BlockKey);
var context = new BlockCommandContext(project);
project.Commands.Do(command, context);
return GetOperationResults();
}
}
public override IEnumerable<ILineIndicator> GetLineIndicators(
int lineIndex,
int startCharacterIndex,
int endCharacterIndex)
{
// Create a list of indicators.
var indicators = new List<ILineIndicator>();
// Grab the line and use the block type to figure out the indicator.
Block block;
using (blocks.AcquireBlockLock(RequestLock.Read, lineIndex, out block))
{
string blockTypeName = block.BlockType.Name;
switch (blockTypeName)
{
case "Chapter":
ILineIndicator indicator = new ProjectLineIndicator(blockTypeName);
indicators.Add(indicator);
break;
}
}
// Return the resulting indicators.
return indicators;
}
public override int GetLineLength(
int lineIndex,
LineContexts lineContexts)
{
string line = GetLineText(lineIndex, lineContexts);
return line.Length;
}
public override string GetLineMarkup(
int lineIndex,
LineContexts lineContexts)
{
// We need to get a read-only lock on the block.
Block block;
using (blocks.AcquireBlockLock(RequestLock.Read, lineIndex, out block))
{
// Now that we have a block, grab the text and text spans and
// format them. If we don't have any text spans, we can return
// a simple formatted string.
string text = block.Text;
TextSpanCollection spans = block.TextSpans;
string markup = spans.Count == 0
? PangoUtility.Escape(text)
: FormatText(text, spans);
// Return the resulting markup.
return markup;
}
}
public override string GetLineNumber(int lineIndex)
{
return lineIndex.ToString(CultureInfo.InvariantCulture);
}
public override string GetLineStyleName(
int lineIndex,
LineContexts lineContexts)
{
// We only need a read-lock on the blocks just to make sure nothing moves
// underneath us while we get the block key.
using (blocks.AcquireLock(RequestLock.Read))
{
// Create the command and submit it to the project's command manager.
Block block = blocks[lineIndex];
string blockTypeName = block.BlockType.Name;
return blockTypeName;
}
}
public override string GetLineText(
int lineIndex,
LineContexts lineContexts)
{
using (blocks.AcquireLock(RequestLock.Read))
{
Block block = blocks[lineIndex];
string line = block.Text;
return line;
}
}
public override LineBufferOperationResults InsertLines(
int lineIndex,
int count)
{
var composite = new CompositeCommand<BlockCommandContext>(true, false);
using (project.Blocks.AcquireLock(RequestLock.Write))
{
for (int i = 0;
i < count;
i++)
{
var block = new Block(project.Blocks);
var command = new InsertIndexedBlockCommand(lineIndex, block);
composite.Commands.Add(command);
}
var context = new BlockCommandContext(project);
project.Commands.Do(composite, context);
return GetOperationResults();
}
}
public override LineBufferOperationResults InsertText(
int lineIndex,
int characterIndex,
string text)
{
using (project.Blocks.AcquireLock(RequestLock.Write))
{
Block block = project.Blocks[lineIndex];
var position = new BlockPosition(block.BlockKey, characterIndex);
var command = new InsertTextCommand(position, text);
var context = new BlockCommandContext(project);
project.Commands.Do(command, context);
return GetOperationResults();
}
}
public void RaiseLineDeleted(int lineIndex)
{
var args = new LineRangeEventArgs(lineIndex, lineIndex);
base.RaiseLinesDeleted(args);
}
public void RaiseLineInserted(int lineIndex)
{
var args = new LineRangeEventArgs(lineIndex, lineIndex);
base.RaiseLinesInserted(args);
}
protected override LineBufferOperationResults Do(
DeleteTextOperation operation)
{
//// We only need a read-lock on the blocks just to make sure nothing moves
//// underneath us while we get the block key.
//using (blocks.AcquireLock(RequestLock.Read))
//{
// // Create the command and submit it to the project's command manager.
// Block block = blocks[operation.LineIndex];
// var command =
// new DeleteTextCommand(
// new BlockPosition(block.BlockKey, operation.CharacterRange.StartIndex),
// operation.CharacterRange.Length);
// commands.Do(command);
// // Fire a line changed operation.
// RaiseLineChanged(new LineChangedArgs(operation.LineIndex));
// // Construct the operation results for the delete from information in the
// // command manager.
// var results =
// new LineBufferOperationResults(
// new TextPosition(blocks.IndexOf(block), commands.LastPosition.TextIndex));
// return results;
//}
throw new NotImplementedException();
}
protected override LineBufferOperationResults Do(
InsertTextOperation operation)
{
//// We need a write lock on the block and a read lock on the blocks.
//Block block = blocks[operation.TextPosition.LineIndex];
//using (block.AcquireBlockLock(RequestLock.Write))
//{
// // Create the command and submit it to the project's command manager.
// var command =
// new InsertTextCommand(
// new BlockPosition(block.BlockKey, operation.TextPosition.CharacterIndex),
// operation.Text);
// commands.Do(command);
// // Fire a line changed operation.
// RaiseLineChanged(new LineChangedArgs(operation.TextPosition.LineIndex));
// // Construct the operation results for the delete from information in the
// // command manager.
// var results =
// new LineBufferOperationResults(
// new TextPosition(blocks.IndexOf(block), commands.LastPosition.TextIndex));
// return results;
//}
throw new NotImplementedException();
}
protected override LineBufferOperationResults Do(SetTextOperation operation)
{
//// We only need a read-lock on the blocks just to make sure nothing moves
//// underneath us while we get the block key.
//using (blocks.AcquireLock(RequestLock.Read))
//{
// // Create the command and submit it to the project's command manager.
// Block block = blocks[operation.LineIndex];
// var command = new SetTextCommand(block.BlockKey, operation.Text);
// commands.Do(command);
// // Fire a line changed operation.
// RaiseLineChanged(new LineChangedArgs(operation.LineIndex));
// // Construct the operation results for the delete from information in the
// // command manager.
// var results =
// new LineBufferOperationResults(
// new TextPosition(blocks.IndexOf(block), commands.LastPosition.TextIndex));
// return results;
//}
throw new NotImplementedException();
}
protected override LineBufferOperationResults Do(
InsertLinesOperation operation)
{
//// We need a write lock on the blocks since this will be making changes
//// to the structure of the document.
//using (blocks.AcquireLock(RequestLock.Write))
//{
// // Create the command and submit it to the project's command manager.
// Block block = blocks[operation.LineIndex];
// var command = new InsertAfterBlockCommand(block.BlockKey, operation.Count);
// commands.Do(command);
// // Raise the events to indicate the line changed.
// RaiseLinesInserted(
// new LineRangeEventArgs(
// operation.LineIndex, operation.LineIndex + operation.Count));
// // Construct the operation results for the delete from information in the
// // command manager.
// var results =
// new LineBufferOperationResults(
// new TextPosition(blocks.IndexOf(block), commands.LastPosition.TextIndex));
// return results;
//}
throw new NotImplementedException();
}
protected override LineBufferOperationResults Do(
DeleteLinesOperation operation)
{
//// We only need a read-lock on the blocks just to make sure nothing moves
//// underneath us while we get the block key.
//using (blocks.AcquireLock(RequestLock.Read))
//{
// // Add each delete line into a composite command.
// var deleteCommand = new CompositeCommand();
// for (int lineIndex = operation.LineIndex;
// lineIndex < operation.LineIndex + operation.Count;
// lineIndex++)
// {
// Block block = blocks[lineIndex];
// var command = new DeleteBlockCommand(block.BlockKey);
// deleteCommand.Commands.Add(command);
// }
// // Submit the delete line.
// commands.Do(deleteCommand);
// // Raise the deleted line events.
// RaiseLinesDeleted(
// new LineRangeEventArgs(
// operation.LineIndex, operation.LineIndex + operation.Count));
// // Construct the operation results for the delete from information in the
// // command manager.
// var results =
// new LineBufferOperationResults(
// new TextPosition(operation.LineIndex, commands.LastPosition.TextIndex));
// return results;
//}
throw new NotImplementedException();
}
/// <summary>
/// Formats the text using the spans, adding in error formatting if there
/// is a text span.
/// </summary>
/// <param name="text">The text to format.</param>
/// <param name="spans">The spans we need to use to format.</param>
/// <returns>A Pango-formatted string.</returns>
private string FormatText(
string text,
TextSpanCollection spans)
{
// Create a string builder and go through the text, one character at a time.
var buffer = new StringBuilder();
bool inSpan = false;
for (int index = 0;
index < text.Length;
index++)
{
// Grab the character at this position in the text.
char c = text[index];
bool hasSpan = spans.Contains(index);
// If the inSpan and hasSpan is different, we need to either
// open or close the span.
if (hasSpan != inSpan)
{
// Add in the tag depending on if we are opening or close the tag.
string tag = inSpan
? "</span>"
: "<span underline='error' underline_color='red' color='red'>";
buffer.Append(tag);
// Update the current inSpan state.
inSpan = hasSpan;
}
// Add in the character we've been processing.
buffer.Append(c);
}
// Check to see if we were in a tag, if we are, we need to close it.
if (inSpan)
{
buffer.Append("</span>");
}
// Return the resulting buffer.
string markup = buffer.ToString();
return markup;
}
private LineBufferOperationResults GetOperationResults()
{
int blockIndex =
project.Blocks.IndexOf(project.Commands.LastPosition.BlockKey);
var results =
new LineBufferOperationResults(
new TextPosition(blockIndex, (int) project.Commands.LastPosition.TextIndex));
return results;
}
private void OnBlockTextChanged(
object sender,
BlockEventArgs e)
{
int blockIndex = blocks.IndexOf(e.Block);
var args = new LineChangedArgs(blockIndex);
RaiseLineChanged(args);
}
private void OnBlockTypeChanged(
object sender,
BlockEventArgs e)
{
int blockIndex = blocks.IndexOf(e.Block);
var args = new LineChangedArgs(blockIndex);
RaiseLineChanged(args);
}
/// <summary>
/// Called when the context menu is being populated.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="args">The event arguments.</param>
private void OnPopulateContextMenu(
object sender,
PopulateContextMenuArgs args)
{
// Remove the existing items from the list.
var menuItems = new HashSet<Widget>(args.Menu.Children);
foreach (Widget menuItem in menuItems)
{
args.Menu.Remove(menuItem);
}
// We need a read lock on both the collection and the specific block
// for the given line index.
TextPosition position = editorView.Caret.Position;
int blockIndex =
position.LinePosition.GetLineIndex(editorView.LineBuffer.LineCount);
int characterIndex = position.GetCharacterIndex(editorView.LineBuffer);
Block block;
var context = new BlockCommandContext(project);
using (blocks.AcquireBlockLock(RequestLock.Read, blockIndex, out block))
{
// Figure out if we have any spans for this position.
if (!block.TextSpans.Contains(characterIndex))
{
// Nothing to add, so we can stop processing.
return;
}
// Gather up all the text spans for the current position in the line.
var textSpans = new List<TextSpan>();
textSpans.AddRange(block.TextSpans.GetAll(characterIndex));
// Gather up the menu items for this point.
bool firstItem = true;
foreach (TextSpan textSpan in textSpans)
{
IList<IEditorAction> actions = textSpan.Controller.GetEditorActions(
block, textSpan);
foreach (IEditorAction action in actions)
{
// Create a menu item and hook up events.
IEditorAction doAction = action;
var menuItem = new MenuItem(action.DisplayName);
menuItem.Activated += delegate
{
doAction.Do(context);
RaiseLineChanged(new LineChangedArgs(blockIndex));
};
// If this is the first item, then make the initial
// selection to avoid scrolling.
if (firstItem)
{
menuItem.Select();
}
firstItem = false;
// Add the item to the popup menu.
args.Menu.Add(menuItem);
}
}
}
}
private void OnTextSpansChanged(
object sender,
BlockEventArgs e)
{
int blockIndex = blocks.IndexOf(e.Block);
var args = new LineChangedArgs(blockIndex);
RaiseLineChanged(args);
}
#endregion
#region Constructors
public ProjectLineBuffer(
Project project,
EditorView editorView)
{
// Save the parameters as member fields for later.
this.project = project;
this.editorView = editorView;
// Pull out some common elements.
blocks = this.project.Blocks;
commands = project.Commands;
// Hook up the events.
editorView.Controller.PopulateContextMenu += OnPopulateContextMenu;
blocks.BlockTextChanged += OnBlockTextChanged;
blocks.TextSpansChanged += OnTextSpansChanged;
blocks.BlockTypeChanged += OnBlockTypeChanged;
}
#endregion
#region Destructors
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool isDisposing)
{
if (isDisposing)
{
// Disconnect from events.
editorView.Controller.PopulateContextMenu -= OnPopulateContextMenu;
blocks.BlockTextChanged -= OnBlockTextChanged;
blocks.TextSpansChanged -= OnTextSpansChanged;
blocks.BlockTypeChanged -= OnBlockTypeChanged;
}
}
#endregion
#region Fields
private readonly ProjectBlockCollection blocks;
private readonly BlockCommandSupervisor commands;
private readonly EditorView editorView;
private readonly Project project;
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using System.Linq;
using AuthorIntrusion.Common.Plugins;
namespace AuthorIntrusion.Common.Persistence
{
/// <summary>
/// Defines a system plugin for handling the Persistence layer. This manages the
/// various ways a file can be loaded and saved from the filesystem and network.
/// </summary>
public class PersistenceFrameworkPlugin: IFrameworkPlugin,
IProjectPluginProviderPlugin
{
#region Properties
public bool AllowMultiple
{
get { return false; }
}
public string Key
{
get { return "Persistence Framework"; }
}
/// <summary>
/// Gets the list of persistent plugins registered with the framework.
/// </summary>
public List<IPersistencePlugin> PersistentPlugins
{
get { return plugins; }
}
#endregion
#region Methods
public IProjectPlugin GetProjectPlugin(Project project)
{
var projectPlugin = new PersistenceFrameworkProjectPlugin(project);
return projectPlugin;
}
public void RegisterPlugins(IEnumerable<IPlugin> additionalPlugins)
{
// Go through all the plugins and add the persistence plugins to our
// internal list.
IEnumerable<IPersistencePlugin> persistencePlugins =
additionalPlugins.OfType<IPersistencePlugin>();
foreach (IPersistencePlugin plugin in persistencePlugins)
{
plugins.Add(plugin);
}
}
#endregion
#region Constructors
public PersistenceFrameworkPlugin()
{
plugins = new List<IPersistencePlugin>();
}
#endregion
#region Fields
private readonly List<IPersistencePlugin> plugins;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Commands;
using AuthorIntrusion.Common.Plugins;
using MfGames.Settings;
namespace AuthorIntrusion.Plugins.ImmediateCorrection
{
public class ImmediateCorrectionProjectPlugin: IImmediateEditorProjectPlugin
{
#region Properties
public string Key
{
get { return "Immediate Correction"; }
}
public ImmediateCorrectionPlugin Plugin { get; set; }
public Project Project { get; set; }
public List<RegisteredSubstitution> Substitutions { get; private set; }
#endregion
#region Methods
public void AddSubstitution(
string search,
string replacement,
SubstitutionOptions options)
{
AddSubstitution(Project.Settings, search, replacement, options);
}
public void AddSubstitution(
SettingsManager settingsManager,
string search,
string replacement,
SubstitutionOptions options)
{
// Create the substitution we'll be registering.
var substitution = new RegisteredSubstitution(search, replacement, options);
// Grab the configuration object for this settings manager or create one if
// it doesn't already exist.
var settings =
settingsManager.Get<ImmediateCorrectionSettings>(
ImmediateCorrectionSettings.SettingsPath);
settings.Substitutions.Add(substitution);
// Mark that our substituions are out of date.
optimizedSubstitions = false;
}
public void ProcessImmediateEdits(
BlockCommandContext context,
Block block,
int textIndex)
{
// If we aren't optimized, we have to pull the settings back in from the
// project settings and optimize them.
if (!optimizedSubstitions)
{
RetrieveSettings();
}
// Pull out the edit text and add a leading space to simplify the
// "whole word" substitutions.
string editText = block.Text.Substring(0, textIndex);
if (editText.Length - 1 < 0)
{
return;
}
// Figure out if we're at a word break.
char finalCharacter = editText[editText.Length - 1];
bool isWordBreak = char.IsPunctuation(finalCharacter)
|| char.IsWhiteSpace(finalCharacter);
// Go through the substitution elements and look for each one.
foreach (RegisteredSubstitution substitution in Substitutions)
{
// If we are doing whole word searches, then we don't bother if
// the final character isn't a word break or if it isn't a word
// break before it.
ReplaceTextCommand command;
int searchLength = substitution.Search.Length;
int startSearchIndex = editText.Length - searchLength;
// If we are going to be searching before the string, then this
// search term will never be valid.
if (startSearchIndex < 0)
{
continue;
}
// Do the search based on the whole word or suffix search.
if (substitution.IsWholeWord)
{
// Check to see if we have a valid search term.
if (!isWordBreak)
{
continue;
}
if (startSearchIndex > 0
&& char.IsPunctuation(editText[startSearchIndex - 1]))
{
continue;
}
if (startSearchIndex - 1 < 0)
{
continue;
}
// Make sure the string we're looking at actually is the same.
string editSubstring = editText.Substring(
startSearchIndex - 1, substitution.Search.Length);
if (editSubstring != substitution.Search)
{
// The words don't match.
continue;
}
// Perform the substitution with a replace operation.
command =
new ReplaceTextCommand(
new BlockPosition(block.BlockKey, startSearchIndex - 1),
searchLength + 1,
substitution.Replacement + finalCharacter);
}
else
{
// Perform a straight comparison search.
if (!editText.EndsWith(substitution.Search))
{
continue;
}
// Figure out the replace operation.
command =
new ReplaceTextCommand(
new BlockPosition(block.BlockKey, startSearchIndex),
searchLength,
substitution.Replacement);
}
// Add the command to the deferred execution so the command could
// be properly handled via the undo/redo management.
block.Project.Commands.DeferDo(command);
}
}
/// <summary>
/// Retrieves the setting substitutions and rebuilds the internal list.
/// </summary>
private void RetrieveSettings()
{
// Clear out the existing settings.
Substitutions.Clear();
// Go through all of the settings in the various projects.
IList<ImmediateCorrectionSettings> settingsList =
Project.Settings.GetAll<ImmediateCorrectionSettings>(
ImmediateCorrectionSettings.SettingsPath);
foreach (ImmediateCorrectionSettings settings in settingsList)
{
// Go through the substitions inside the settings.
foreach (RegisteredSubstitution substitution in settings.Substitutions)
{
// Check to see if we already have it in the collection.
if (!Substitutions.Contains(substitution))
{
Substitutions.Add(substitution);
}
}
}
// Sort the substitutions.
Substitutions.Sort();
// Clear out the optimization list so we rebuild it on the first request.
optimizedSubstitions = true;
}
#endregion
#region Constructors
public ImmediateCorrectionProjectPlugin(
ImmediateCorrectionPlugin plugin,
Project project)
{
// Save the various properties we need for the controller.
Plugin = plugin;
Project = project;
// Set up the substitions from the configuration settings.
Substitutions = new List<RegisteredSubstitution>();
RetrieveSettings();
}
#endregion
#region Fields
private bool optimizedSubstitions;
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Actions;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
using AuthorIntrusion.Common.Commands;
using AuthorIntrusion.Common.Plugins;
using AuthorIntrusion.Plugins.Spelling.Common;
using MfGames.HierarchicalPaths;
namespace AuthorIntrusion.Plugins.Spelling
{
/// <summary>
/// Project-specific controller for handling the spelling framework.
/// </summary>
public class SpellingFrameworkProjectPlugin: IFrameworkProjectPlugin,
IBlockAnalyzerProjectPlugin,
ITextControllerProjectPlugin
{
#region Properties
public string Key
{
get { return "Spelling Framework"; }
}
private List<ISpellingProjectPlugin> SpellingControllers { get; set; }
private SpellingWordSplitter Splitter { get; set; }
#endregion
#region Methods
public void AnalyzeBlock(
Block block,
int blockVersion)
{
// Grab the information about the block.
string text;
var originalMispelledWords = new TextSpanCollection();
using (block.AcquireBlockLock(RequestLock.Read))
{
// If we are stale, then break out.
if (block.IsStale(blockVersion))
{
return;
}
// Grab the information from the block. We need the text and
// alow the current spelling areas.
text = block.Text;
originalMispelledWords.AddRange(
block.TextSpans.Where(span => span.Controller == this));
}
// Split the word and perform spell-checking.
var misspelledWords = new List<TextSpan>();
IList<TextSpan> words = Splitter.SplitAndNormalize(text);
IEnumerable<TextSpan> misspelledSpans =
words.Where(span => !IsCorrect(span.GetText(text)));
foreach (TextSpan span in misspelledSpans)
{
// We aren't correct, so add it to the list.
span.Controller = this;
misspelledWords.Add(span);
}
// Look to see if we have any change from the original spelling
// errors and this one. This will only happen if the count is
// identical and every one in the original list is in the new list.
if (originalMispelledWords.Count == misspelledWords.Count)
{
bool isMatch = originalMispelledWords.All(misspelledWords.Contains);
if (isMatch)
{
// There are no new changes, so we don't have anything to
// update.
return;
}
}
// Inside a write lock, we need to make modifications to the block's list.
using (block.AcquireBlockLock(RequestLock.Write))
{
// Check one last time to see if the block is stale.
if (block.IsStale(blockVersion))
{
return;
}
// Make the changes to the block's contents.
block.TextSpans.Remove(this);
block.TextSpans.AddRange(misspelledWords);
// Raise that we changed the spelling on the block.
block.RaiseTextSpansChanged();
}
}
/// <summary>
/// Gets the editor actions associated with the given TextSpan.
/// </summary>
/// <param name="block">The block.</param>
/// <param name="textSpan">The text span.</param>
/// <returns>
/// A list of editor actions associated with this span.
/// </returns>
/// <remarks>
/// This will be called within a read-only lock.
/// </remarks>
public IList<IEditorAction> GetEditorActions(
Block block,
TextSpan textSpan)
{
// We only get to this point if we have a misspelled word.
string word = textSpan.GetText(block.Text);
// Get the suggestions for the word.
IList<SpellingSuggestion> suggestions = GetSuggestions(word);
// Go through the suggestions and create an editor action for each one.
// These will already be ordered coming out of the GetSuggestions()
// method.
BlockCommandSupervisor commands = block.Project.Commands;
var actions = new List<IEditorAction>(suggestions.Count);
foreach (SpellingSuggestion suggestion in suggestions)
{
// Figure out the operation we'll be using to implement the change.
var command =
new ReplaceTextCommand(
new BlockPosition(block.BlockKey, textSpan.StartTextIndex),
textSpan.Length,
suggestion.Suggestion);
// Create the suggestion action, along with the replacement command.
var action =
new EditorAction(
string.Format("Change to \"{0}\"", suggestion.Suggestion),
new HierarchicalPath("/Plugins/Spelling/Change"),
context => commands.Do(command, context));
actions.Add(action);
}
// Add the additional editor actions from the plugins.
foreach (ISpellingProjectPlugin controller in SpellingControllers)
{
IEnumerable<IEditorAction> additionalActions =
controller.GetAdditionalEditorActions(word);
actions.AddRange(additionalActions);
}
// Return all the change actions.
return actions;
}
public void HandleAddedController(
Project project,
IProjectPlugin controller)
{
var spellingController = controller as ISpellingProjectPlugin;
if (spellingController != null)
{
// Update the collections.
SpellingControllers.Remove(spellingController);
SpellingControllers.Add(spellingController);
// Inject some additional linkage into the controller.
spellingController.BlockAnalyzer = this;
}
}
public void HandleRemovedController(
Project project,
IProjectPlugin controller)
{
var spellingController = controller as ISpellingProjectPlugin;
if (spellingController != null)
{
// Update the collections.
SpellingControllers.Remove(spellingController);
// Inject some additional linkage into the controller.
spellingController.BlockAnalyzer = null;
}
}
public void InitializePluginFramework(
Project project,
IEnumerable<IProjectPlugin> controllers)
{
foreach (IProjectPlugin controller in controllers)
{
HandleAddedController(project, controller);
}
}
public void WriteTextSpanData(
XmlWriter writer,
object data)
{
throw new ApplicationException(
"Had a request for writing a text span but spelling has no data.");
}
private IList<SpellingSuggestion> GetSuggestions(string word)
{
// Gather up all the suggestions from all the controllers.
var suggestions = new List<SpellingSuggestion>();
foreach (ISpellingProjectPlugin controller in SpellingControllers)
{
// Get the suggestions from the controller.
IEnumerable<SpellingSuggestion> controllerSuggestions =
controller.GetSuggestions(word);
// Go through each one and add them, removing lower priority ones
// as we process.
foreach (SpellingSuggestion controllerSuggestion in controllerSuggestions)
{
// If we already have it and its lower priority, then skip it.
if (suggestions.Contains(controllerSuggestion))
{
}
// Add it to the list.
suggestions.Add(controllerSuggestion);
}
}
// Sort the suggestions by priority.
//suggestions.Sort();
// Return the suggestions so they can be processed.
return suggestions;
}
private bool IsCorrect(string word)
{
// Go through the plugins and look for a determine answer.
var correctness = WordCorrectness.Indeterminate;
foreach (ISpellingProjectPlugin controller in SpellingControllers)
{
// Get the correctness of this word.
correctness = controller.IsCorrect(word);
// If we have a non-determinate answer, then break out.
if (correctness != WordCorrectness.Indeterminate)
{
break;
}
}
// If we finished through all the controllers and we still have
// an indeterminate result, we assume it is correctly spelled.
if (correctness == WordCorrectness.Indeterminate)
{
correctness = WordCorrectness.Correct;
}
// Return if we are correct or not.
return correctness == WordCorrectness.Correct;
}
#endregion
#region Constructors
public SpellingFrameworkProjectPlugin()
{
SpellingControllers = new List<ISpellingProjectPlugin>();
Splitter = new SpellingWordSplitter();
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Collections.Generic;
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Plugins;
using MfGames.HierarchicalPaths;
namespace AuthorIntrusion.Plugins.Counter
{
/// <summary>
/// Contains some useful constants and static methods used for standardizing
/// word counter paths.
/// </summary>
public static class WordCounterPathUtility
{
#region Methods
public static void GetCounts(
IProjectPlugin project,
Block block,
out int count,
out int wordCount,
out int characterCount,
out int nonWhitespaceCount)
{
// Make sure we have a sane state.
if (project == null)
{
throw new ArgumentNullException("project");
}
if (block == null)
{
throw new ArgumentNullException("block");
}
// Figure out the root path for the various components.
HierarchicalPath rootPath = GetPluginRootPath(project);
count = GetCount(block, rootPath, "Total/" + CountType);
wordCount = GetCount(block, rootPath, "Total/" + WordCountType);
characterCount = GetCount(block, rootPath, "Total/" + CharacterCountType);
nonWhitespaceCount = GetCount(
block, rootPath, "Total/" + NonWhitespaceCountType);
}
/// <summary>
/// Gets the deltas as a dictionary of key and deltas for the block.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="block">The block.</param>
/// <param name="wordDelta">The word delta.</param>
/// <param name="characterDelta">The character delta.</param>
/// <param name="nonWhitespaceDelta">The non whitespace delta.</param>
/// <returns>
/// A dictionary of paths and deltas.
/// </returns>
public static Dictionary<HierarchicalPath, int> GetDeltas(
IProjectPlugin project,
Block block,
int delta,
int wordDelta,
int characterDelta,
int nonWhitespaceDelta)
{
// Make sure we have a sane arguments.
if (project == null)
{
throw new ArgumentNullException("project");
}
if (block == null)
{
throw new ArgumentNullException("block");
}
// Create the dictionary and figure out the top-level elements.
var deltas = new Dictionary<HierarchicalPath, int>();
HierarchicalPath rootPath = GetPluginRootPath(project);
// Add in the path for the totals.
var totalPath = new HierarchicalPath("Total", rootPath);
AddDeltas(
deltas, totalPath, delta, wordDelta, characterDelta, nonWhitespaceDelta);
// Add in a block-type specific path along with a counter.
string relativeBlockPath = "Block Types/" + block.BlockType.Name;
var blockPath = new HierarchicalPath(relativeBlockPath, rootPath);
AddDeltas(
deltas, blockPath, delta, wordDelta, characterDelta, nonWhitespaceDelta);
// Return the resulting delta.
return deltas;
}
/// <summary>
/// Adds the deltas for the various counters underneath the given path.
/// </summary>
/// <param name="deltas">The deltas.</param>
/// <param name="rootPath">The root path.</param>
/// <param name="delta"></param>
/// <param name="wordDelta">The word delta.</param>
/// <param name="characterDelta">The character delta.</param>
/// <param name="nonWhitespaceDelta">The non whitespace delta.</param>
private static void AddDeltas(
IDictionary<HierarchicalPath, int> deltas,
HierarchicalPath rootPath,
int delta,
int wordDelta,
int characterDelta,
int nonWhitespaceDelta)
{
AddDeltas(deltas, rootPath, CountType, delta);
AddDeltas(deltas, rootPath, WordCountType, wordDelta);
AddDeltas(deltas, rootPath, CharacterCountType, characterDelta);
AddDeltas(deltas, rootPath, NonWhitespaceCountType, nonWhitespaceDelta);
AddDeltas(
deltas, rootPath, WhitespaceCountType, characterDelta - nonWhitespaceDelta);
}
/// <summary>
/// Adds a delta for a given path.
/// </summary>
/// <param name="deltas">The deltas.</param>
/// <param name="rootPath">The root path.</param>
/// <param name="type">The type.</param>
/// <param name="delta">The delta.</param>
private static void AddDeltas(
IDictionary<HierarchicalPath, int> deltas,
HierarchicalPath rootPath,
string type,
int delta)
{
var path = new HierarchicalPath(type, rootPath);
if (deltas.ContainsKey(path))
{
deltas[path] += delta;
}
else
{
deltas[path] = delta;
}
}
private static int GetCount(
IPropertiesContainer propertiesContainer,
HierarchicalPath rootPath,
string countType)
{
var path = new HierarchicalPath(countType, rootPath);
string count;
return propertiesContainer.Properties.TryGetValue(path, out count)
? Convert.ToInt32(count)
: 0;
}
private static HierarchicalPath GetPluginRootPath(IProjectPlugin project)
{
return new HierarchicalPath("/Plugins/" + project.Key);
}
#endregion
#region Fields
private const string CharacterCountType = "Characters";
private const string CountType = "Count";
private const string NonWhitespaceCountType = "Non-Whitespace";
private const string WhitespaceCountType = "Whitespace";
private const string WordCountType = "Words";
#endregion
}
}
<file_sep>// Copyright 2012-2013 Mo<NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
namespace AuthorIntrusion.Common.Plugins
{
/// <summary>
/// Defines a generic plugin used in the system.
/// </summary>
public interface IPlugin
{
#region Properties
/// <summary>
/// Gets the internal name of the plugin. This is not displayed to the
/// user and it is used to look up the plugin via a string, so it must not
/// be translated and cannot change between versions.
///
/// This should contain information to distinguish between different instances
/// of the project plugin if the plugin allows multiple instances.
/// </summary>
string Key { get; }
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Collections.Generic;
using System.IO;
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Plugins;
using NHunspell;
namespace AuthorIntrusion.Plugins.Spelling.NHunspell
{
public class HunspellSpellingPlugin: IProjectPluginProviderPlugin
{
#region Properties
public bool AllowMultiple
{
get { return false; }
}
public string Key
{
get { return "NHunspell"; }
}
/// <summary>
/// Gets the spell engine associated with this plugin.
/// </summary>
public SpellEngine SpellEngine { get; private set; }
#endregion
#region Methods
public IProjectPlugin GetProjectPlugin(Project project)
{
return projectPlugin;
}
/// <summary>
/// Searches through the calculated paths and attempts to find a
/// file in that directory.
/// </summary>
/// <param name="basename">The basename to look for (en_US.aff).</param>
/// <param name="filename">The resulting filename, if found..</param>
/// <returns>True if a file was found, otherwise false.</returns>
private bool GetDictionaryPath(
string basename,
out string filename)
{
// Go through all the paths and try to find it.
foreach (string searchPath in searchPaths)
{
// Figure out the full name for this file.
filename = Path.Combine(searchPath, basename);
if (File.Exists(filename))
{
// We found it, so use this one.
return true;
}
}
// If we got out of the loop, then we couldn't find it at all.
filename = null;
return false;
}
/// <summary>
/// Gets the paths for the affix and dictionary files by searching for
/// them at various locations in the filesystem.
/// </summary>
/// <param name="languageCode">The language code needed.</param>
/// <param name="affixFilename">The resulting affix filename, if found.</param>
/// <param name="dictFilename">The resulting dictionary filename, if found.</param>
/// <returns>True if both the affix and dictionary files were found, otherwise false.</returns>
private bool GetDictionaryPaths(
string languageCode,
out string affixFilename,
out string dictFilename)
{
// Try to get the affix filename.
string affixBasename = languageCode + ".aff";
bool affixFound = GetDictionaryPath(affixBasename, out affixFilename);
if (!affixFound)
{
dictFilename = null;
return false;
}
// We have the affix, now try the dictionary.
string dictBasename = languageCode + ".dic";
bool dictFound = GetDictionaryPath(dictBasename, out dictFilename);
return dictFound;
}
#endregion
#region Constructors
static HunspellSpellingPlugin()
{
// Build up an array of locations we'll look for the dictionaries.
string assemblyFilename = typeof (HunspellSpellingPlugin).Assembly.Location;
string assemblyPath = Directory.GetParent(assemblyFilename).FullName;
string assemblyDictPath = Path.Combine(assemblyPath, "dicts");
var paths = new List<string>
{
// Add in the paths relative to the assembly.
assemblyPath,
assemblyDictPath,
// Add in the Linux-specific paths.
"/usr/share/hunspell",
"/usr/share/myspell",
"/usr/share/myspell/dicts",
// Add in the Windows-specific paths.
"C:\\Program Files\\OpenOffice.org 3\\share\\dict\\ooo",
};
searchPaths = paths.ToArray();
}
public HunspellSpellingPlugin()
{
// Set up the spell engine for multi-threaded access.
SpellEngine = new SpellEngine();
// Assume we are disabled unless we can configure it properly.
projectPlugin = new DisabledSpellingProjectPlugin();
// Figure out the paths to the dictionary files. For the time being,
// we're going to assume we're using U.S. English.
string affixFilename;
string dictionaryFilename;
if (!GetDictionaryPaths("en_US", out affixFilename, out dictionaryFilename))
{
// We couldn't get the dictionary paths, so just stick with the
// disabled spelling plugin.
return;
}
// Attempt to load the NHunspell plugin. This is a high-quality
// plugin based on Managed C++. This works nicely in Windows, but
// has no support for Linux.
try
{
// Attempt to load the U.S. English language. This will throw
// an exception if it cannot load. If it does, then we use it.
var englishUnitedStates = new LanguageConfig
{
LanguageCode = "en_US",
HunspellAffFile = affixFilename,
HunspellDictFile = dictionaryFilename,
HunspellKey = string.Empty
};
SpellEngine.AddLanguage(englishUnitedStates);
// If we got this far, set the project plugin to the one that
// uses the SpellEngine from NHunspell.
projectPlugin = new SpellEngineSpellingProjectPlugin(this);
return;
}
catch (Exception exception)
{
// Report that we can't load the first attempt.
Console.WriteLine("Cannot load NHunspell: " + exception);
}
// If we got this far, we couldn't load the NHunspell plugin.
// Attempt to load in the PInvoke implementation instead.
try
{
// Create a new Hunspell P/Invoke loader.
var pinvokePlugin = new PInvokeSpellingProjectPlugin(
affixFilename, dictionaryFilename);
projectPlugin = pinvokePlugin;
}
catch (Exception exception)
{
// Report that we can't load the first attempt.
Console.WriteLine("Cannot load NHunspell via P/Invoke: " + exception);
}
}
#endregion
#region Fields
private readonly CommonSpellingProjectPlugin projectPlugin;
private static readonly string[] searchPaths;
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Dedications;
using Gtk;
namespace AuthorIntrusion.Gui.GtkGui
{
/// <summary>
/// The about window which includes a display of the dedication and information
/// </summary>
public class AboutWindow: Dialog
{
#region Methods
private void CreateGui(
string programName,
Dedication dedication)
{
// Create the title and version labels.
var programLabel = new Label
{
Markup = "<b><span size='100'>" + programName + "</span></b>"
};
var versionLabel = new Label
{
Markup = "<b><span size='80'>" + dedication.Version + "</span></b>"
};
var authorLabel = new Label
{
Markup = "<b><span size='80'>" + dedication.Author + "</span></b>"
};
// Set up the dedication text.
string html = string.Join("\n", dedication.Lines);
string text = html + "- " + dedication.Dedicator;
// Create an HTML display widget with the text.
var dedicationView = new TextView
{
Buffer =
{
Text = text
},
WrapMode = WrapMode.Word,
PixelsBelowLines = 10,
RightMargin = 8,
LeftMargin = 4,
Justification = Justification.Fill,
Sensitive = false,
};
var dedicatorTag = new TextTag("dedicator");
dedicatorTag.Style = Pango.Style.Italic;
dedicatorTag.Justification = Justification.Right;
dedicationView.Buffer.TagTable.Add(dedicatorTag);
TextIter dedicatorIterBegin =
dedicationView.Buffer.GetIterAtOffset(html.Length);
TextIter dedicatorIterEnd = dedicationView.Buffer.GetIterAtOffset(
text.Length);
dedicationView.Buffer.ApplyTag(
dedicatorTag, dedicatorIterBegin, dedicatorIterEnd);
// Wrap it in a scroll window with some additional spacing.
var dedicationScroll = new ScrolledWindow
{
BorderWidth = 4
};
dedicationScroll.Add(dedicationView);
// Create the notebook we'll be using for the larger text tabs.
var notebook = new Notebook();
notebook.SetSizeRequest(512, 256);
notebook.BorderWidth = 4;
notebook.AppendPage(dedicationScroll, new Label("Dedication"));
// Arrange everything in the vertical box.
VBox.PackStart(programLabel, false, false, 4);
VBox.PackStart(versionLabel, false, false, 4);
VBox.PackStart(authorLabel, false, false, 4);
VBox.PackStart(notebook, true, true, 4);
// Set up the buttons.
Modal = true;
AddButton("Close", ResponseType.Close);
}
#endregion
#region Constructors
public AboutWindow()
{
// Pull out some useful variables.
var dedicationManager = new DedicationManager();
Dedication dedication = dedicationManager.CurrentDedication;
// Set the title to the longer title with the program name.
const string programName = "Author Intrusion";
const string windowTitle = "About " + programName;
Title = windowTitle;
// Create the rest of the GUI.
CreateGui(programName, dedication);
ShowAll();
// Version = dedication.ToString();
// Comments = dedication.Html;
// Copyright = "2013, Moonfire Games";
// License = @"Copyright (c) 2013, Moonfire Games
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the ""Software""), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.";
// Authors = new[]
// {
// "<NAME>"
// };
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Plugins;
namespace AuthorIntrusion.Plugins.BlockStructure
{
/// <summary>
/// A project plugin for creating a relationship between blocks within a
/// document.
/// </summary>
public class BlockStructureProjectPlugin: IProjectPlugin
{
#region Properties
public string Key
{
get { return "Block Structure"; }
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Xml;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Plugins;
using MfGames.HierarchicalPaths;
namespace AuthorIntrusion.Common.Persistence.Filesystem
{
/// <summary>
/// A XML-based Writer for the content data part of a project, either as a
/// separate file or as part of the project file itself.
/// </summary>
public class FilesystemPersistenceContentDataWriter:
PersistenceReaderWriterBase<FilesystemPersistenceSettings>
{
#region Methods
/// <summary>
/// Writes the content file, to either the project Writer or the Structure
/// file depending on the persistence settings.
/// </summary>
/// <param name="projectWriter">The project Writer.</param>
public void Write(XmlWriter projectWriter)
{
// Figure out which Writer we'll be using.
bool createdWriter;
XmlWriter writer = GetXmlWriter(
projectWriter, Macros, Settings.ContentDataFilename, out createdWriter);
// Start by creating the initial element.
writer.WriteStartElement("content-data", ProjectNamespace);
writer.WriteElementString("version", "1");
// Write out the project properties.
writer.WriteStartElement("project", ProjectNamespace);
WriteProperties(writer, Project);
writer.WriteEndElement();
// Go through the blocks in the list.
ProjectBlockCollection blocks = Project.Blocks;
for (int blockIndex = 0;
blockIndex < blocks.Count;
blockIndex++)
{
// Write out this block.
Block block = blocks[blockIndex];
writer.WriteStartElement("block-data", ProjectNamespace);
// Write out the text of the block so we can identify it later. It
// normally will be in order, but this is a second verification
// that won't change.
writer.WriteStartElement("block-key", ProjectNamespace);
writer.WriteAttributeString(
"block-index", blockIndex.ToString(CultureInfo.InvariantCulture));
writer.WriteAttributeString(
"text-hash", block.Text.GetHashCode().ToString("X8"));
writer.WriteEndElement();
// For this pass, we write out the data generates by the plugins
// and internal state.
WriteProperties(writer, block);
WriteAnalysisState(writer, block);
WriteTextSpans(writer, block);
// Finish up the block.
writer.WriteEndElement();
}
// Finish up the blocks element.
writer.WriteEndElement();
// If we created the Writer, close it.
if (createdWriter)
{
writer.Dispose();
}
}
/// <summary>
/// Writes the state of the analyzer plugins for this block. This will
/// prevent the block from being being re-analyzed once it is read in.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="block">The block.</param>
private void WriteAnalysisState(
XmlWriter writer,
Block block)
{
// If we don't have properties, then don't write out anything.
HashSet<IBlockAnalyzerProjectPlugin> analyzers = block.GetAnalysis();
if (analyzers.Count <= 0)
{
return;
}
// We always have to produce a consistent order for the list.
List<string> analyzerKeys = analyzers.Select(plugin => plugin.Key).ToList();
analyzerKeys.Sort();
// Write out the start element for the analyzers list.
writer.WriteStartElement("analyzers", ProjectNamespace);
// Write out each element.
foreach (string key in analyzerKeys)
{
writer.WriteElementString("analyzer", ProjectNamespace, key);
}
// Finish up the analyzers element.
writer.WriteEndElement();
}
/// <summary>
/// Writes out the block properties of a block.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="propertiesContainer">The block.</param>
private static void WriteProperties(
XmlWriter writer,
IPropertiesContainer propertiesContainer)
{
// If we don't have properties, then don't write out anything.
if (propertiesContainer.Properties.Count <= 0)
{
return;
}
// Write out the start element for the properties list.
writer.WriteStartElement("properties", ProjectNamespace);
// Go through all the properties, in order, and write it out.
var propertyPaths = new List<HierarchicalPath>();
propertyPaths.AddRange(propertiesContainer.Properties.Keys);
propertyPaths.Sort();
foreach (HierarchicalPath propertyPath in propertyPaths)
{
writer.WriteStartElement("property");
writer.WriteAttributeString("path", propertyPath.ToString());
writer.WriteString(propertiesContainer.Properties[propertyPath]);
writer.WriteEndElement();
}
// Finish up the properties element.
writer.WriteEndElement();
}
/// <summary>
/// Writes the text spans of a block.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="block">The block.</param>
private static void WriteTextSpans(
XmlWriter writer,
Block block)
{
// If we don't have spans, then skip them.
if (block.TextSpans.Count <= 0)
{
return;
}
// Write out the text spans.
writer.WriteStartElement("text-spans", ProjectNamespace);
foreach (TextSpan textSpan in block.TextSpans)
{
// Write out the beginning of the text span element.
writer.WriteStartElement("text-span", ProjectNamespace);
// Write out the common elements.
writer.WriteStartElement("index", ProjectNamespace);
writer.WriteAttributeString(
"start", textSpan.StartTextIndex.ToString(CultureInfo.InvariantCulture));
writer.WriteAttributeString(
"stop", textSpan.StopTextIndex.ToString(CultureInfo.InvariantCulture));
writer.WriteEndElement();
// If we have an associated controller, we need to write it out and
// it's data. Since we don't know how to write it out, we pass the
// writing to the controller.
if (textSpan.Controller != null)
{
// Write out the name of the controller.
writer.WriteElementString(
"plugin", ProjectNamespace, textSpan.Controller.Key);
// If we have data, then write out the plugin data tag and pass
// the writing to the controller.
if (textSpan.Data != null)
{
writer.WriteStartElement("plugin-data", ProjectNamespace);
textSpan.Controller.WriteTextSpanData(writer, textSpan.Data);
writer.WriteEndElement();
}
}
// Finish up the tag.
writer.WriteEndElement();
}
writer.WriteEndElement();
}
#endregion
#region Constructors
public FilesystemPersistenceContentDataWriter(
PersistenceReaderWriterBase<FilesystemPersistenceSettings> baseWriter)
: base(baseWriter)
{
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
namespace AuthorIntrusion.Common.Tests
{
public class BlockOperationReporter
{
#region Methods
public void Register(ProjectBlockCollection ownerCollection)
{
//ownerCollection.ItemsAdded += OnItemsAdded;
//ownerCollection.ItemsRemoved += OnItemsRemoved;
//ownerCollection.ItemRemovedAt += OnItemRemovedAt;
//ownerCollection.ItemInserted += OnItemInserted;
//ownerCollection.CollectionCleared += OnCollectionCleared;
//ownerCollection.CollectionChanged += OnCollectionChanged;
}
#endregion
//private void OnCollectionChanged(object sender)
//{
// Console.WriteLine("Blocks.CollectionChanged");
//}
//private void OnCollectionCleared(
// object sender,
// ClearedEventArgs eventargs)
//{
// Console.WriteLine("Blocks.CollectionCleared: " + eventargs.Count + " items");
//}
//private void OnItemInserted(
// object sender,
// ItemAtEventArgs<Block> eventargs)
//{
// Console.WriteLine(
// "Blocks.ItemInserted: {0} @{1}", eventargs.Index, eventargs.Item);
//}
//private void OnItemRemovedAt(
// object sender,
// ItemAtEventArgs<Block> eventargs)
//{
// Console.WriteLine(
// "Blocks.ItemRemoved: {0} @ {1}", eventargs.Index, eventargs.Item);
//}
//private void OnItemsAdded(
// object sender,
// ItemCountEventArgs<Block> args)
//{
// Console.WriteLine("Blocks.ItemAdded: " + args.Item);
//}
//private void OnItemsRemoved(
// object sender,
// ItemCountEventArgs<Block> eventargs)
//{
// Console.WriteLine("Blocks.ItemsRemoved: {0}", eventargs.Count);
//}
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
namespace AuthorIntrusion.Common.Commands
{
public class BlockCommandContext
{
#region Properties
/// <summary>
/// Contains the blocks associated with the project.
/// </summary>
public ProjectBlockCollection Blocks
{
get { return Project.Blocks; }
}
public BlockPosition? Position { get; set; }
/// <summary>
/// Contains the project associated with this context.
/// </summary>
public Project Project { get; private set; }
#endregion
#region Constructors
public BlockCommandContext(Project project)
{
Project = project;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
using MfGames.Commands.TextEditing;
namespace AuthorIntrusion.Common.Extensions
{
public static class SingleLineTextRangeExtensions
{
#region Methods
public static void GetBeginAndEndCharacterIndices(
this SingleLineTextRange range,
ProjectBlockCollection blocks,
out int blockIndex,
out int sourceBegin,
out int sourceEnd)
{
string text;
GetBeginAndEndCharacterIndices(
range, blocks, out blockIndex, out sourceBegin, out sourceEnd, out text);
}
public static void GetBeginAndEndCharacterIndices(
this SingleLineTextRange range,
ProjectBlockCollection blocks,
out int blockIndex,
out int sourceBegin,
out int sourceEnd,
out string text)
{
using (blocks.AcquireLock(RequestLock.Read))
{
// Start by getting the block based on the index.
Block block;
blockIndex = range.LinePosition.GetLineIndex(blocks.Count);
using (
blocks.AcquireBlockLock(
RequestLock.Read, RequestLock.Read, blockIndex, out block))
{
// Get the text and calculate the character indicies.
text = block.Text;
range.GetBeginAndEndCharacterIndices(text, out sourceBegin, out sourceEnd);
}
}
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Collections.Generic;
using System.Linq;
namespace AuthorIntrusion.Common.Blocks
{
/// <summary>
/// A specialized collection to manage Block objects in memory.
/// </summary>
public class BlockCollection: List<Block>
{
#region Properties
public Block this[BlockKey blockKey]
{
get
{
foreach (Block block in this.Where(block => block.BlockKey == blockKey))
{
return block;
}
throw new IndexOutOfRangeException("Cannot find block " + blockKey);
}
}
#endregion
#region Events
/// <summary>
/// Occurs when the collection changes.
/// </summary>
public event EventHandler<EventArgs> CollectionChanged;
#endregion
#region Methods
/// <summary>
/// Adds the specified block to the collection.
/// </summary>
/// <param name="block">The block.</param>
public new void Add(Block block)
{
base.Add(block);
RaiseCollectionChanged();
}
/// <summary>
/// Finds the index of a given block key.
/// </summary>
/// <param name="blockKey">The block key to look it up.</param>
/// <returns>The index of the position.</returns>
public int IndexOf(BlockKey blockKey)
{
Block block = this[blockKey];
int index = IndexOf(block);
return index;
}
public new void Insert(
int index,
Block block)
{
base.Insert(index, block);
RaiseCollectionChanged();
}
public new void Remove(Block block)
{
base.Remove(block);
RaiseCollectionChanged();
}
public new void RemoveAt(int index)
{
base.RemoveAt(index);
RaiseCollectionChanged();
}
private void RaiseCollectionChanged()
{
EventHandler<EventArgs> listeners = CollectionChanged;
if (listeners != null)
{
listeners(this, EventArgs.Empty);
}
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Xml;
using AuthorIntrusion.Common.Blocks;
namespace AuthorIntrusion.Common.Persistence.Filesystem
{
/// <summary>
/// A XML-based reader for the content part of a project, either as a separate
/// file or as part of the project file itself.
/// </summary>
public class FilesystemPersistenceContentReader:
PersistenceReaderWriterBase<FilesystemPersistenceSettings>
{
#region Methods
/// <summary>
/// Reads the content file, either from the project reader or the Structure
/// file depending on the persistence settings.
/// </summary>
/// <param name="projectReader">The project reader.</param>
public void Read(XmlReader projectReader)
{
// Figure out which reader we'll be using.
bool createdReader;
XmlReader reader = GetXmlReader(
projectReader, Settings.ContentFilename, out createdReader);
// Loop through the resulting file until we get to the end of the
// XML element we care about.
ProjectBlockCollection blocks = Project.Blocks;
bool reachedContents = reader.NamespaceURI == XmlConstants.ProjectNamespace
&& reader.LocalName == "content";
string text = null;
BlockType blockType = null;
bool firstBlock = true;
while (reader.Read())
{
// Ignore anything outside of our namespace.
if (reader.NamespaceURI != XmlConstants.ProjectNamespace)
{
continue;
}
// Check to see if we're done reading.
if (reader.NodeType == XmlNodeType.EndElement)
{
switch (reader.LocalName)
{
case "content":
return;
case "block":
// Create the block and insert it into the list.
var block = new Block(blocks, blockType, text);
if (firstBlock)
{
// Because we have a rule that the collection may
// not have less than one block, the first block is
// a replacement instead of adding to the list.
blocks[0] = block;
firstBlock = false;
}
else
{
blocks.Add(block);
}
break;
}
}
// For the rest of this loop, we only deal with begin elements.
if (reader.NodeType != XmlNodeType.Element)
{
continue;
}
// If we haven't reached the Structure, we just cycle through the XML.
if (!reachedContents)
{
// Flip the flag if we are starting to read the Structure.
if (reader.NamespaceURI == XmlConstants.ProjectNamespace
&& reader.LocalName == "content")
{
reachedContents = true;
}
// Continue on since we're done with this if clause.
continue;
}
// We process the remaining elements based on their local name.
switch (reader.LocalName)
{
case "type":
string blockTypeName = reader.ReadString();
blockType = Project.BlockTypes[blockTypeName];
break;
case "text":
text = reader.ReadString();
break;
}
}
// If we created the reader, close it.
if (createdReader)
{
reader.Close();
reader.Dispose();
}
}
#endregion
#region Constructors
public FilesystemPersistenceContentReader(
PersistenceReaderWriterBase<FilesystemPersistenceSettings> baseReader)
: base(baseReader)
{
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using MfGames.Settings;
namespace AuthorIntrusion.Common.Projects
{
/// <summary>
/// Contains a settings, either project or external, along with naming and
/// versioning information.
/// </summary>
public class ProjectSettings: SettingsManager
{
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Collections.Generic;
using MfGames.Conversion;
using MfGames.HierarchicalPaths;
namespace AuthorIntrusion.Common.Blocks
{
/// <summary>
/// Implements a dictionary of properties to be assigned to a block or
/// project.
/// </summary>
public class PropertiesDictionary: Dictionary<HierarchicalPath, string>
{
#region Methods
/// <summary>
/// Either adds a value to an existing key or adds a new one.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="amount">The amount.</param>
/// <exception cref="System.NotImplementedException"></exception>
public void AdditionOrAdd(
HierarchicalPath path,
int amount)
{
if (ContainsKey(path))
{
int value = Convert.ToInt32(this[path]);
this[path] = Convert.ToString(value + amount);
}
else
{
this[path] = Convert.ToString(amount);
}
}
public TResult Get<TResult>(HierarchicalPath path)
{
string value = this[path];
TResult result = ExtendableConvert.Instance.Convert<string, TResult>(value);
return result;
}
public TResult Get<TResult>(
string path,
HierarchicalPath rootPath = null)
{
var key = new HierarchicalPath(path, rootPath);
var results = Get<TResult>(key);
return results;
}
/// <summary>
/// Gets the value at the path, or the default if the item is not a stored
/// property.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="path">The path.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>Either the converted value or the default value.</returns>
public TResult GetOrDefault<TResult>(
HierarchicalPath path,
TResult defaultValue)
{
return ContainsKey(path)
? Get<TResult>(path)
: defaultValue;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moon<NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using AuthorIntrusion.Common.Actions;
using AuthorIntrusion.Common.Plugins;
using MfGames.Enumerations;
namespace AuthorIntrusion.Plugins.Spelling.Common
{
/// <summary>
/// Defines the signature for a controller that provides spell checking and
/// suggestions.
/// </summary>
public interface ISpellingProjectPlugin
{
#region Properties
/// <summary>
/// Gets or sets the block analyzer used for updating analysis.
/// </summary>
IBlockAnalyzerProjectPlugin BlockAnalyzer { get; set; }
/// <summary>
/// Gets or sets the overall weight of the spelling control and its
/// suggestions.
/// </summary>
Importance Weight { get; set; }
#endregion
#region Methods
/// <summary>
/// Gets the additional editor actions for the spelling.
/// </summary>
/// <param name="word">The word that is being processed.</param>
/// <returns>An enumerable of editor actions.</returns>
IEnumerable<IEditorAction> GetAdditionalEditorActions(string word);
/// <summary>
/// Gets a list of suggestions for the given word.
/// </summary>
/// <param name="word">The word to get suggestions for.</param>
/// <returns>A list of <see cref="SpellingSuggestion">suggestions</see>.</returns>
IEnumerable<SpellingSuggestion> GetSuggestions(string word);
/// <summary>
/// Determines whether the specified word is correct.
/// </summary>
/// <param name="word">The word.</param>
/// <returns>
/// <c>true</c> if the specified word is correct; otherwise, <c>false</c>.
/// </returns>
WordCorrectness IsCorrect(string word);
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Commands;
using NUnit.Framework;
namespace AuthorIntrusion.Common.Tests
{
[TestFixture]
public class InsertMultilineTextCommandTests: CommonMultilineTests
{
#region Methods
[Test]
public void LastLineTestCommand()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
BlockTypeSupervisor blockTypes;
BlockCommandContext context;
SetupMultilineTest(out context, out blocks, out blockTypes, out commands);
// Act
var command =
new InsertMultilineTextCommand(
new BlockPosition(blocks[3].BlockKey, 6), "AAA\nBBB\nCCC");
commands.Do(command, context);
// Assert
Assert.AreEqual(6, blocks.Count);
Assert.AreEqual(new BlockPosition(blocks[5], 3), commands.LastPosition);
int index = 0;
Assert.AreEqual("Line 1", blocks[index].Text);
Assert.AreEqual(blockTypes.Chapter, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 2", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 3", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 4AAA", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
index++;
Assert.AreEqual("BBB", blocks[index].Text);
Assert.AreEqual(blockTypes.Paragraph, blocks[index].BlockType);
index++;
Assert.AreEqual("CCC", blocks[index].Text);
Assert.AreEqual(blockTypes.Paragraph, blocks[index].BlockType);
}
[Test]
public void LastLineTestUndoCommand()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
BlockTypeSupervisor blockTypes;
BlockCommandContext context;
SetupMultilineTest(out context, out blocks, out blockTypes, out commands);
var command =
new InsertMultilineTextCommand(
new BlockPosition(blocks[3].BlockKey, 5), "AAA\nBBB\nCCC");
commands.Do(command, context);
// Act
commands.Undo(context);
// Assert
Assert.AreEqual(4, blocks.Count);
Assert.AreEqual(new BlockPosition(blocks[3], 5), commands.LastPosition);
int index = 0;
Assert.AreEqual("Line 1", blocks[index].Text);
Assert.AreEqual(blockTypes.Chapter, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 2", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 3", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 4", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
}
[Test]
public void LastLineTestUndoRedoCommand()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
BlockTypeSupervisor blockTypes;
BlockCommandContext context;
SetupMultilineTest(out context, out blocks, out blockTypes, out commands);
var command =
new InsertMultilineTextCommand(
new BlockPosition(blocks[3].BlockKey, 6), "AAA\nBBB\nCCC");
commands.Do(command, context);
commands.Undo(context);
// Act
commands.Redo(context);
// Assert
Assert.AreEqual(6, blocks.Count);
Assert.AreEqual(new BlockPosition(blocks[5], 3), commands.LastPosition);
int index = 0;
Assert.AreEqual("Line 1", blocks[index].Text);
Assert.AreEqual(blockTypes.Chapter, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 2", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 3", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 4AAA", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
index++;
Assert.AreEqual("BBB", blocks[index].Text);
Assert.AreEqual(blockTypes.Paragraph, blocks[index].BlockType);
index++;
Assert.AreEqual("CCC", blocks[index].Text);
Assert.AreEqual(blockTypes.Paragraph, blocks[index].BlockType);
}
[Test]
public void LastLineTestUndoRedoUndoCommand()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
BlockTypeSupervisor blockTypes;
BlockCommandContext context;
SetupMultilineTest(out context, out blocks, out blockTypes, out commands);
var command =
new InsertMultilineTextCommand(
new BlockPosition(blocks[3].BlockKey, 5), "AAA\nBBB\nCCC");
commands.Do(command, context);
commands.Undo(context);
commands.Redo(context);
// Act
commands.Undo(context);
// Assert
Assert.AreEqual(4, blocks.Count);
Assert.AreEqual(new BlockPosition(blocks[3], 5), commands.LastPosition);
int index = 0;
Assert.AreEqual("Line 1", blocks[index].Text);
Assert.AreEqual(blockTypes.Chapter, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 2", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 3", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 4", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
}
[Test]
public void TestCommand()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
BlockTypeSupervisor blockTypes;
BlockCommandContext context;
SetupMultilineTest(out context, out blocks, out blockTypes, out commands);
// Act
var command =
new InsertMultilineTextCommand(
new BlockPosition(blocks[0].BlockKey, 5), "AAA\nBBB\nCCC");
commands.Do(command, context);
// Assert
Assert.AreEqual(6, blocks.Count);
Assert.AreEqual(new BlockPosition(blocks[2], 3), commands.LastPosition);
int index = 0;
Assert.AreEqual("Line AAA", blocks[index].Text);
Assert.AreEqual(blockTypes.Chapter, blocks[index].BlockType);
index++;
Assert.AreEqual("BBB", blocks[index].Text);
Assert.AreEqual(blockTypes.Paragraph, blocks[index].BlockType);
index++;
Assert.AreEqual("CCC1", blocks[index].Text);
Assert.AreEqual(blockTypes.Paragraph, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 2", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 3", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 4", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
}
[Test]
public void TestUndoCommand()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
BlockTypeSupervisor blockTypes;
BlockCommandContext context;
SetupMultilineTest(out context, out blocks, out blockTypes, out commands);
var command =
new InsertMultilineTextCommand(
new BlockPosition(blocks[0].BlockKey, 5), "AAA\nBBB\nCCC");
commands.Do(command, context);
// Act
commands.Undo(context);
// Assert
Assert.AreEqual(4, blocks.Count);
Assert.AreEqual(new BlockPosition(blocks[0], 5), commands.LastPosition);
int index = 0;
Assert.AreEqual("Line 1", blocks[index].Text);
Assert.AreEqual(blockTypes.Chapter, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 2", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 3", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 4", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
}
[Test]
public void TestUndoRedoCommand()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
BlockTypeSupervisor blockTypes;
BlockCommandContext context;
SetupMultilineTest(out context, out blocks, out blockTypes, out commands);
var command =
new InsertMultilineTextCommand(
new BlockPosition(blocks[0].BlockKey, 5), "AAA\nBBB\nCCC");
commands.Do(command, context);
commands.Undo(context);
// Act
commands.Redo(context);
// Assert
Assert.AreEqual(6, blocks.Count);
Assert.AreEqual(new BlockPosition(blocks[2], 3), commands.LastPosition);
int index = 0;
Assert.AreEqual("Line AAA", blocks[index].Text);
Assert.AreEqual(blockTypes.Chapter, blocks[index].BlockType);
index++;
Assert.AreEqual("BBB", blocks[index].Text);
Assert.AreEqual(blockTypes.Paragraph, blocks[index].BlockType);
index++;
Assert.AreEqual("CCC1", blocks[index].Text);
Assert.AreEqual(blockTypes.Paragraph, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 2", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 3", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 4", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
}
[Test]
public void TestUndoRedoUndoCommand()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
BlockTypeSupervisor blockTypes;
BlockCommandContext context;
SetupMultilineTest(out context, out blocks, out blockTypes, out commands);
var command =
new InsertMultilineTextCommand(
new BlockPosition(blocks[0].BlockKey, 5), "AAA\nBBB\nCCC");
commands.Do(command, context);
commands.Undo(context);
commands.Redo(context);
// Act
commands.Undo(context);
// Assert
Assert.AreEqual(4, blocks.Count);
Assert.AreEqual(new BlockPosition(blocks[0], 5), commands.LastPosition);
int index = 0;
Assert.AreEqual("Line 1", blocks[index].Text);
Assert.AreEqual(blockTypes.Chapter, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 2", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 3", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
index++;
Assert.AreEqual("Line 4", blocks[index].Text);
Assert.AreEqual(blockTypes.Scene, blocks[index].BlockType);
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Mo<NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
namespace AuthorIntrusion.Common
{
public interface IPropertiesContainer
{
#region Properties
/// <summary>
/// Gets the properties associated with the block.
/// </summary>
PropertiesDictionary Properties { get; }
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Runtime.InteropServices;
namespace AuthorIntrusion.Plugins.Spelling.NHunspell.Interop
{
/// <summary>
/// Encapsulates an Hunspell handle.
/// </summary>
internal sealed class HunspellHandle: SafeHandle
{
#region Properties
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
#endregion
#region Methods
protected override bool ReleaseHandle()
{
HunspellInterop.Hunspell_destroy(this);
return true;
}
#endregion
#region P/Invokes
#endregion
#region Constructors
public HunspellHandle()
: base(IntPtr.Zero, false)
{
}
public HunspellHandle(
string affpath,
string dicpath)
: base(IntPtr.Zero, true)
{
handle = HunspellInterop.Hunspell_create(affpath, dicpath);
if (IsInvalid)
{
throw new InvalidOperationException("Couldn't load hunspell.");
}
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Collections.Generic;
using AuthorIntrusion.Common.Actions;
using AuthorIntrusion.Common.Plugins;
using AuthorIntrusion.Plugins.Spelling.Common;
using MfGames.Enumerations;
namespace AuthorIntrusion.Plugins.Spelling.NHunspell
{
/// <summary>
/// Contains the common project plugin settings for the Hunspell spelling.
/// There are multiple versions of this, based on how and if it can be
/// loaded.
/// </summary>
public abstract class CommonSpellingProjectPlugin: IProjectPlugin,
ISpellingProjectPlugin
{
#region Properties
public IBlockAnalyzerProjectPlugin BlockAnalyzer { get; set; }
public string Key
{
get { return "Hunspell"; }
}
public Importance Weight { get; set; }
#endregion
#region Methods
public IEnumerable<IEditorAction> GetAdditionalEditorActions(string word)
{
return new IEditorAction[]
{
};
}
public virtual IEnumerable<SpellingSuggestion> GetSuggestions(string word)
{
throw new NotImplementedException();
}
public virtual WordCorrectness IsCorrect(string word)
{
throw new NotImplementedException();
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
using MfGames.Commands;
namespace AuthorIntrusion.Common.Commands
{
/// <summary>
/// A command intended to be used as a deferred command to mass change multiple
/// block types in a single request.
/// </summary>
public class ChangeMultipleBlockTypesCommand: IBlockCommand
{
#region Properties
public bool CanUndo
{
get { return true; }
}
/// <summary>
/// Gets the list of changes to block keys and their new types.
/// </summary>
public Dictionary<BlockKey, BlockType> Changes { get; private set; }
public bool IsTransient
{
get { return false; }
}
public DoTypes UpdateTextPosition { get; set; }
#endregion
#region Methods
public void Do(BlockCommandContext context)
{
// Since we're making chanegs to the list, we need a write lock.
ProjectBlockCollection blocks = context.Blocks;
using (blocks.AcquireLock(RequestLock.Write))
{
// Clear out the undo list since we'll be rebuilding it.
previousBlockTypes.Clear();
// Go through all the blocks in the project.
foreach (Block block in blocks)
{
if (Changes.ContainsKey(block.BlockKey))
{
BlockType blockType = Changes[block.BlockKey];
BlockType existingType = block.BlockType;
previousBlockTypes[block.BlockKey] = existingType;
block.SetBlockType(blockType);
}
}
}
}
public void Redo(BlockCommandContext context)
{
Do(context);
}
public void Undo(BlockCommandContext context)
{
// Since we're making chanegs to the list, we need a write lock.
ProjectBlockCollection blocks = context.Blocks;
using (blocks.AcquireLock(RequestLock.Write))
{
// Go through all the blocks in the project.
foreach (Block block in blocks)
{
if (Changes.ContainsKey(block.BlockKey))
{
// Revert the type of this block.
BlockType blockType = previousBlockTypes[block.BlockKey];
block.SetBlockType(blockType);
}
}
}
}
#endregion
#region Constructors
public ChangeMultipleBlockTypesCommand()
{
Changes = new Dictionary<BlockKey, BlockType>();
previousBlockTypes = new Dictionary<BlockKey, BlockType>();
UpdateTextPosition = DoTypes.All;
}
#endregion
#region Fields
private readonly Dictionary<BlockKey, BlockType> previousBlockTypes;
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.IO;
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Events;
using AuthorIntrusion.Common.Persistence;
using AuthorIntrusion.Common.Plugins;
namespace AuthorIntrusion
{
/// <summary>
/// The project manager is a general manager for projects when used in a GUI
/// interface. It functions a single point of accessing a currently loaded
/// project, along with events to report the loading and unloading of projects.
/// It also manages the entry into project loading and saving.
/// </summary>
public class ProjectManager
{
#region Properties
/// <summary>
/// Gets a value indicating whether this instance has a loaded project.
/// </summary>
/// <value>
/// <c>true</c> if this instance has a loaded project; otherwise, <c>false</c>.
/// </value>
public bool HasLoadedProject
{
get { return Project != null; }
}
/// <summary>
/// Gets the currently loaded project. This will be null if there are no
/// projects loaded.
/// </summary>
public Project Project { get; private set; }
/// <summary>
/// The file of the currently loaded project.
/// </summary>
protected FileInfo ProjectFile { get; private set; }
#endregion
#region Events
/// <summary>
/// Occurs when a project is loaded into the project manager.
/// </summary>
public event EventHandler<ProjectEventArgs> ProjectLoaded;
/// <summary>
/// Occurs when a project is unloaded from the project manager.
/// </summary>
public event EventHandler<ProjectEventArgs> ProjectUnloaded;
#endregion
#region Methods
/// <summary>
/// Closes the currently loaded project, if any.
/// </summary>
public void CloseProject()
{
SetProject(null);
ProjectFile = null;
}
/// <summary>
/// Opens the project from the given file and loads it into memory.
/// </summary>
/// <param name="projectFile">The project file.</param>
public void OpenProject(FileInfo projectFile)
{
// Get the filesystem plugin.
var plugin =
(FilesystemPersistencePlugin)
PluginManager.Instance.Get("Filesystem Persistence");
// Load the project and connect it.
Project project = plugin.ReadProject(projectFile);
SetProject(project);
ProjectFile = projectFile;
}
public void SaveProject()
{
if (HasLoadedProject)
{
// Get the filesystem plugin.
var plugin =
(FilesystemPersistenceProjectPlugin)
Project.Plugins["Filesystem Persistence"];
plugin.Settings.SetIndividualDirectoryLayout();
plugin.Settings.ProjectDirectory = ProjectFile.Directory.FullName;
// Save the project file.
plugin.Save(ProjectFile.Directory);
}
}
/// <summary>
/// Sets the project and fires the various events
/// </summary>
/// <param name="project">The project.</param>
public void SetProject(Project project)
{
// If the project is identical to the currently loaded one, we
// don't have to do anything nor do we want events loaded.
if (project == Project)
{
return;
}
// If we already had a project loaded, we need to unload it
// so the various listeners can handle the unloading (and
// interrupt it).
if (Project != null)
{
// Disconnect the project from the manager.
Project unloadedProject = Project;
Project = null;
// Raise the associated event.
RaiseProjectUnloaded(unloadedProject);
}
// If we have a new project, then load it and raise the appropriate
// event.
if (project != null)
{
// Set the new project in the manager.
Project = project;
// Raise the loaded event to listeners.
RaiseProjectLoaded(project);
}
}
/// <summary>
/// Raises the project loaded event
/// </summary>
/// <param name="project">The project.</param>
protected void RaiseProjectLoaded(Project project)
{
EventHandler<ProjectEventArgs> listeners = ProjectLoaded;
if (listeners != null)
{
var args = new ProjectEventArgs(project);
listeners(this, args);
}
}
/// <summary>
/// Raises the project is unloaded.
/// </summary>
/// <param name="project">The project.</param>
protected void RaiseProjectUnloaded(Project project)
{
EventHandler<ProjectEventArgs> listeners = ProjectUnloaded;
if (listeners != null)
{
var args = new ProjectEventArgs(project);
listeners(this, args);
}
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
using AuthorIntrusion.Common.Commands;
namespace AuthorIntrusion.Common.Tests
{
/// <summary>
/// Common functionality when running multiline unit tests.
/// </summary>
public abstract class CommonMultilineTests
{
#region Methods
protected void SetupComplexMultilineTest(
Project project,
int lineCount)
{
// Insert the bulk of the lines.
InsertLines(project, lineCount);
// Change the block types for the project. This basically builds up a
// structure of one chapter with any number of scenes that have one
// epigraph, one epigraph attribution, and two paragraphs.
BlockTypeSupervisor blockTypes = project.BlockTypes;
ProjectBlockCollection blocks = project.Blocks;
blocks[0].SetBlockType(blockTypes.Chapter);
for (int blockIndex = 1;
blockIndex < blocks.Count;
blockIndex++)
{
Block block = blocks[blockIndex];
if ((blockIndex - 1) % 5 == 0)
{
block.SetBlockType(blockTypes.Scene);
}
else if ((blockIndex - 2) % 5 == 0)
{
block.SetBlockType(blockTypes.Epigraph);
}
else if ((blockIndex - 3) % 5 == 0)
{
block.SetBlockType(blockTypes.EpigraphAttribution);
}
else
{
block.SetBlockType(blockTypes.Paragraph);
}
}
// Let everything finish running.
project.Plugins.WaitForBlockAnalzyers();
}
protected void SetupComplexMultilineTest(
out ProjectBlockCollection blocks,
out BlockTypeSupervisor blockTypes,
out BlockCommandSupervisor commands,
int lineCount = 10)
{
// Everything is based on the project.
var project = new Project();
blocks = project.Blocks;
commands = project.Commands;
blockTypes = project.BlockTypes;
// Set up the structure and insert the lines.
SetupComplexMultilineTest(project, lineCount);
}
/// <summary>
/// Creates a project with a set number of lines and gives them a state that
/// can easily be tested for.
/// </summary>
/// <param name="context"></param>
/// <param name="blocks">The block collection in the project.</param>
/// <param name="blockTypes">The block types supervisor for the project.</param>
/// <param name="commands">The commands supervisor for the project.</param>
/// <param name="lineCount">The number of blocks to insert into the projects.</param>
protected void SetupMultilineTest(
out BlockCommandContext context,
out ProjectBlockCollection blocks,
out BlockTypeSupervisor blockTypes,
out BlockCommandSupervisor commands,
int lineCount = 4)
{
// Everything is based on the project.
var project = new Project();
context = new BlockCommandContext(project);
blocks = project.Blocks;
commands = project.Commands;
blockTypes = project.BlockTypes;
// Insert the bulk of the lines.
InsertLines(project, lineCount);
// Go through and set up the block types for these elements.
project.Blocks[0].SetBlockType(blockTypes.Chapter);
for (int index = 1;
index < project.Blocks.Count;
index++)
{
project.Blocks[index].SetBlockType(blockTypes.Scene);
}
}
/// <summary>
/// Inserts the lines.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="lineCount">The line count.</param>
private void InsertLines(
Project project,
int lineCount)
{
// Pull out some useful variables.
ProjectBlockCollection blocks = project.Blocks;
// Modify the first line, which is always there.
using (blocks[0].AcquireBlockLock(RequestLock.Write))
{
blocks[0].SetText("Line 1");
}
// Add in the additional lines after the first one.
for (int i = 1;
i < lineCount;
i++)
{
var block = new Block(blocks);
using (block.AcquireBlockLock(RequestLock.Write))
{
block.SetText("Line " + (i + 1));
}
blocks.Add(block);
}
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Xml;
using MfGames.Settings;
namespace AuthorIntrusion.Common.Persistence.Filesystem
{
public class FilesystemPersistenceSettingsReader:
PersistenceReaderWriterBase<FilesystemPersistenceSettings>
{
#region Methods
/// <summary>
/// Reads the structure file, either from the project reader or the settings
/// file depending on the persistence settings.
/// </summary>
/// <param name="projectReader">The project reader.</param>
public void Read(XmlReader projectReader)
{
// Figure out which reader we'll be using.
bool createdReader;
XmlReader reader = GetXmlReader(
projectReader, Settings.SettingsFilename, out createdReader);
// Loop through the resulting file until we get to the end of the
// XML element we care about.
bool reachedSettings = reader.NamespaceURI == XmlConstants.ProjectNamespace
&& reader.LocalName == "settings";
while (reader.Read())
{
// If we get the full settings, then load it in.
if (reader.NamespaceURI == SettingsManager.SettingsNamespace
&& reader.LocalName == "settings")
{
Project.Settings.Load(reader);
continue;
}
// Ignore anything outside of our namespace.
if (reader.NamespaceURI != XmlConstants.ProjectNamespace)
{
continue;
}
// Check to see if we're done reading.
if (reader.NodeType == XmlNodeType.EndElement
&& reader.LocalName == "settings")
{
// We're done reading the settings.
break;
}
// For the rest of this loop, we only deal with begin elements.
if (reader.NodeType != XmlNodeType.Element)
{
continue;
}
// If we haven't reached the settings, we just cycle through the XML.
if (!reachedSettings)
{
// Flip the flag if we are starting to read the settings.
if (reader.NamespaceURI == XmlConstants.ProjectNamespace
&& reader.LocalName == "settings")
{
reachedSettings = true;
}
// Continue on since we're done with this if clause.
continue;
}
// We process the remaining elements based on their local name.
if (reader.LocalName == "plugin")
{
string value = reader.ReadString();
Project.Plugins.Add(value);
}
}
// If we created the reader, close it.
if (createdReader)
{
reader.Close();
reader.Dispose();
}
}
#endregion
#region Constructors
public FilesystemPersistenceSettingsReader(
PersistenceReaderWriterBase<FilesystemPersistenceSettings> baseReader)
: base(baseReader)
{
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using AuthorIntrusion.Common.Blocks;
using NUnit.Framework;
namespace AuthorIntrusion.Plugins.Spelling.Tests
{
[TestFixture]
public class SpellingWordSplitterTests
{
#region Methods
[Test]
public void SplitBlankString()
{
// Arrange
var splitter = new SpellingWordSplitter();
// Act
IList<TextSpan> words = splitter.SplitAndNormalize("");
// Assert
Assert.AreEqual(0, words.Count);
}
[Test]
public void SplitOneContractedWord()
{
// Arrange
var splitter = new SpellingWordSplitter();
const string input = "don't";
// Act
IList<TextSpan> words = splitter.SplitAndNormalize(input);
// Assert
Assert.AreEqual(1, words.Count);
Assert.AreEqual(input, words[0].GetText(input));
}
[Test]
public void SplitOneWord()
{
// Arrange
var splitter = new SpellingWordSplitter();
const string input = "one";
// Act
IList<TextSpan> words = splitter.SplitAndNormalize(input);
// Assert
Assert.AreEqual(1, words.Count);
Assert.AreEqual(input, words[0].GetText(input));
}
[Test]
public void SplitTwoWords()
{
// Arrange
var splitter = new SpellingWordSplitter();
const string input = "one two";
// Act
IList<TextSpan> words = splitter.SplitAndNormalize(input);
// Assert
Assert.AreEqual(2, words.Count);
Assert.AreEqual("one", words[0].GetText(input));
Assert.AreEqual("two", words[1].GetText(input));
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
using Cairo;
using MfGames.GtkExt;
using MfGames.GtkExt.TextEditor;
using MfGames.GtkExt.TextEditor.Models.Styles;
namespace AuthorIntrusion.Gui.GtkGui
{
public static class EditorViewTheme
{
#region Methods
/// <summary>
/// Sets up the theme elements.
/// </summary>
/// <param name="theme"></param>
public static void SetupTheme(Theme theme)
{
// Set up the indicator elements.
SetupThemeIndicators(theme);
// Use slightly more muted colors for the current line.
theme.RegionStyles["EditorViewCurrentLine"].BackgroundColor = new Color(
1, 1, 1);
theme.RegionStyles["EditorViewCurrentWrappedLine"].BackgroundColor =
new Color(245 / 255.0, 245 / 255.0, 220 / 255.0);
// Set up the paragraph style.
var paragraphyStyle = new LineBlockStyle(theme.TextLineStyle)
{
FontDescription =
FontDescriptionCache.GetFontDescription("Source Code Pro 16"),
Margins =
{
Top = 8,
Bottom = 8
}
};
// Set up the chapter style.
var chapterStyle = new LineBlockStyle(theme.TextLineStyle)
{
FontDescription =
FontDescriptionCache.GetFontDescription("Source Code Pro Bold 32"),
Margins =
{
Bottom = 5
},
Borders =
{
Bottom = new Border(2, new Color(0, 0, 0))
}
};
// Set up the scene style.
var sceneStyle = new LineBlockStyle(theme.TextLineStyle)
{
FontDescription =
FontDescriptionCache.GetFontDescription("Source Code Pro Italic 24"),
ForegroundColor = new Color(.5, .5, .5)
};
// Set up the epigraph style.
var epigraphStyle = new LineBlockStyle(theme.TextLineStyle)
{
FontDescription =
FontDescriptionCache.GetFontDescription("Source Code Pro 12"),
Padding =
{
Left = 20
}
};
// Set up the epigraph attributation style.
var epigraphAttributationStyle = new LineBlockStyle(theme.TextLineStyle)
{
FontDescription =
FontDescriptionCache.GetFontDescription("Source Code Pro Italic 12"),
Padding =
{
Left = 20
}
};
// Add all the styles into the theme.
theme.LineStyles[BlockTypeSupervisor.ParagraphName] = paragraphyStyle;
theme.LineStyles[BlockTypeSupervisor.ChapterName] = chapterStyle;
theme.LineStyles[BlockTypeSupervisor.SceneName] = sceneStyle;
theme.LineStyles[BlockTypeSupervisor.EpigraphName] = epigraphStyle;
theme.LineStyles[BlockTypeSupervisor.EpigraphAttributionName] =
epigraphAttributationStyle;
}
private static void SetupThemeIndicators(Theme theme)
{
// Set up the indicator styles.
theme.IndicatorRenderStyle = IndicatorRenderStyle.Ratio;
theme.IndicatorPixelHeight = 2;
theme.IndicatorRatioPixelGap = 1;
var indicatorBackgroundStyle = new RegionBlockStyle
{
//BackgroundColor = new Color(1, 0.9, 1)
};
var indicatorVisibleStyle = new RegionBlockStyle
{
BackgroundColor = new Color(1, 1, 0.9)
};
indicatorVisibleStyle.Borders.SetBorder(new Border(1, new Color(0, 0.5, 0)));
// Add the styles to the theme.
theme.RegionStyles[IndicatorView.BackgroundRegionName] =
indicatorBackgroundStyle;
theme.RegionStyles[IndicatorView.VisibleRegionName] = indicatorVisibleStyle;
// Set up the various indicators.
theme.IndicatorStyles["Error"] = new IndicatorStyle(
"Error", 100, new Color(1, 0, 0));
theme.IndicatorStyles["Warning"] = new IndicatorStyle(
"Warning", 10, new Color(1, 165 / 255.0, 0));
theme.IndicatorStyles["Chapter"] = new IndicatorStyle(
"Chapter", 2, new Color(100 / 255.0, 149 / 255.0, 237 / 255.0));
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
using AuthorIntrusion.Common.Commands;
using NUnit.Framework;
namespace AuthorIntrusion.Common.Tests
{
[TestFixture]
public class ReplaceTextBlockCommandTests
{
#region Methods
[Test]
public void TestCommand()
{
// Arrange
var project = new Project();
var context = new BlockCommandContext(project);
ProjectBlockCollection blocks = project.Blocks;
Block block = blocks[0];
using (block.AcquireBlockLock(RequestLock.Write))
{
block.SetText("abcd");
}
int blockVersion = block.Version;
BlockKey blockKey = block.BlockKey;
// Act
var command = new ReplaceTextCommand(
new BlockPosition(blockKey, 2), 1, "YES");
project.Commands.Do(command, context);
// Assert
Assert.AreEqual(1, blocks.Count);
Assert.AreEqual(
new BlockPosition(blocks[0], 5), project.Commands.LastPosition);
const int index = 0;
Assert.AreEqual("abYESd", blocks[index].Text);
Assert.AreEqual(blockVersion + 2, blocks[index].Version);
}
[Test]
public void TestUndoCommand()
{
// Arrange
var project = new Project();
var context = new BlockCommandContext(project);
ProjectBlockCollection blocks = project.Blocks;
Block block = blocks[0];
using (block.AcquireBlockLock(RequestLock.Write))
{
block.SetText("abcd");
}
int blockVersion = block.Version;
BlockKey blockKey = block.BlockKey;
var command = new ReplaceTextCommand(
new BlockPosition(blockKey, 2), 1, "YES");
project.Commands.Do(command, context);
// Act
project.Commands.Undo(context);
// Assert
Assert.AreEqual(1, blocks.Count);
Assert.AreEqual(
new BlockPosition(blocks[0], 3), project.Commands.LastPosition);
const int index = 0;
Assert.AreEqual("abcd", blocks[index].Text);
Assert.AreEqual(blockVersion + 4, blocks[index].Version);
}
[Test]
public void TestUndoRedoCommand()
{
// Arrange
var project = new Project();
var context = new BlockCommandContext(project);
ProjectBlockCollection blocks = project.Blocks;
Block block = blocks[0];
using (block.AcquireBlockLock(RequestLock.Write))
{
block.SetText("abcd");
}
int blockVersion = block.Version;
BlockKey blockKey = block.BlockKey;
var command = new ReplaceTextCommand(
new BlockPosition(blockKey, 2), 1, "YES");
project.Commands.Do(command, context);
project.Commands.Undo(context);
// Act
project.Commands.Redo(context);
// Assert
Assert.AreEqual(1, blocks.Count);
Assert.AreEqual(
new BlockPosition(blocks[0], 5), project.Commands.LastPosition);
const int index = 0;
Assert.AreEqual("abYESd", blocks[index].Text);
Assert.AreEqual(blockVersion + 6, blocks[index].Version);
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using AuthorIntrusion.Common.Commands;
using MfGames.Enumerations;
using MfGames.HierarchicalPaths;
namespace AuthorIntrusion.Common.Actions
{
public class EditorAction: IEditorAction
{
#region Properties
public string DisplayName { get; private set; }
public Importance Importance { get; private set; }
public HierarchicalPath ResourceKey { get; private set; }
private Action<BlockCommandContext> Action { get; set; }
#endregion
#region Methods
public void Do(BlockCommandContext context)
{
Action(context);
}
#endregion
#region Constructors
public EditorAction(
string displayName,
HierarchicalPath resourceKey,
Action<BlockCommandContext> action,
Importance importance = Importance.Normal)
{
DisplayName = displayName;
Importance = importance;
ResourceKey = resourceKey;
Action = action;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
using MfGames.Commands;
namespace AuthorIntrusion.Common.Commands
{
/// <summary>
/// An operation that sets the text for the entire block with no respect to
/// position or current state.
/// </summary>
public class SetTextCommand: SingleBlockKeyCommand
{
#region Properties
public string Text { get; private set; }
#endregion
#region Methods
protected override void Do(
BlockCommandContext context,
Block block)
{
previousText = block.Text;
block.SetText(Text);
if (UpdateTextPosition.HasFlag(DoTypes.Do))
{
context.Position = new BlockPosition(BlockKey, Text.Length);
}
}
protected override void Undo(
BlockCommandContext context,
Block block)
{
block.SetText(previousText);
if (UpdateTextPosition.HasFlag(DoTypes.Undo))
{
context.Position = new BlockPosition(BlockKey, previousText.Length);
}
}
#endregion
#region Constructors
public SetTextCommand(
BlockKey blockKey,
string text)
: base(blockKey)
{
Text = text;
}
#endregion
#region Fields
private string previousText;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
using MfGames.Commands;
using MfGames.Commands.TextEditing;
namespace AuthorIntrusion.Common.Commands
{
public class InsertIndexedBlockCommand: IBlockCommand
{
#region Properties
public Block Block { get; private set; }
public int BlockIndex { get; private set; }
public bool CanUndo
{
get { return true; }
}
public bool IsTransient
{
get { return false; }
}
public bool IsUndoable
{
get { return true; }
}
public BlockPosition LastPosition { get; private set; }
public DoTypes UpdateTextPosition { get; set; }
#endregion
#region Methods
public void Do(BlockCommandContext context)
{
// We need a write lock since we are making changes to the collection itself.
using (context.Blocks.AcquireLock(RequestLock.Write))
{
if (UpdateTextPosition.HasFlag(DoTypes.Undo))
{
previousPosition = context.Position;
}
context.Blocks.Insert(BlockIndex, Block);
// Set the position after the command.
if (UpdateTextPosition.HasFlag(DoTypes.Do))
{
context.Position = new BlockPosition(
Block.BlockKey, CharacterPosition.Begin);
}
}
}
public void Redo(BlockCommandContext context)
{
Do(context);
}
public void Undo(BlockCommandContext context)
{
// We need a write lock since we are making changes to the collection itself.
using (context.Blocks.AcquireLock(RequestLock.Write))
{
context.Blocks.Remove(Block);
// Set the position after the command.
if (UpdateTextPosition.HasFlag(DoTypes.Undo)
&& previousPosition.HasValue)
{
context.Position = previousPosition.Value;
}
}
}
#endregion
#region Constructors
public InsertIndexedBlockCommand(
int blockIndex,
Block block)
{
BlockIndex = blockIndex;
Block = block;
UpdateTextPosition = DoTypes.All;
}
#endregion
#region Fields
private BlockPosition? previousPosition;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.IO;
using System.Xml;
using AuthorIntrusion.Common.Projects;
namespace AuthorIntrusion.Common.Persistence.Filesystem
{
/// <summary>
/// Handles the persistence (reading and writing) of the primary project
/// files.
/// </summary>
public class FilesystemPersistenceProjectReader:
PersistenceReaderWriterBase<FilesystemPersistenceSettings>
{
#region Methods
/// <summary>
/// Reads the specified file and loads a project from it.
/// </summary>
/// <param name="projectFile">The project file.</param>
public void Read(FileInfo projectFile)
{
// Open up an XML stream for the project.
using (XmlReader reader = GetXmlReader(projectFile))
{
// We don't have to do anything initially with the project file.
// However, if the settings indicate that there is a file inside
// this one, we'll use this reader.
//
// The reading must be performed in the same order as writing.
// Read in the various components.
var settingsReader = new FilesystemPersistenceSettingsReader(this);
var structureReader = new FilesystemPersistenceStructureReader(this);
var contentReader = new FilesystemPersistenceContentReader(this);
var contentDataReader = new FilesystemPersistenceContentDataReader(this);
settingsReader.Read(reader);
structureReader.Read(reader);
contentReader.Read(reader);
contentDataReader.Read(reader);
// Close the file and stream.
reader.Close();
}
}
#endregion
#region Constructors
public FilesystemPersistenceProjectReader(
Project project,
FilesystemPersistenceSettings settings,
ProjectMacros macros)
: base(project, settings, macros)
{
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
using MfGames.Commands.TextEditing;
namespace AuthorIntrusion.Common.Commands
{
/// <summary>
/// Encapsulates the functionality for a command that takes a single block and
/// index (e.g., BlockPosition).
/// </summary>
public abstract class BlockPositionCommand: SingleBlockKeyCommand
{
#region Properties
/// <summary>
/// Gets the block position for this command.
/// </summary>
protected BlockPosition BlockPosition
{
get
{
var position = new BlockPosition(BlockKey, (CharacterPosition) TextIndex);
return position;
}
}
/// <summary>
/// Gets the index of the text operation.
/// </summary>
protected int TextIndex { get; private set; }
#endregion
#region Constructors
protected BlockPositionCommand(BlockPosition position)
: base(position.BlockKey)
{
TextIndex = (int) position.TextIndex;
}
protected BlockPositionCommand(TextPosition position)
: base(position.LinePosition)
{
TextIndex = (int) position.CharacterPosition;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using System.Xml;
using AuthorIntrusion.Common.Actions;
using AuthorIntrusion.Common.Blocks;
namespace AuthorIntrusion.Common.Plugins
{
/// <summary>
/// Describes the interface of a controller that controls and manages
/// <see cref="TextSpan"/> objects inside a block.
/// </summary>
public interface ITextControllerProjectPlugin: IProjectPlugin
{
#region Methods
/// <summary>
/// Gets the editor actions associated with the given TextSpan.
/// </summary>
/// <param name="block">The block.</param>
/// <param name="textSpan">The text span.</param>
/// <returns>
/// A list of editor actions associated with this span.
/// </returns>
/// <remarks>
/// This will be called within a read-only lock.
/// </remarks>
IList<IEditorAction> GetEditorActions(
Block block,
TextSpan textSpan);
/// <summary>
/// Writes out the data stored in a TextSpan created by this controller.
/// This will only be called if the text span data is not null and a wrapper
/// tag will already be started before this is called. It is also the
/// responsibility of the calling code to close the opened tag.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="data">The data.</param>
void WriteTextSpanData(
XmlWriter writer,
object data);
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Plugins;
namespace AuthorIntrusion.Plugins.BlockStructure
{
/// <summary>
/// Implements a project plugin provider that establishes a relationship
/// between the various blocks to create a structure of elements, such as
/// a book containing chapters containing paragraphs.
/// </summary>
public class BlockStructurePlugin: IProjectPluginProviderPlugin
{
#region Properties
public bool AllowMultiple
{
get { return false; }
}
public string Key
{
get { return "Block Structure"; }
}
#endregion
#region Methods
public IProjectPlugin GetProjectPlugin(Project project)
{
var projectPlugin = new BlockStructureProjectPlugin();
return projectPlugin;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
using AuthorIntrusion.Common.Commands;
using MfGames.Commands;
using MfGames.Commands.TextEditing;
using MfGames.GtkExt.TextEditor.Models;
using MfGames.GtkExt.TextEditor.Models.Buffers;
namespace AuthorIntrusion.Gui.GtkGui.Commands
{
/// <summary>
/// An adapter class that converts the editor view's controller commands into
/// the Author Intrusion command elements.
/// </summary>
public class ProjectCommandController: ICommandController<OperationContext>,
ITextEditingCommandController<OperationContext>
{
#region Properties
public bool CanRedo
{
get { return Commands.CanRedo; }
}
public bool CanUndo
{
get { return Commands.CanUndo; }
}
public BlockCommandSupervisor Commands
{
get { return Project.Commands; }
}
/// <summary>
/// Contains the currently loaded project for the controller.
/// </summary>
public Project Project { get; set; }
public ProjectLineBuffer ProjectLineBuffer { get; set; }
public OperationContext State { get; private set; }
#endregion
#region Methods
public IDeleteLineCommand<OperationContext> CreateDeleteLineCommand(
LinePosition line)
{
// Create the command adapter and return it.
var command = new ProjectDeleteLineCommand(ProjectLineBuffer, Project, line);
//Debug.WriteLine("CreateDeleteLineCommand: " + line);
return command;
}
public IDeleteTextCommand<OperationContext> CreateDeleteTextCommand(
SingleLineTextRange range)
{
// Create the command adapter and return it.
var command = new ProjectDeleteTextCommand(Project, range);
//Debug.WriteLine("CreateDeleteTextCommand: " + range);
return command;
}
public IInsertLineCommand<OperationContext> CreateInsertLineCommand(
LinePosition line)
{
// Create the command adapter and return it.
var command = new ProjectInsertLineCommand(ProjectLineBuffer, Project, line);
//Debug.WriteLine("CreateInsertLineCommand: " + line);
return command;
}
public IInsertTextCommand<OperationContext> CreateInsertTextCommand(
TextPosition textPosition,
string text)
{
// Create the command adapter and return it.
var command = new ProjectInsertTextCommand(Project, textPosition, text);
//Debug.WriteLine("CreateInsertTextCommand: " + textPosition + ", " + text);
return command;
}
public IInsertTextFromTextRangeCommand<OperationContext>
CreateInsertTextFromTextRangeCommand(
TextPosition destinationPosition,
SingleLineTextRange sourceRange)
{
// Create the command adapter and return it.
var command = new ProjectInsertTextFromTextRangeCommand(
Project, destinationPosition, sourceRange);
//Debug.WriteLine(
// "CreateInsertTextFromTextRangeCommand: " + destinationPosition + ", "
// + sourceRange);
return command;
}
public void DeferDo(ICommand<OperationContext> command)
{
throw new NotImplementedException();
}
public void Do(
ICommand<OperationContext> command,
OperationContext context)
{
// Every command needs a full write lock on the blocks.
using (Project.Blocks.AcquireLock(RequestLock.Write))
{
// Create the context for the block commands.
var blockContext = new BlockCommandContext(Project);
LinePosition linePosition = context.Position.LinePosition;
int lineIndex = linePosition.GetLineIndex(Project.Blocks.Count);
Block currentBlock = Project.Blocks[lineIndex];
blockContext.Position = new BlockPosition(
currentBlock, context.Position.CharacterPosition);
// Wrap the command with our wrappers.
IWrappedCommand wrappedCommand = WrapCommand(command, context);
Project.Commands.Do(wrappedCommand, blockContext);
// Set the operation context from the block context.
if (blockContext.Position.HasValue)
{
// Grab the block position and figure out the index.
BlockPosition blockPosition = blockContext.Position.Value;
int blockIndex = Project.Blocks.IndexOf(blockPosition.BlockKey);
var position = new TextPosition(blockIndex, (int) blockPosition.TextIndex);
// Set the context results.
context.Results = new LineBufferOperationResults(position);
}
// Make sure we process our wrapped command.
wrappedCommand.PostDo(context);
}
}
public ICommand<OperationContext> Redo(OperationContext context)
{
// Every command needs a full write lock on the blocks.
using (Project.Blocks.AcquireLock(RequestLock.Write))
{
// Create the context for the block commands.
var blockContext = new BlockCommandContext(Project);
// Execute the internal command.
ICommand<BlockCommandContext> command = Commands.Redo(blockContext);
// Set the operation context from the block context.
if (blockContext.Position.HasValue)
{
// Grab the block position and figure out the index.
BlockPosition blockPosition = blockContext.Position.Value;
int blockIndex = Project.Blocks.IndexOf(blockPosition.BlockKey);
var position = new TextPosition(blockIndex, (int) blockPosition.TextIndex);
// Set the context results.
context.Results = new LineBufferOperationResults(position);
}
// See if we have a wrapped command, then do the post do.
var wrapped = command as IWrappedCommand;
if (wrapped != null)
{
wrapped.PostDo(context);
}
}
// Always return null for now.
return null;
}
public ICommand<OperationContext> Undo(OperationContext context)
{
// Every command needs a full write lock on the blocks.
using (Project.Blocks.AcquireLock(RequestLock.Write))
{
// Create the context for the block commands.
var blockContext = new BlockCommandContext(Project);
// Execute the internal command.
ICommand<BlockCommandContext> command = Commands.Undo(blockContext);
// Set the operation context from the block context.
if (blockContext.Position.HasValue)
{
// Grab the block position and figure out the index.
BlockPosition blockPosition = blockContext.Position.Value;
int blockIndex = Project.Blocks.IndexOf(blockPosition.BlockKey);
var position = new TextPosition(blockIndex, (int) blockPosition.TextIndex);
// Set the context results.
context.Results = new LineBufferOperationResults(position);
}
// See if we have a wrapped command, then do the post do.
var wrapped = command as IWrappedCommand;
if (wrapped != null)
{
wrapped.PostUndo(context);
}
}
return null;
}
public IWrappedCommand WrapCommand(
ICommand<OperationContext> command,
OperationContext operationContext)
{
// If the command is a ProjectCommandAdapter, then we want to wrap the
// individual commands.
var adapter = command as ProjectCommandAdapter;
if (adapter != null)
{
// Implement the commands in the wrapper.
var wrappedCommand = new ProjectCommandWrapper(adapter, adapter.Command);
return wrappedCommand;
}
// If we have a composite command, we want to wrap it in a custom
// composite of our own.
var composite = command as CompositeCommand<OperationContext>;
if (composite != null)
{
var wrappedCompositeCommand = new ProjectCompositeCommandAdapter(
this, composite, operationContext);
return wrappedCompositeCommand;
}
// If we got this far, we have an invalid state.
throw new InvalidOperationException("Cannot wrap a command " + command);
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Projects;
using NUnit.Framework;
namespace AuthorIntrusion.Common.Tests
{
[TestFixture]
public class ProjectMacrosTest
{
#region Methods
[Test]
public void ExpandBlankString()
{
// Arrange
var macros = new ProjectMacros();
macros.Substitutions["ProjectDir"] = "pd";
// Act
string results = macros.ExpandMacros("");
// Assert
Assert.AreEqual("", results);
}
[Test]
public void ExpandNonExistantValue()
{
// Arrange
var macros = new ProjectMacros();
macros.Substitutions["ProjectDir"] = "pd";
// Act
string results = macros.ExpandMacros("{ProjectPath}");
// Assert
Assert.AreEqual("", results);
}
[Test]
public void ExpandRepeatedValue()
{
// Arrange
var macros = new ProjectMacros();
macros.Substitutions["ProjectDir"] = "pd";
macros.Substitutions["ProjectPath"] = "{ProjectDir}/p";
// Act
string results = macros.ExpandMacros("{ProjectPath}");
// Assert
Assert.AreEqual("pd/p", results);
}
[Test]
public void ExpandValue()
{
// Arrange
var macros = new ProjectMacros();
macros.Substitutions["ProjectDir"] = "pd";
// Act
string results = macros.ExpandMacros("{ProjectDir}");
// Assert
Assert.AreEqual("pd", results);
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.IO;
using AuthorIntrusion.Common.Plugins;
namespace AuthorIntrusion.Common.Persistence
{
/// <summary>
/// Defines the common interface for all plugins that are involved with reading
/// and writing project data to a filesystem or network.
/// </summary>
public interface IPersistencePlugin: IProjectPluginProviderPlugin
{
#region Methods
/// <summary>
/// Determines whether this instance can read the specified project file.
/// </summary>
/// <param name="projectFile">The project file.</param>
/// <returns>
/// <c>true</c> if this instance can read the specified project file; otherwise, <c>false</c>.
/// </returns>
bool CanRead(FileInfo projectFile);
/// <summary>
/// Reads the project from the given file and returns it.
/// </summary>
/// <param name="projectFile">The project file.</param>
/// <returns>The resulting project file.</returns>
Project ReadProject(FileInfo projectFile);
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Commands;
using AuthorIntrusion.Common.Plugins;
using MfGames.Commands;
namespace AuthorIntrusion.Plugins.ImmediateBlockTypes
{
public class ImmediateBlockTypesProjectPlugin: IImmediateEditorProjectPlugin
{
#region Properties
public string Key
{
get { return "Immediate Block Types"; }
}
public Project Project { get; set; }
public ImmediateBlockTypesSettings Settings
{
get
{
var settings =
Project.Settings.Get<ImmediateBlockTypesSettings>(
ImmediateBlockTypesSettings.SettingsPath);
return settings;
}
}
#endregion
#region Methods
public void ProcessImmediateEdits(
BlockCommandContext context,
Block block,
int textIndex)
{
// Get the plugin settings from the project.
ImmediateBlockTypesSettings settings = Settings;
// Grab the substring from the beginning to the index and compare that
// in the dictionary.
string text = block.Text.Substring(0, textIndex);
if (!settings.Replacements.ContainsKey(text))
{
// We want to fail as fast as possible.
return;
}
// If the block type is already set to the same name, skip it.
string blockTypeName = settings.Replacements[text];
BlockType blockType = Project.BlockTypes[blockTypeName];
if (block.BlockType == blockType)
{
return;
}
// Perform the substitution with a replace operation and a block change
// operation.
var replaceCommand =
new ReplaceTextCommand(
new BlockPosition(block.BlockKey, 0), textIndex, string.Empty);
var changeCommand = new ChangeBlockTypeCommand(block.BlockKey, blockType);
// Create a composite command that binds everything together.
var compositeCommand = new CompositeCommand<BlockCommandContext>(true, false);
compositeCommand.Commands.Add(replaceCommand);
compositeCommand.Commands.Add(changeCommand);
// Add the command to the deferred execution so the command could
// be properly handled via the undo/redo management.
block.Project.Commands.DeferDo(compositeCommand);
}
#endregion
#region Constructors
public ImmediateBlockTypesProjectPlugin(Project project)
{
Project = project;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Mo<NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
using MfGames.Commands.TextEditing;
namespace AuthorIntrusion.Common.Commands
{
/// <summary>
/// Encapsulates a command that works on a single block identified by a key.
/// </summary>
public abstract class SingleBlockKeyCommand: BlockKeyCommand
{
#region Methods
public override void Do(BlockCommandContext context)
{
// If we have a block key, we use that first.
ProjectBlockCollection blocks = context.Blocks;
if (UseBlockKey)
{
Block block;
using (
blocks.AcquireBlockLock(
RequestLock.Write, RequestLock.Write, BlockKey, out block))
{
Do(context, block);
}
}
else
{
Block block;
using (
blocks.AcquireBlockLock(
RequestLock.Write, RequestLock.Write, (int) Line, out block))
{
BlockKey = block.BlockKey;
Do(context, block);
}
}
}
public override void Undo(BlockCommandContext context)
{
// If we have a block key, we use that first.
ProjectBlockCollection blocks = context.Blocks;
if (UseBlockKey)
{
Block block;
using (
blocks.AcquireBlockLock(
RequestLock.Read, RequestLock.Write, BlockKey, out block))
{
Undo(context, block);
}
}
else
{
Block block;
using (
blocks.AcquireBlockLock(
RequestLock.Read, RequestLock.Write, (int) Line, out block))
{
Undo(context, block);
}
}
}
#endregion
#region Constructors
protected SingleBlockKeyCommand(BlockKey blockKey)
: base(blockKey)
{
}
protected SingleBlockKeyCommand(LinePosition line)
: base(line)
{
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
namespace AuthorIntrusion.Common
{
public static class XmlConstants
{
#region Fields
public const string ProjectNamespace =
"urn:mfgames.com/author-intrusion/project/0";
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
using AuthorIntrusion.Common.Commands;
using MfGames.Commands.TextEditing;
using MfGames.GtkExt.TextEditor.Models;
using MfGames.GtkExt.TextEditor.Models.Buffers;
namespace AuthorIntrusion.Gui.GtkGui.Commands
{
public class ProjectInsertTextFromTextRangeCommand: ProjectCommandAdapter,
IInsertTextFromTextRangeCommand<OperationContext>
{
#region Methods
public override void Do(OperationContext context)
{
base.Do(context);
// We need a read lock on the block so we can retrieve information.
Block block;
var blockIndex = (int) destinationPosition.LinePosition;
using (
Project.Blocks.AcquireBlockLock(RequestLock.Read, blockIndex, out block))
{
int characterIndex =
destinationPosition.CharacterPosition.GetCharacterIndex(block.Text);
var bufferPosition = new TextPosition(
destinationPosition.LinePosition,
new CharacterPosition(characterIndex + block.Text.Length));
context.Results = new LineBufferOperationResults(bufferPosition);
}
}
public override void Undo(OperationContext context)
{
base.Undo(context);
// We need a read lock on the block so we can retrieve information.
Block block;
var blockIndex = (int) destinationPosition.LinePosition;
using (
Project.Blocks.AcquireBlockLock(RequestLock.Read, blockIndex, out block))
{
int characterIndex =
destinationPosition.CharacterPosition.GetCharacterIndex(block.Text);
var bufferPosition = new TextPosition(
(int) destinationPosition.LinePosition,
(characterIndex + block.Text.Length));
context.Results = new LineBufferOperationResults(bufferPosition);
}
}
#endregion
#region Constructors
public ProjectInsertTextFromTextRangeCommand(
Project project,
TextPosition destinationPosition,
SingleLineTextRange sourceRange)
: base(project)
{
// Save the position for later.
this.destinationPosition = destinationPosition;
// Create the project command wrapper.
var command = new InsertTextFromIndexedBlock(
destinationPosition, sourceRange);
// Set the command into the adapter.
Command = command;
}
#endregion
#region Fields
private readonly TextPosition destinationPosition;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Events;
using Gtk;
namespace AuthorIntrusion.Gui.GtkGui
{
/// <summary>
/// Encapsulates the logic for displaying a project tab view.
/// </summary>
public class ProjectTabView: Frame
{
#region Methods
private void OnProjectLoaded(
object sender,
ProjectEventArgs e)
{
// Remove the child, if we have one.
if (Child != null)
{
Remove(Child);
}
// Create a tree model for this project.
var store = new TreeStore(typeof (string));
TreeIter iter = store.AppendValues("Project");
store.AppendValues(iter, "Chapter");
// Create the view for the tree.
var treeView = new TreeView
{
Model = store,
HeadersVisible = false,
};
treeView.AppendColumn("Name", new CellRendererText(), "text", 0);
// We need to wrap this in a scroll bar since the list might become
// too larger.
var scrolledWindow = new ScrolledWindow();
scrolledWindow.Add(treeView);
Add(scrolledWindow);
// Show our components to the user.
ShowAll();
}
private void OnProjectUnloaded(
object sender,
ProjectEventArgs e)
{
// Remove the child, if we have one.
if (Child != null)
{
Remove(Child);
}
// Add a label to indicate we don't have a loaded project.
var label = new Label("No Project Loaded");
Add(label);
}
#endregion
#region Constructors
public ProjectTabView(ProjectManager projectManager)
{
// Save the fields for later use.
this.projectManager = projectManager;
// Set the internal elements of this frame.
BorderWidth = 0;
Shadow = ShadowType.None;
ShadowType = ShadowType.None;
// Hook up to the events for this project.
projectManager.ProjectLoaded += OnProjectLoaded;
projectManager.ProjectUnloaded += OnProjectUnloaded;
}
#endregion
#region Fields
private readonly ProjectManager projectManager;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.IO;
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Events;
using AuthorIntrusion.Common.Persistence;
using AuthorIntrusion.Common.Plugins;
using AuthorIntrusion.Gui.GtkGui.Commands;
using Gtk;
using MfGames.GtkExt.TextEditor;
namespace AuthorIntrusion.Gui.GtkGui
{
/// <summary>
/// Primary interfact window for a tabbed document interface.
/// </summary>
public class MainWindow: Window
{
#region Methods
/// <summary>
/// Opens the given project file.
/// </summary>
/// <param name="file">A file object to load.</param>
public void OpenProject(FileInfo file)
{
// Load the project into memory.
projectManager.OpenProject(file);
}
/// <summary>
/// Creates the GUI from code elements.
/// </summary>
private void CreateGui()
{
// Hook up the accelerator group.
accelerators = new AccelGroup();
AddAccelGroup(accelerators);
// The main frame has a VBox to arrange all the components. The VBox
// contains the menu, the primary text editor, and a status bar.
var vertical = new VBox(false, 0);
Add(vertical);
// The center part of the area has a horizontal separator with the
// bulk of the text editor on the left.
var pane = new HPaned
{
Position = 1024 - 256,
BorderWidth = 0,
};
// Create the various components and add them to the vertical box.
Widget menuBarWidget = CreateGuiMenubar();
Widget panelsWidget = CreatePanelArea();
Widget textEditorWidget = CreateGuiEditor();
Widget statusBarWidget = CreateGuiStatusbar();
pane.Pack1(textEditorWidget, true, true);
pane.Pack2(panelsWidget, true, true);
vertical.PackStart(menuBarWidget, false, false, 0);
vertical.PackStart(pane, true, true, 0);
vertical.PackStart(statusBarWidget, false, false, 0);
}
private Widget CreateGuiEditor()
{
// Create the editor for the user.
commandController = new ProjectCommandController();
editorView = new EditorView();
editorView.Controller.CommandController = commandController;
EditorViewTheme.SetupTheme(editorView.Theme);
// Remove the default margins because they aren't helpful at this
// point and whenever they load, it causes the document to reset.
editorView.Margins.Clear();
// Wrap the text editor in a scrollbar.
var scrolledWindow = new ScrolledWindow();
scrolledWindow.VscrollbarPolicy = PolicyType.Always;
scrolledWindow.Add(editorView);
// Create the indicator bar that is 10 px wide.
indicatorView = new IndicatorView(editorView);
indicatorView.SetSizeRequest(20, 1);
var indicatorFrame = new Frame
{
BorderWidth = 2,
ShadowType = ShadowType.None,
Shadow = ShadowType.None
};
indicatorFrame.Add(indicatorView);
// Add the editor and bar to the current tab.
var editorBand = new HBox(false, 0);
editorBand.PackStart(indicatorFrame, false, false, 0);
editorBand.PackStart(scrolledWindow, true, true, 4);
// Return the top-most frame.
return editorBand;
}
/// <summary>
/// Creates the menubar elements of a GUI.
/// </summary>
/// <returns></returns>
private Widget CreateGuiMenubar()
{
// Create the menu items we'll be using.
newMenuItem = new ImageMenuItem(Stock.New, accelerators);
newMenuItem.Activated += OnProjectMenuNewItem;
openMenuItem = new ImageMenuItem(Stock.Open, accelerators);
openMenuItem.Activated += OnProjectMenuOpenItem;
closeMenuItem = new ImageMenuItem(Stock.Close, accelerators)
{
Sensitive = false
};
closeMenuItem.Activated += OnProjectMenuCloseItem;
saveMenuItem = new ImageMenuItem(Stock.Save, accelerators)
{
Sensitive = false
};
saveMenuItem.Activated += OnProjectMenuSaveItem;
exitMenuItem = new ImageMenuItem(Stock.Quit, accelerators);
exitMenuItem.Activated += OnProjectMenuExitItem;
aboutMenuItem = new ImageMenuItem(Stock.About, accelerators);
aboutMenuItem.Activated += OnHelpMenuAboutItem;
// Create the project menu.
var projectMenu = new Menu
{
newMenuItem,
openMenuItem,
closeMenuItem,
new SeparatorMenuItem(),
saveMenuItem,
new SeparatorMenuItem(),
exitMenuItem
};
var projectMenuItem = new MenuItem("_Project")
{
Submenu = projectMenu
};
// Create the about menu.
var helpMenu = new Menu
{
aboutMenuItem,
};
var helpMenuItem = new MenuItem("_Help")
{
Submenu = helpMenu
};
// Create the menu bar and reutrn it.
var menuBar = new MenuBar
{
projectMenuItem,
helpMenuItem,
};
return menuBar;
}
private Widget CreateGuiStatusbar()
{
var statusbar = new Statusbar();
return statusbar;
}
/// <summary>
/// Creates the hard-coded panel area. This will get replaced with the
/// docking widgets at some point, but for the time being, they are set
/// as part of code.
/// </summary>
/// <returns></returns>
private Widget CreatePanelArea()
{
// Create the project pane.
var projectTab = new ProjectTabView(projectManager);
// We have a notepad that contains the the individual elements.
var notebook = new Notebook
{
TabPos = PositionType.Bottom
};
notebook.AppendPage(projectTab, new Label("Project"));
// Wrap the notebook in a frame for spacing.
var frame = new Frame
{
Child = notebook,
BorderWidth = 2,
Shadow = ShadowType.None,
ShadowType = ShadowType.None,
};
return frame;
}
private void OnDeleteWindow(
object o,
DeleteEventArgs args)
{
Application.Quit();
}
private void OnHelpMenuAboutItem(
object sender,
EventArgs e)
{
var about = new AboutWindow();
about.Run();
about.Destroy();
}
/// <summary>
/// Called when a project is loaded.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="ProjectEventArgs"/> instance containing the event data.</param>
private void OnProjectLoaded(
object sender,
ProjectEventArgs e)
{
// Set up the line buffer for the loaded project.
var projectLineBuffer = new ProjectLineBuffer(e.Project, editorView);
editorView.SetLineBuffer(projectLineBuffer);
commandController.Project = e.Project;
commandController.ProjectLineBuffer = projectLineBuffer;
// Update the GUI element.
UpdateGuiState();
}
private void OnProjectMenuCloseItem(
object sender,
EventArgs e)
{
projectManager.CloseProject();
}
private void OnProjectMenuExitItem(
object sender,
EventArgs e)
{
Application.Quit();
}
private void OnProjectMenuNewItem(
object sender,
EventArgs e)
{
// We need an open file dialog box and use that to select the project.
var dialog = new FileChooserDialog(
"Choose Author Intrusion Project",
this,
FileChooserAction.Save,
"Cancel",
ResponseType.Cancel,
"Save",
ResponseType.Accept);
// Set up the filter on the dialog.
var filter = new FileFilter
{
Name = "Project Files"
};
filter.AddMimeType("binary/x-author-intrusion");
filter.AddPattern("*.aiproj");
dialog.AddFilter(filter);
// Show the dialog and process the results.
try
{
// Show the dialog and get the button the user selected.
int results = dialog.Run();
// If the user accepted a file, then use that to open the file.
if (results != (int) ResponseType.Accept)
{
return;
}
// Create a project and (for now) add in every plugin.
var project = new Project();
foreach (IPlugin plugin in project.Plugins.PluginManager.Plugins)
{
project.Plugins.Add(plugin.Key);
}
// Save the project to the given file.
var file = new FileInfo(dialog.Filename);
var savePlugin =
(FilesystemPersistenceProjectPlugin)
project.Plugins["Filesystem Persistence"];
savePlugin.Settings.SetIndividualDirectoryLayout();
savePlugin.Settings.ProjectDirectory = file.Directory.FullName;
savePlugin.Save(file.Directory);
// Set the project to the new plugin.
string newProjectFilename = System.IO.Path.Combine(
file.Directory.FullName, "Project.aiproj");
var projectFile = new FileInfo(newProjectFilename);
projectManager.OpenProject(projectFile);
}
finally
{
// Destroy the dialog the box.
dialog.Destroy();
}
}
private void OnProjectMenuOpenItem(
object sender,
EventArgs e)
{
// We need an open file dialog box and use that to select the project.
var dialog = new FileChooserDialog(
"Open Author Intrusion Project",
this,
FileChooserAction.Open,
"Cancel",
ResponseType.Cancel,
"Open",
ResponseType.Accept);
// Set up the filter on the dialog.
var filter = new FileFilter
{
Name = "Project Files"
};
filter.AddMimeType("binary/x-author-intrusion");
filter.AddPattern("*.aiproj");
dialog.AddFilter(filter);
// Show the dialog and process the results.
try
{
// Show the dialog and get the button the user selected.
int results = dialog.Run();
// If the user accepted a file, then use that to open the file.
if (results != (int) ResponseType.Accept)
{
return;
}
// Get the project file and load it.
var file = new FileInfo(dialog.Filename);
if (!file.Exists)
{
return;
}
// Open the project.
OpenProject(file);
}
finally
{
// Destroy the dialog the box.
dialog.Destroy();
}
}
private void OnProjectMenuSaveItem(
object sender,
EventArgs e)
{
projectManager.SaveProject();
}
/// <summary>
/// Called when a project is unloaded.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="ProjectEventArgs"/> instance containing the event data.</param>
private void OnProjectUnloaded(
object sender,
ProjectEventArgs e)
{
// Dispose of the project because we need to disconnect from
// events.
if (commandController.ProjectLineBuffer != null)
{
commandController.ProjectLineBuffer.Dispose();
}
// Remove the line buffer.
commandController.ProjectLineBuffer = null;
commandController.Project = null;
editorView.ClearLineBuffer();
// Update the GUI state elements.
UpdateGuiState();
}
/// <summary>
/// Updates the state of various components of the GUI.
/// </summary>
private void UpdateGuiState()
{
saveMenuItem.Sensitive = projectManager.HasLoadedProject;
closeMenuItem.Sensitive = projectManager.HasLoadedProject;
}
#endregion
#region Constructors
public MainWindow(ProjectManager projectManager)
: base("Author Intrusion")
{
// Set up the manager to handle project loading and unloading.
this.projectManager = projectManager;
projectManager.ProjectLoaded += OnProjectLoaded;
projectManager.ProjectUnloaded += OnProjectUnloaded;
// Set up the GUI elements.
CreateGui();
// Hook up the window-level events.
DeleteEvent += OnDeleteWindow;
// Resize the window to a resonable size.
SetSizeRequest(1024, 768);
}
#endregion
#region Fields
private ImageMenuItem aboutMenuItem;
private AccelGroup accelerators;
private ImageMenuItem closeMenuItem;
private ProjectCommandController commandController;
private EditorView editorView;
private MenuItem exitMenuItem;
private IndicatorView indicatorView;
private MenuItem newMenuItem;
private MenuItem openMenuItem;
private readonly ProjectManager projectManager;
private MenuItem saveMenuItem;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Collections.Generic;
using AuthorIntrusion.Common.Blocks;
using MfGames.Commands;
namespace AuthorIntrusion.Common.Commands
{
/// <summary>
/// A command to insert one or more blocks after a given block. The text value
/// of the new blocks will be a blank string.
/// </summary>
public class InsertAfterBlockCommand: MultipleBlockKeyCommand
{
#region Properties
protected int Count { get; private set; }
#endregion
#region Methods
protected override void Do(
BlockCommandContext context,
Block block)
{
// Pull out some common elements we'll need.
ProjectBlockCollection blocks = block.Blocks;
int blockIndex = blocks.IndexOf(block) + 1;
// Because of how block keys work, the ID is unique very time so we have
// to update our inverse operation.
addedBlocks.Clear();
// Go through and create each block at a time, adding it to the inverse
// command as we create them.
for (int count = 0;
count < Count;
count++)
{
// Create and insert a new block into the system.
var newBlock = new Block(blocks);
blocks.Insert(blockIndex, newBlock);
// Keep track of the block so we can remove them later.
addedBlocks.Add(newBlock);
// Update the position.
if (UpdateTextPosition.HasFlag(DoTypes.Do))
{
context.Position = new BlockPosition(newBlock.BlockKey, 0);
}
}
}
protected override void Undo(
BlockCommandContext context,
Block block)
{
foreach (Block addedBlock in addedBlocks)
{
context.Blocks.Remove(addedBlock);
}
if (UpdateTextPosition.HasFlag(DoTypes.Undo))
{
context.Position = new BlockPosition(BlockKey, block.Text.Length);
}
}
#endregion
#region Constructors
public InsertAfterBlockCommand(
BlockKey blockKey,
int count)
: base(blockKey)
{
// Make sure we have a sane state.
if (count <= 0)
{
throw new ArgumentOutOfRangeException(
"count", "Cannot insert or zero or less blocks.");
}
// Keep track of the counts.
Count = count;
// We have to keep track of the blocks we added.
addedBlocks = new List<Block>();
}
#endregion
#region Fields
private readonly List<Block> addedBlocks;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Threading;
using MfGames.Locking;
namespace AuthorIntrusion.Common.Blocks.Locking
{
/// <summary>
/// Implements a read-only lock on the given block. This intended to be used
/// in an using() code block and released once the read-lock is no longer
/// needed.
/// </summary>
public class BlockLock: IDisposable
{
#region Constructors
/// <summary>
/// Acquires a read lock on both the block and the block collection.
/// </summary>
/// <param name="collectionLock">The lock on the block collection.</param>
/// <param name="blockLock">The lock object used to acquire the lock.</param>
/// <param name="requestLock"></param>
public BlockLock(
IDisposable collectionLock,
ReaderWriterLockSlim accessLock,
RequestLock requestLock)
{
// Keep track of the collection lock so we can release it.
this.collectionLock = collectionLock;
// Acquire the lock based on the requested type.
switch (requestLock)
{
case RequestLock.Read:
blockLock = new NestableReadLock(accessLock);
break;
case RequestLock.UpgradableRead:
blockLock = new NestableUpgradableReadLock(accessLock);
break;
case RequestLock.Write:
blockLock = new NestableWriteLock(accessLock);
break;
default:
throw new InvalidOperationException(
"Could not acquire lock with unknown type: " + requestLock);
}
}
#endregion
#region Destructors
public void Dispose()
{
// We have to release the block lock first before we release the collection.
if (blockLock != null)
{
blockLock.Dispose();
blockLock = null;
}
// Release the collection lock last to avoid deadlocks.
if (collectionLock != null)
{
collectionLock.Dispose();
collectionLock = null;
}
}
#endregion
#region Fields
private IDisposable blockLock;
private IDisposable collectionLock;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
using NUnit.Framework;
namespace AuthorIntrusion.Common.Tests
{
[TestFixture]
public class BlockTypeManagerTests
{
#region Methods
[Test]
public void CreateEmptyBlockTypeManager()
{
// Arrange
var project = new Project();
// Act
var manager = new BlockTypeSupervisor(project);
// Assert
Assert.AreEqual(project, manager.Project);
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Commands;
using MfGames.Enumerations;
using MfGames.HierarchicalPaths;
namespace AuthorIntrusion.Common.Actions
{
/// <summary>
/// Defines an abstract editor action which is provided from the various plugins
/// to the front-end interfaces, such as the GUI.
/// </summary>
public interface IEditorAction
{
#region Properties
/// <summary>
/// Gets the display name suitable for displaying in menus and popups. The
/// display name may have a "&" in front of a character to indicate the
/// preferred mnemonic, but if two items have the same shortcut (and in the
/// same menu), then the one with the lowest Importanance.
/// </summary>
string DisplayName { get; }
/// <summary>
/// Gets the importance of the editor action. This is used to decide which
/// items should be on the main menus when there are too many items to
/// reasonably display on screen at the same time.
/// </summary>
Importance Importance { get; }
/// <summary>
/// Gets the key for this action. Unlike the display name, this should never
/// be translated into other languages. It is used to look up additional
/// resources for the interface, such as icons or help.
/// </summary>
HierarchicalPath ResourceKey { get; }
#endregion
#region Methods
/// <summary>
/// Performs the action associated with this editor action.
/// </summary>
void Do(BlockCommandContext context);
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Collections.Generic;
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Actions;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Commands;
using AuthorIntrusion.Common.Plugins;
using NUnit.Framework;
namespace AuthorIntrusion.Plugins.Spelling.LocalWords.Tests
{
[TestFixture]
public class LocalWordsControllerTests
{
#region Methods
[Test]
public void ActivatePlugin()
{
// Act
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
PluginSupervisor plugins;
LocalWordsProjectPlugin projectPlugin;
SetupPlugin(out blocks, out commands, out plugins, out projectPlugin);
// Assert
Project project = blocks.Project;
Assert.AreEqual(2, project.Plugins.Controllers.Count);
}
[Test]
public void CheckCaseInsensitiveCorrectWord()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
PluginSupervisor plugins;
LocalWordsProjectPlugin projectPlugin;
SetupPlugin(out blocks, out commands, out plugins, out projectPlugin);
// Act
commands.InsertText(blocks[0], 0, "one.");
plugins.WaitForBlockAnalzyers();
// Assert
Assert.AreEqual(0, blocks[0].TextSpans.Count);
}
[Test]
public void CheckCaseInsensitiveCorrectWordDifferentCase()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
PluginSupervisor plugins;
LocalWordsProjectPlugin projectPlugin;
SetupPlugin(out blocks, out commands, out plugins, out projectPlugin);
// Act
commands.InsertText(blocks[0], 0, "ONE.");
plugins.WaitForBlockAnalzyers();
// Assert
Assert.AreEqual(0, blocks[0].TextSpans.Count);
}
[Test]
public void CheckCaseInsensitiveIncorrectWord()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
PluginSupervisor plugins;
LocalWordsProjectPlugin projectPlugin;
SetupPlugin(out blocks, out commands, out plugins, out projectPlugin);
// Act
commands.InsertText(blocks[0], 0, "two.");
plugins.WaitForBlockAnalzyers();
// Assert
Assert.AreEqual(1, blocks[0].TextSpans.Count);
}
[Test]
public void CheckCaseSensitiveCorrectWord()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
PluginSupervisor plugins;
LocalWordsProjectPlugin projectPlugin;
SetupPlugin(out blocks, out commands, out plugins, out projectPlugin);
// Act
commands.InsertText(blocks[0], 0, "Correct.");
plugins.WaitForBlockAnalzyers();
// Assert
Assert.AreEqual(0, blocks[0].TextSpans.Count);
}
[Test]
public void CheckCaseSensitiveCorrectWordWrongCase()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
PluginSupervisor plugins;
LocalWordsProjectPlugin projectPlugin;
SetupPlugin(out blocks, out commands, out plugins, out projectPlugin);
// Act
commands.InsertText(blocks[0], 0, "correct.");
plugins.WaitForBlockAnalzyers();
// Assert
Assert.AreEqual(1, blocks[0].TextSpans.Count);
}
[Test]
public void CheckCaseSensitiveIncorrectActions()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
PluginSupervisor plugins;
LocalWordsProjectPlugin projectPlugin;
SetupPlugin(out blocks, out commands, out plugins, out projectPlugin);
// Arrange: Edit the text
Block block = blocks[0];
commands.InsertText(block, 0, "Correc.");
plugins.WaitForBlockAnalzyers();
// Act: Get the editor actions.
TextSpan textSpan = block.TextSpans[0];
IList<IEditorAction> actions = plugins.GetEditorActions(block, textSpan);
// Assert
Assert.AreEqual(0, actions.Count);
}
[Test]
public void CheckCaseSensitiveIncorrectTextSpan()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
PluginSupervisor plugins;
LocalWordsProjectPlugin projectPlugin;
SetupPlugin(out blocks, out commands, out plugins, out projectPlugin);
// Act
commands.InsertText(blocks[0], 0, "Correc.");
plugins.WaitForBlockAnalzyers();
// Assert: TextSpans created
Assert.AreEqual(1, blocks[0].TextSpans.Count);
}
[Test]
public void CheckCaseSensitiveIncorrectWord()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
PluginSupervisor plugins;
LocalWordsProjectPlugin projectPlugin;
SetupPlugin(out blocks, out commands, out plugins, out projectPlugin);
// Act
commands.InsertText(blocks[0], 0, "Correc.");
plugins.WaitForBlockAnalzyers();
// Assert
Project project = blocks.Project;
Assert.AreEqual(2, project.Plugins.Controllers.Count);
}
/// <summary>
/// Configures the environment to load the plugin manager and verify we
/// have access to our plugin and projectPlugin.
/// </summary>
private void SetupPlugin(
out ProjectBlockCollection blocks,
out BlockCommandSupervisor commands,
out PluginSupervisor plugins,
out LocalWordsProjectPlugin projectPlugin)
{
// Start getting us a simple plugin manager.
var spelling = new SpellingFrameworkPlugin();
var nhunspell = new LocalWordsPlugin();
var pluginManager = new PluginManager(spelling, nhunspell);
PluginManager.Instance = pluginManager;
// Create a project and pull out the useful properties we'll use to
// make changes.
var project = new Project();
blocks = project.Blocks;
commands = project.Commands;
plugins = project.Plugins;
// Load in the immediate correction editor.
if (!plugins.Add("Spelling Framework"))
{
// We couldn't load it for some reason.
throw new ApplicationException("Cannot load 'Spelling' plugin.");
}
if (!plugins.Add("Local Words"))
{
// We couldn't load it for some reason.
throw new ApplicationException("Cannot load 'Local Words' plugin.");
}
// Pull out the projectPlugin for the correction and cast it (since we know
// what type it is).
ProjectPluginController pluginController = plugins.Controllers[1];
projectPlugin = (LocalWordsProjectPlugin) pluginController.ProjectPlugin;
projectPlugin.CaseSensitiveDictionary.Add("Correct");
projectPlugin.CaseInsensitiveDictionary.Add("one");
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
namespace AuthorIntrusion.Common.Plugins
{
/// <summary>
/// Defines the interface of a plugin that coordinates between other plugins. These
/// plugins are used to gather up other plugins or to establish a relationship
/// between multiple plugins.
/// </summary>
public interface IFrameworkPlugin: IPlugin
{
#region Methods
/// <summary>
/// Attempts to register the plugins with the current plugin. The given
/// enumerable will not contain the plugin itself.
/// </summary>
/// <param name="additionalPlugins">The plugins.</param>
void RegisterPlugins(IEnumerable<IPlugin> additionalPlugins);
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
namespace AuthorIntrusion.Plugins.Spelling.Common
{
/// <summary>
/// Describes a spelling suggestion including a word and its given weight.
/// </summary>
public class SpellingSuggestion
{
#region Properties
/// <summary>
/// Gets or sets the suggested word.
/// </summary>
public string Suggestion { get; set; }
/// <summary>
/// Gets or sets the weight in the range of -4 to +4. When sorting suggestions
/// for display to the user, the higher weighted suggestions will go first. In
/// most cases, a weight should only be -1 to +1.
/// </summary>
public int Weight { get; set; }
#endregion
#region Constructors
public SpellingSuggestion(
string suggestedWord,
int weight = 0)
{
Suggestion = suggestedWord;
Weight = weight;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using MfGames;
namespace AuthorIntrusion.Dedications
{
/// <summary>
/// A manager class that reads the dedications from an embedded resource
/// and allows for retrieval of the versions.
/// </summary>
public class DedicationManager
{
#region Properties
/// <summary>
/// Contains the dedication for the current assembly version.
/// </summary>
public Dedication CurrentDedication
{
get
{
// Get our assembly version so we can look up the dedication.
Version assemblyVersion = GetType().Assembly.GetName().Version;
var extendedVersion = new ExtendedVersion(assemblyVersion.ToString());
// Go through and find the appropriate version.
IEnumerable<Dedication> search =
Dedications.Where(d => d.Version == extendedVersion);
foreach (Dedication dedication in search)
{
return dedication;
}
// If we get this far, then we couldn't find it.
throw new InvalidOperationException(
"Cannot find a dedication for version " + extendedVersion + ".");
}
}
/// <summary>
/// Contains the dedications for all the versions of Author Intrusion.
/// </summary>
public List<Dedication> Dedications { get; private set; }
#endregion
#region Constructors
public DedicationManager()
{
// Get the embedded resource stream.
Type type = GetType();
Assembly assembly = type.Assembly;
Stream stream = assembly.GetManifestResourceStream(type, "Dedication.xml");
if (stream == null)
{
throw new InvalidOperationException(
"Cannot load Dedication.xml from the assembly to load dedications.");
}
// Load the XML from the given stream.
using (XmlReader reader = XmlReader.Create(stream))
{
// Loop through the reader.
Dedications = new List<Dedication>();
Dedication dedication = null;
while (reader.Read())
{
// If we have a "dedication", we are either starting or
// finishing one.
if (reader.LocalName == "dedication")
{
if (reader.NodeType == XmlNodeType.Element)
{
dedication = new Dedication();
}
else
{
Dedications.Add(dedication);
dedication = null;
}
}
if (reader.NodeType != XmlNodeType.Element
|| dedication == null)
{
continue;
}
// For the remaining tags, we just need to pull out the text.
switch (reader.LocalName)
{
case "author":
string author = reader.ReadString();
dedication.Author = author;
break;
case "version":
string version = reader.ReadString();
var assemblyVersion = new ExtendedVersion(version);
dedication.Version = assemblyVersion;
break;
case "dedicator":
string dedicator = reader.ReadString();
dedication.Dedicator = dedicator;
break;
case "p":
string p = reader.ReadOuterXml();
dedication.Html += p;
break;
}
}
// Finish up the stream.
reader.Close();
}
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Collections.Generic;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
using MfGames.Commands;
using MfGames.Commands.TextEditing;
namespace AuthorIntrusion.Common.Commands
{
/// <summary>
/// Command to insert multiple lines of text into the blocks.
/// </summary>
public class InsertMultilineTextCommand: IBlockCommand
{
#region Properties
public BlockPosition BlockPosition { get; set; }
public bool CanUndo
{
get { return true; }
}
public bool IsTransient
{
get { return false; }
}
public bool IsUndoable
{
get { return true; }
}
public string Text { get; private set; }
public DoTypes UpdateTextPosition { get; set; }
#endregion
#region Methods
public void Do(BlockCommandContext context)
{
// We have to clear the undo buffer every time because we'll be creating
// new blocks.
addedBlocks.Clear();
// Start by breaking apart the lines on the newline.
string[] lines = Text.Split('\n');
// Make changes to the first line by creating a command, adding it to the
// list of commands we need an inverse for, and then performing it.
Block block = context.Blocks[BlockPosition.BlockKey];
string remainingText = block.Text.Substring((int) BlockPosition.TextIndex);
deleteFirstCommand = new DeleteTextCommand(BlockPosition, block.Text.Length);
insertFirstCommand = new InsertTextCommand(BlockPosition, lines[0]);
deleteFirstCommand.Do(context);
insertFirstCommand.Do(context);
// Update the final lines text with the remains of the first line.
int lastLineLength = lines[lines.Length - 1].Length;
lines[lines.Length - 1] += remainingText;
// For the remaining lines, we need to insert each one in turn.
if (UpdateTextPosition.HasFlag(DoTypes.Do))
{
context.Position = BlockPosition.Empty;
}
if (lines.Length > 1)
{
// Go through all the lines in reverse order to insert them.
int firstBlockIndex = context.Blocks.IndexOf(block);
for (int i = lines.Length - 1;
i > 0;
i--)
{
// Insert the line and set its text value.
var newBlock = new Block(context.Blocks);
addedBlocks.Add(newBlock);
using (newBlock.AcquireBlockLock(RequestLock.Write))
{
newBlock.SetText(lines[i]);
}
context.Blocks.Insert(firstBlockIndex + 1, newBlock);
// Update the last position as we go.
if (context.Position == BlockPosition.Empty)
{
if (UpdateTextPosition.HasFlag(DoTypes.Do))
{
context.Position = new BlockPosition(
newBlock.BlockKey, (CharacterPosition) lastLineLength);
}
}
}
}
}
public void Redo(BlockCommandContext context)
{
Do(context);
}
public void Undo(BlockCommandContext context)
{
// Delete all the added blocks first.
foreach (Block block in addedBlocks)
{
context.Blocks.Remove(block);
}
// Restore the text from the first line.
insertFirstCommand.Undo(context);
deleteFirstCommand.Undo(context);
// Update the last position to where we started.
if (UpdateTextPosition.HasFlag(DoTypes.Undo))
{
context.Position = BlockPosition;
}
}
#endregion
#region Constructors
public InsertMultilineTextCommand(
BlockPosition position,
string text)
{
// Make sure we have a sane state.
if (text.Contains("\r"))
{
throw new ArgumentException(
"text cannot have a return (\\r) character in it.", "text");
}
// Save the text for the changes.
BlockPosition = position;
Text = text;
UpdateTextPosition = DoTypes.All;
// Set up our collection.
addedBlocks = new List<Block>();
}
#endregion
#region Fields
private readonly List<Block> addedBlocks;
private DeleteTextCommand deleteFirstCommand;
private InsertTextCommand insertFirstCommand;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
using AuthorIntrusion.Common.Commands;
using MfGames.Commands.TextEditing;
using MfGames.GtkExt.TextEditor.Models;
namespace AuthorIntrusion.Gui.GtkGui.Commands
{
public class ProjectDeleteLineCommand: ProjectCommandAdapter,
IDeleteLineCommand<OperationContext>
{
#region Methods
public override void PostDo(OperationContext context)
{
lineBuffer.RaiseLineDeleted(line.Index);
}
public override void PostUndo(OperationContext context)
{
lineBuffer.RaiseLineInserted(line.Index);
}
#endregion
#region Constructors
public ProjectDeleteLineCommand(
ProjectLineBuffer lineBuffer,
Project project,
LinePosition line)
: base(project)
{
// Save the line for later events.
this.lineBuffer = lineBuffer;
this.line = line;
// Get a lock on the blocks so we can retrieve information.
using (project.Blocks.AcquireLock(RequestLock.Read))
{
// Create the project command wrapper.
Block block = project.Blocks[(int) line];
var command = new DeleteBlockCommand(block.BlockKey);
// Set the command into the adapter.
Command = command;
}
}
#endregion
#region Fields
private readonly LinePosition line;
private readonly ProjectLineBuffer lineBuffer;
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
namespace AuthorIntrusion.Plugins.Spelling.NHunspell.Interop
{
/// <summary>
/// Wrapper around the Hunspell library.
/// </summary>
internal sealed class Hunspell
{
#region Methods
/// <summary>Returns a list of misspelled words in the text.</summary>
public string[] Check(string text)
{
var words = new List<string>();
int index = 0;
while (index < text.Length)
{
if (DoIsWordStart(text, index))
{
int count = DoGetWordLength(text, index);
string word = text.Substring(index, count);
index += count;
count = DoSkipMarkup(text, index);
if (count == 0)
{
word = word.Trim('\'', '-');
if (words.IndexOf(word) < 0
&& !CheckWord(word))
{
words.Add(word);
}
}
else
{
index += count;
}
}
else
{
int count = Math.Max(1, DoSkipMarkup(text, index));
index += count;
}
}
return words.ToArray();
}
public bool CheckWord(string word)
{
// If the word is mixed case or has numbers call it good.
for (int i = 1;
i < word.Length;
++i)
{
if (char.IsUpper(word[i])
|| char.IsNumber(word[i]))
{
return true;
}
}
int result = HunspellInterop.Hunspell_spell(handle, word);
GC.KeepAlive(this);
return result != 0;
}
/// <summary>Returns suggested spellings for a word.</summary>
public string[] Suggest(string word)
{
var suggestions = new List<string>();
int ptrSize = Marshal.SizeOf(typeof (IntPtr));
IntPtr slst = Marshal.AllocHGlobal(ptrSize);
int count = HunspellInterop.Hunspell_suggest(handle, slst, word);
if (count > 0)
{
IntPtr sa = Marshal.ReadIntPtr(slst);
for (int i = 0;
i < count;
++i)
{
IntPtr sp = Marshal.ReadIntPtr(sa, i * ptrSize);
string suggestion = Marshal.PtrToStringAuto(sp);
suggestions.Add(suggestion);
}
HunspellInterop.Hunspell_free_list(handle, slst, count);
}
Marshal.FreeHGlobal(slst);
return suggestions.ToArray();
}
private static int DoGetWordLength(
string text,
int index)
{
int count = 0;
while (index + count < text.Length)
{
char ch = text[index + count];
switch (char.GetUnicodeCategory(ch))
{
// case UnicodeCategory.DashPunctuation:
case UnicodeCategory.DecimalDigitNumber:
case UnicodeCategory.LowercaseLetter:
case UnicodeCategory.NonSpacingMark:
case UnicodeCategory.TitlecaseLetter:
case UnicodeCategory.UppercaseLetter:
++count;
break;
case UnicodeCategory.OtherPunctuation:
if (ch == '\'')
{
++count;
}
else
{
return count;
}
break;
default:
return count;
}
}
return count;
}
private static bool DoIsWordStart(
string text,
int index)
{
char ch = text[index];
switch (char.GetUnicodeCategory(ch))
{
case UnicodeCategory.LowercaseLetter:
case UnicodeCategory.TitlecaseLetter:
case UnicodeCategory.UppercaseLetter:
return true;
}
return false;
}
private static int DoSkipMarkup(
string text,
int index)
{
int count = 0;
if (index < text.Length
&& text[index] == '<')
{
while (index + count < text.Length
&& text[index + count] != '>')
{
++count;
}
if (index + count < text.Length
&& text[index + count] == '>')
{
++count;
}
else
{
count = 0;
}
}
return count;
}
#endregion
#region Constructors
internal Hunspell(
string affixFilename,
string dictionaryFilename)
{
// Make sure we have a sane state.
if (string.IsNullOrWhiteSpace(affixFilename))
{
throw new ArgumentNullException("affixFilename");
}
if (string.IsNullOrWhiteSpace(dictionaryFilename))
{
throw new ArgumentNullException("dictionaryFilename");
}
// Keep the handle we'll be using.
handle = new HunspellHandle(affixFilename, dictionaryFilename);
}
#endregion
#region Fields
private readonly HunspellHandle handle;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
namespace AuthorIntrusion.Common.Commands
{
public class SplitBlockCommand: InsertMultilineTextCommand
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="SplitBlockCommand"/> class.
/// </summary>
/// <param name="position">The position to break the paragraph.</param>
public SplitBlockCommand(
ProjectBlockCollection blocks,
BlockPosition position)
: base(position, "\n")
{
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace AuthorIntrusion.Common.Persistence
{
/// <summary>
/// Manager class for handling reading files from the file system.
/// </summary>
public class PersistenceManager
{
#region Properties
/// <summary>
/// Gets or sets the singleton instance of the persistence manager.
/// </summary>
public static PersistenceManager Instance { get; set; }
#endregion
#region Methods
public Project ReadProject(FileInfo projectFile)
{
// Make sure we have a sane state.
if (projectFile == null)
{
throw new ArgumentNullException("projectFile");
}
// Query the plugins to determine which persistence plugins are capable
// of reading this project.
var validPlugins = new List<IPersistencePlugin>();
foreach (IPersistencePlugin persistencePlugin in
plugin.PersistentPlugins.Where(
persistencePlugin => persistencePlugin.CanRead(projectFile)))
{
validPlugins.Add(persistencePlugin);
}
// If we don't have a plugin, then we have nothing that will open it.
if (validPlugins.Count == 0)
{
throw new FileLoadException("Cannot load the project file: " + projectFile);
}
// If we have more than one plugin, we can't handle it.
if (validPlugins.Count > 1)
{
throw new FileLoadException(
"Too many plugins claim they can read the file: " + projectFile);
}
// Pass the loading process to the actual plugin we'll be using.
IPersistencePlugin persistentPlugin = validPlugins[0];
Project project = persistentPlugin.ReadProject(projectFile);
return project;
}
#endregion
#region Constructors
public PersistenceManager(PersistenceFrameworkPlugin plugin)
{
this.plugin = plugin;
}
#endregion
#region Fields
private readonly PersistenceFrameworkPlugin plugin;
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
namespace AuthorIntrusion.Common.Blocks
{
#if REMOVED
/// <summary>
/// The block type supervisor is a manager class responsible for maintaining
/// the relationship between the various blocks based on their types.
/// </summary>
public class BlockStructureSupervisor
{
#region Properties
/// <summary>
/// Gets or sets the root block structure for the entire project. Typically
/// the root block structure is the top-most element of a project, either a book
/// or a story.
/// </summary>
public BlockStructure RootBlockStructure
{
get { return rootBlockStructure; }
set
{
if (value == null)
{
throw new NullReferenceException(
"Cannot assign a null to the RootBlockStructure.");
}
rootBlockStructure = value;
}
}
protected Project Project { get; private set; }
#endregion
#region Methods
/// <summary>
/// Updates the blocks in the project and assign them to block types that fit
/// the document structure. This will attempt to keep the current block type
/// of a given block if it can fit into the structure.
/// </summary>
public void Update()
{
// If we are inside interactive processing, we need to skip updates
// since this can be an expensive operation.
if (Project.ProcessingState == ProjectProcessingState.Batch)
{
return;
}
// We need to get a write lock on the block since we'll be making changes
// to all the blocks and their relationships. This will, in effect, also
// ensure no block is being modified.
using (Project.Blocks.AcquireLock(RequestLock.Write))
{
// Go through all the blocks in the list.
ProjectBlockCollection blocks = Project.Blocks;
for (int blockIndex = 0;
blockIndex < Project.Blocks.Count;
blockIndex++)
{
// Grab the block we're currently looking at.
Block block = blocks[blockIndex];
BlockType blockType = block.BlockType;
// To figure out the block type, we go backwards until we find the
// first block's structure that contains this block type. If we
// can't find one, we will just use the first block in the list
// regardless of type.
BlockStructure newBlockStructure = null;
Block newParentBlock = null;
for (int searchIndex = blockIndex - 1;
searchIndex >= 0;
searchIndex--)
{
// Grab this block and structure.
Block searchBlock = blocks[searchIndex];
BlockStructure searchStructure = searchBlock.BlockStructure;
// If the search structure includes the current block type,
// then we'll use that and stop looking through the rest of the list.
if (searchStructure.ContainsChildStructure(blockType))
{
newBlockStructure = searchStructure.GetChildStructure(blockType);
newParentBlock = searchBlock;
break;
}
}
// Look to see if we assigned the parent block and structure. If we
// haven't, then assign the parent to the first one (obvious not if
// we are modifying the first one).
if (newParentBlock == null
&& blockIndex > 0)
{
newParentBlock = Project.Blocks[0];
}
if (newBlockStructure == null)
{
newBlockStructure = RootBlockStructure;
}
// Assign the new block structure and parent.
block.SetParentBlock(newParentBlock);
//block.SetBlockStructure(newBlockStructure);
}
}
}
#endregion
#region Constructors
public BlockStructureSupervisor(Project project)
{
// Save the members we need for later referencing.
Project = project;
// Set up the default structure which is just one or more paragraphs
// and no structural elements.
rootBlockStructure = new BlockStructure
{
BlockType = project.BlockTypes.Paragraph
};
}
#endregion
#region Fields
private BlockStructure rootBlockStructure;
#endregion
}
#endif
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Commands;
using AuthorIntrusion.Common.Plugins;
using AuthorIntrusion.Common.Tests;
using MfGames.HierarchicalPaths;
using NUnit.Framework;
namespace AuthorIntrusion.Plugins.Counter.Tests
{
[TestFixture]
public class WordCounterControllerTests: CommonMultilineTests
{
#region Methods
[Test]
public void ActivatePlugin()
{
// Act
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
WordCounterProjectPlugin projectPlugin;
SetupPlugin(out blocks, out commands, out projectPlugin);
// Assert
Project project = blocks.Project;
Assert.AreEqual(1, project.Plugins.Controllers.Count);
}
[Test]
public void ChangeSingleBlockTwoWords()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
WordCounterProjectPlugin projectPlugin;
SetupPlugin(out blocks, out commands, out projectPlugin);
// Arrange: Initial insert
commands.InsertText(blocks[0], 0, "Line 1");
blocks.Project.Plugins.WaitForBlockAnalzyers();
// Act
commands.InsertText(blocks[0], 0, "One ");
blocks.Project.Plugins.WaitForBlockAnalzyers();
// Assert
var path = new HierarchicalPath("/Plugins/Word Counter");
var total = new HierarchicalPath("Total", path);
var paragraph = new HierarchicalPath("Block Types/Paragraph", path);
Project project = blocks.Project;
PropertiesDictionary blockProperties = blocks[0].Properties;
PropertiesDictionary projectProperties = project.Properties;
Assert.AreEqual(1, project.Plugins.Controllers.Count);
Assert.AreEqual(3, blockProperties.Get<int>("Words", total));
Assert.AreEqual(10, blockProperties.Get<int>("Characters", total));
Assert.AreEqual(8, blockProperties.Get<int>("Non-Whitespace", total));
Assert.AreEqual(2, blockProperties.Get<int>("Whitespace", total));
Assert.AreEqual(1, blockProperties.Get<int>("Count", paragraph));
Assert.AreEqual(3, blockProperties.Get<int>("Words", paragraph));
Assert.AreEqual(10, blockProperties.Get<int>("Characters", paragraph));
Assert.AreEqual(8, blockProperties.Get<int>("Non-Whitespace", paragraph));
Assert.AreEqual(2, blockProperties.Get<int>("Whitespace", paragraph));
Assert.AreEqual(3, projectProperties.Get<int>("Words", total));
Assert.AreEqual(10, projectProperties.Get<int>("Characters", total));
Assert.AreEqual(8, projectProperties.Get<int>("Non-Whitespace", total));
Assert.AreEqual(2, projectProperties.Get<int>("Whitespace", total));
Assert.AreEqual(1, projectProperties.Get<int>("Count", paragraph));
Assert.AreEqual(3, projectProperties.Get<int>("Words", paragraph));
Assert.AreEqual(10, projectProperties.Get<int>("Characters", paragraph));
Assert.AreEqual(8, projectProperties.Get<int>("Non-Whitespace", paragraph));
Assert.AreEqual(2, projectProperties.Get<int>("Whitespace", paragraph));
}
[Test]
public void CountComplexSetup()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
WordCounterProjectPlugin projectPlugin;
SetupPlugin(out blocks, out commands, out projectPlugin);
SetupComplexMultilineTest(blocks.Project, 6);
BlockTypeSupervisor blockTypes = blocks.Project.BlockTypes;
// Act
blocks.Project.Plugins.WaitForBlockAnalzyers();
// Assert
Project project = blocks.Project;
Assert.AreEqual(1, project.Plugins.Controllers.Count);
//int index = 0;
//Assert.AreEqual(
// 12, blocks[index].Properties.Get<int>(WordCounterPathUtility.WordCountPath));
//Assert.AreEqual(
// 36, blocks[index].Properties.Get<int>(WordCounterPathUtility.CharacterCountPath));
//Assert.AreEqual(
// 30, blocks[index].Properties.Get<int>(WordCounterPathUtility.NonWhitespaceCountPath));
//Assert.AreEqual(
// 1,
// blocks[index].Properties.Get<int>(WordCounterPathUtility.GetPath(blockTypes.Chapter)));
//Assert.AreEqual(
// 1, blocks[index].Properties.Get<int>(WordCounterPathUtility.GetPath(blockTypes.Scene)));
//Assert.AreEqual(
// 1,
// blocks[index].Properties.Get<int>(WordCounterPathUtility.GetPath(blockTypes.Epigraph)));
//Assert.AreEqual(
// 1,
// blocks[index].Properties.Get<int>(
// WordCounterPathUtility.GetPath(blockTypes.EpigraphAttribution)));
//Assert.AreEqual(
// 2,
// blocks[index].Properties.Get<int>(
// WordCounterPathUtility.GetPath(blockTypes.Paragraph)));
//index++;
//Assert.AreEqual(
// 10, blocks[index].Properties.Get<int>(WordCounterPathUtility.WordCountPath));
//Assert.AreEqual(
// 30, blocks[index].Properties.Get<int>(WordCounterPathUtility.CharacterCountPath));
//Assert.AreEqual(
// 25, blocks[index].Properties.Get<int>(WordCounterPathUtility.NonWhitespaceCountPath));
//Assert.AreEqual(
// 1, blocks[index].Properties.Get<int>(WordCounterPathUtility.GetPath(blockTypes.Scene)));
//Assert.AreEqual(
// 1,
// blocks[index].Properties.Get<int>(WordCounterPathUtility.GetPath(blockTypes.Epigraph)));
//Assert.AreEqual(
// 1,
// blocks[index].Properties.Get<int>(
// WordCounterPathUtility.GetPath(blockTypes.EpigraphAttribution)));
//Assert.AreEqual(
// 2,
// blocks[index].Properties.Get<int>(
// WordCounterPathUtility.GetPath(blockTypes.Paragraph)));
}
[Test]
public void InsertTwoBlocksFourWords()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
WordCounterProjectPlugin projectPlugin;
SetupPlugin(out blocks, out commands, out projectPlugin);
// Arrange: Initial insert
commands.InsertText(blocks[0], 0, "Line 1");
blocks.Project.Plugins.WaitForBlockAnalzyers();
blocks.Add(new Block(blocks));
// Act
commands.InsertText(blocks[1], 0, "Line 2");
blocks.Project.Plugins.WaitForBlockAnalzyers();
// Assert
var path = new HierarchicalPath("/Plugins/Word Counter");
var total = new HierarchicalPath("Total", path);
var paragraph = new HierarchicalPath("Block Types/Paragraph", path);
Project project = blocks.Project;
PropertiesDictionary blockProperties = blocks[0].Properties;
PropertiesDictionary projectProperties = project.Properties;
Assert.AreEqual(2, blockProperties.Get<int>("Words", total));
Assert.AreEqual(6, blockProperties.Get<int>("Characters", total));
Assert.AreEqual(5, blockProperties.Get<int>("Non-Whitespace", total));
Assert.AreEqual(1, blockProperties.Get<int>("Whitespace", total));
Assert.AreEqual(1, blockProperties.Get<int>("Count", paragraph));
Assert.AreEqual(2, blockProperties.Get<int>("Words", paragraph));
Assert.AreEqual(6, blockProperties.Get<int>("Characters", paragraph));
Assert.AreEqual(5, blockProperties.Get<int>("Non-Whitespace", paragraph));
Assert.AreEqual(1, blockProperties.Get<int>("Whitespace", paragraph));
Assert.AreEqual(4, projectProperties.Get<int>("Words", total));
Assert.AreEqual(12, projectProperties.Get<int>("Characters", total));
Assert.AreEqual(10, projectProperties.Get<int>("Non-Whitespace", total));
Assert.AreEqual(2, projectProperties.Get<int>("Whitespace", total));
Assert.AreEqual(2, projectProperties.Get<int>("Count", paragraph));
Assert.AreEqual(4, projectProperties.Get<int>("Words", paragraph));
Assert.AreEqual(12, projectProperties.Get<int>("Characters", paragraph));
Assert.AreEqual(10, projectProperties.Get<int>("Non-Whitespace", paragraph));
Assert.AreEqual(2, projectProperties.Get<int>("Whitespace", paragraph));
}
[Test]
public void SingleBlockTwoWords()
{
// Arrange
ProjectBlockCollection blocks;
BlockCommandSupervisor commands;
WordCounterProjectPlugin projectPlugin;
SetupPlugin(out blocks, out commands, out projectPlugin);
// Act
commands.InsertText(blocks[0], 0, "Line 1");
blocks.Project.Plugins.WaitForBlockAnalzyers();
// Assert
var path = new HierarchicalPath("/Plugins/Word Counter");
var total = new HierarchicalPath("Total", path);
var paragraph = new HierarchicalPath("Block Types/Paragraph", path);
Project project = blocks.Project;
PropertiesDictionary blockProperties = blocks[0].Properties;
PropertiesDictionary projectProperties = project.Properties;
Assert.AreEqual(1, project.Plugins.Controllers.Count);
Assert.AreEqual(2, blockProperties.Get<int>("Words", total));
Assert.AreEqual(6, blockProperties.Get<int>("Characters", total));
Assert.AreEqual(5, blockProperties.Get<int>("Non-Whitespace", total));
Assert.AreEqual(1, blockProperties.Get<int>("Whitespace", total));
Assert.AreEqual(1, blockProperties.Get<int>("Count", paragraph));
Assert.AreEqual(2, blockProperties.Get<int>("Words", paragraph));
Assert.AreEqual(6, blockProperties.Get<int>("Characters", paragraph));
Assert.AreEqual(5, blockProperties.Get<int>("Non-Whitespace", paragraph));
Assert.AreEqual(1, blockProperties.Get<int>("Whitespace", paragraph));
Assert.AreEqual(2, projectProperties.Get<int>("Words", total));
Assert.AreEqual(6, projectProperties.Get<int>("Characters", total));
Assert.AreEqual(5, projectProperties.Get<int>("Non-Whitespace", total));
Assert.AreEqual(1, projectProperties.Get<int>("Whitespace", total));
Assert.AreEqual(1, projectProperties.Get<int>("Count", paragraph));
Assert.AreEqual(2, projectProperties.Get<int>("Words", paragraph));
Assert.AreEqual(6, projectProperties.Get<int>("Characters", paragraph));
Assert.AreEqual(5, projectProperties.Get<int>("Non-Whitespace", paragraph));
Assert.AreEqual(1, projectProperties.Get<int>("Whitespace", paragraph));
}
/// <summary>
/// Configures the environment to load the plugin manager and verify we
/// have access to the ImmediateCorrectionPlugin.
/// </summary>
private void SetupPlugin(
out ProjectBlockCollection blocks,
out BlockCommandSupervisor commands,
out WordCounterProjectPlugin projectPlugin)
{
// Start getting us a simple plugin manager.
var plugin = new WordCounterPlugin();
var pluginManager = new PluginManager(plugin);
PluginManager.Instance = pluginManager;
// Create a project and pull out the useful properties we'll use to
// make changes.
var project = new Project();
blocks = project.Blocks;
commands = project.Commands;
// Load in the immediate correction editor.
if (!project.Plugins.Add("Word Counter"))
{
// We couldn't load it for some reason.
throw new ApplicationException("Cannot load word counter plugin.");
}
// Pull out the controller for the correction and cast it (since we know
// what type it is).
ProjectPluginController pluginController = project.Plugins.Controllers[0];
projectPlugin = (WordCounterProjectPlugin) pluginController.ProjectPlugin;
// Set up logging for the controller.
WordCounterProjectPlugin.Logger = Console.WriteLine;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Mo<NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
namespace AuthorIntrusion.Common.Blocks
{
/// <summary>
/// BlockType uniquely identifies the various types of blocks inside a project.
/// There are two categories of block types. System blocks are ones critical to
/// the system and can be deleted. User blocks are customizable to organize
/// a document.
///
/// In both cases, the bulk of the formatting and display is based on block types.
/// </summary>
public class BlockType
{
#region Properties
/// <summary>
/// Gets or sets a value indicating whether this block type can contain
/// other blocks inside it. Examples would be scenes and chapters where as
/// paragraphs would not be structural.
/// </summary>
/// <value>
/// <c>true</c> if this instance is structural; otherwise, <c>false</c>.
/// </value>
public bool IsStructural { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is a system block
/// type.
/// </summary>
public bool IsSystem { get; set; }
/// <summary>
/// Gets or sets the unique name for the block.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets the Supervisor that handles the block types.
/// </summary>
public BlockTypeSupervisor Supervisor { get; private set; }
#endregion
#region Methods
public override string ToString()
{
return string.Format("BlockType({0})", Name);
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="BlockType"/> class.
/// </summary>
/// <param name="supervisor">The Supervisor.</param>
public BlockType(BlockTypeSupervisor supervisor)
{
Supervisor = supervisor;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
namespace AuthorIntrusion.Common.Blocks.Locking
{
/// <summary>
/// An enumeration of requested lock types for locking collections and blocks.
/// </summary>
public enum RequestLock
{
/// <summary>
/// Requests a read-only lock.
/// </summary>
Read,
/// <summary>
/// Requests a read lock that can be upgraded to a write.
/// </summary>
UpgradableRead,
/// <summary>
/// Requests a write lock.
/// </summary>
Write,
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
namespace AuthorIntrusion.Common.Plugins
{
/// <summary>
/// Defines the signature for a plugin that is used at the project level. This
/// differs from IEnvironmentPlugin in that each project has their own plugins
/// (some can be duplicates of the same IPlugin) along with their own
/// configuration.
/// </summary>
public interface IProjectPluginProviderPlugin: IPlugin
{
#region Properties
/// <summary>
/// Gets a value indicating whether there can be multiple controllers
/// for this plugin inside a given project. This would be false for plugins
/// that have little or no configuration or that their operation would
/// conflict with each other. It would be true for customizable plugins
/// such as ones that allow for word highlighting or specific grammer rules.
/// </summary>
/// <value>
/// <c>true</c> if multiple controllers are allowed; otherwise, <c>false</c>.
/// </value>
bool AllowMultiple { get; }
#endregion
#region Methods
/// <summary>
/// Gets a project-specific controller for the plugin.
/// </summary>
/// <param name="project">The project.</param>
/// <returns>A controller for the project.</returns>
IProjectPlugin GetProjectPlugin(Project project);
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace AuthorIntrusion.Common.Persistence
{
/// <summary>
/// Defines the serializable settings used to control the filesystem persistence
/// project plugin.
///
/// All of the string variables in here can have project macros in them, which are
/// expanded at the point of saving.
/// </summary>
[XmlRoot(XmlElementName, Namespace = XmlConstants.ProjectNamespace)]
public class FilesystemPersistenceSettings: IXmlSerializable
{
#region Properties
public string ContentDataFilename { get; set; }
public string ContentFilename { get; set; }
public string DataDirectory { get; set; }
public string ExternalSettingsDirectory { get; set; }
public string ExternalSettingsFilename { get; set; }
public string InternalContentDataFilename { get; set; }
public string InternalContentDirectory { get; set; }
public string InternalContentFilename { get; set; }
public bool NeedsProjectDirectory
{
get { return string.IsNullOrWhiteSpace(ProjectDirectory); }
}
public bool NeedsProjectFilename
{
get { return string.IsNullOrWhiteSpace(ProjectFilename); }
}
public string ProjectDirectory { get; set; }
public string ProjectFilename { get; set; }
/// <summary>
/// Gets or sets the filename for the settings file. This will contains the
/// settings for plugins and configuration settings will be stored here.
///
/// External settings are identified by the ExternalSettingsFilename property.
/// </summary>
/// <remarks>
/// This can have macro substitutions (e.g., "{ProjectDir}") in the name
/// which will be expanded during use.
/// </remarks>
public string SettingsFilename { get; set; }
public string StructureFilename { get; set; }
#endregion
#region Methods
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
// We are already at the starting point of this element, so read until the
// end.
string elementName = reader.LocalName;
// Read until we get to the end element.
while (reader.Read())
{
// If we aren't in our namespace, we don't need to bother.
if (reader.NamespaceURI != XmlConstants.ProjectNamespace)
{
continue;
}
// If we got to the end of the node, then stop reading.
if (reader.LocalName == elementName)
{
return;
}
// Look for a key, if we have it, set that value.
if (reader.NodeType == XmlNodeType.Element
&& reader.LocalName == "setting")
{
// Set has two parameters. We use the key to figure out which
// variable to set.
string key = reader["key"];
string value = reader["value"];
switch (key)
{
case "ContentDataFilename":
ContentDataFilename = value;
break;
case "ContentFilename":
ContentFilename = value;
break;
case "DataDirectory":
DataDirectory = value;
break;
case "ExternalSettingsDirectory":
ExternalSettingsDirectory = value;
break;
case "ExternalSettingsFilename":
ExternalSettingsFilename = value;
break;
case "InternalContentDataFilename":
InternalContentDataFilename = value;
break;
case "InternalContentDirectory":
InternalContentDirectory = value;
break;
case "InternalContentFilename":
InternalContentFilename = value;
break;
case "ProjectDirectory":
ProjectDirectory = value;
break;
case "ProjectFilename":
ProjectFilename = value;
break;
case "SettingsFilename":
SettingsFilename = value;
break;
case "StructureFilename":
StructureFilename = value;
break;
}
}
}
}
/// <summary>
/// Configures a standard file layout that uses an entire directory for
/// the layout. This layout is set up to optimize the handling of the
/// project's content, settings, and data with a source control system, such as
/// Git.
/// </summary>
public void SetIndividualDirectoryLayout()
{
// Setting project directory to null and setting the filename tells
// any calling method that we need an output directory instead of a filename
// dialog box.
ProjectDirectory = null;
ProjectFilename = "{ProjectDirectory}/Project.aiproj";
DataDirectory = "{ProjectDirectory}/Data";
SettingsFilename = "{ProjectDirectory}/Settings.xml";
StructureFilename = "{ProjectDirectory}/Structure.xml";
ContentFilename = "{ProjectDirectory}/Content.xml";
ContentDataFilename = "{DataDirectory}/Content Data.xml";
InternalContentDirectory = "{ProjectDirectory}/Content";
InternalContentFilename = "{InternalContentDirectory}/{ContentName}.xml";
InternalContentDataFilename =
"{DataDirectory}/Content/{ContentName} Data.xml";
ExternalSettingsDirectory = "{ProjectDirectory}/Settings";
ExternalSettingsFilename =
"{ExternalSettingsDirectory}/{SettingsProviderName}/{SettingsName}.xml";
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The <see cref="T:System.Xml.XmlWriter" /> stream to which the object is serialized.</param>
public void WriteXml(XmlWriter writer)
{
// Always start with the version field, because that will control how
// we read it back in.
writer.WriteElementString("version", XmlConstants.ProjectNamespace, "1");
// Write out the various properties.
WriteSetting(writer, "ContentDataFilename", ContentDataFilename);
WriteSetting(writer, "ContentFilename", ContentFilename);
WriteSetting(writer, "DataDirectory", DataDirectory);
WriteSetting(writer, "ExternalSettingsDirectory", ExternalSettingsDirectory);
WriteSetting(writer, "ExternalSettingsFilename", ExternalSettingsFilename);
WriteSetting(
writer, "InternalContentDataFilename", InternalContentDataFilename);
WriteSetting(writer, "InternalContentDirectory", InternalContentDirectory);
WriteSetting(writer, "InternalContentFilename", InternalContentFilename);
WriteSetting(writer, "ProjectDirectory", ProjectDirectory);
WriteSetting(writer, "ProjectFilename", ProjectFilename);
WriteSetting(writer, "SettingsFilename", SettingsFilename);
WriteSetting(writer, "StructureFilename", StructureFilename);
}
/// <summary>
/// Writes the setting value to an XML writer.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
private void WriteSetting(
XmlWriter writer,
string key,
string value)
{
if (!string.IsNullOrWhiteSpace(value))
{
writer.WriteStartElement("setting", XmlConstants.ProjectNamespace);
writer.WriteAttributeString("key", key);
writer.WriteAttributeString("value", value);
writer.WriteEndElement();
}
}
#endregion
#region Fields
public const string XmlElementName = "filesystem-persistence-settings";
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
namespace AuthorIntrusion.Common.Plugins
{
/// <summary>
/// Defines a specific instance of an IPlugin along with its configuration,
/// current state, and settings.
/// </summary>
public class ProjectPluginController
{
#region Properties
public bool IsBlockAnalyzer
{
get
{
bool isImmediateEditor = ProjectPlugin is IBlockAnalyzerProjectPlugin;
return isImmediateEditor;
}
}
public bool IsImmediateEditor
{
get
{
bool isImmediateEditor = ProjectPlugin is IImmediateEditorProjectPlugin;
return isImmediateEditor;
}
}
public string Name
{
get { return Plugin.Key; }
}
public IProjectPluginProviderPlugin Plugin { get; set; }
public IProjectPlugin ProjectPlugin { get; set; }
public PluginSupervisor Supervisor { get; set; }
#endregion
#region Constructors
public ProjectPluginController(
PluginSupervisor supervisor,
IProjectPluginProviderPlugin plugin)
{
Supervisor = supervisor;
Plugin = plugin;
ProjectPlugin = plugin.GetProjectPlugin(supervisor.Project);
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Plugins;
namespace AuthorIntrusion.Common.Persistence
{
public class PersistenceFrameworkProjectPlugin: IProjectPlugin
{
#region Properties
public string Key
{
get { return "Persistence Framework"; }
}
#endregion
#region Constructors
public PersistenceFrameworkProjectPlugin(Project project)
{
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Mo<NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
using MfGames.Commands;
namespace AuthorIntrusion.Common.Commands
{
public class DeleteBlockCommand: IBlockCommand
{
#region Properties
public bool CanUndo
{
get { return true; }
}
/// <summary>
/// Gets or sets a value indicating whether the operation should ensure
/// there is always one line in the block buffer. In most cases, this should
/// remain false except for undo operations.
/// </summary>
/// <value>
/// <c>true</c> if no minimum line processing should be done; otherwise, <c>false</c>.
/// </value>
public bool IgnoreMinimumLines { get; set; }
public bool IsTransient
{
get { return false; }
}
public DoTypes UpdateTextPosition { get; set; }
#endregion
#region Methods
public void Do(BlockCommandContext context)
{
using (context.Blocks.AcquireLock(RequestLock.Write))
{
// We need the index of the block so we can restore it back into
// its place.
Block block = context.Blocks[blockKey];
removedBlockIndex = context.Blocks.IndexOf(blockKey);
removedBlock = block;
// Delete the block from the list.
context.Blocks.Remove(block);
// If we have no more blocks, then we need to ensure we have a minimum
// number of blocks.
addedBlankBlock = null;
if (!IgnoreMinimumLines
&& context.Blocks.Count == 0)
{
// Create a new placeholder block, which is blank.
addedBlankBlock = new Block(
context.Blocks, block.Project.BlockTypes.Paragraph);
context.Blocks.Add(addedBlankBlock);
if (UpdateTextPosition.HasFlag(DoTypes.Do))
{
context.Position = new BlockPosition(addedBlankBlock.BlockKey, 0);
}
}
else if (!IgnoreMinimumLines)
{
// We have to figure out where the cursor would be after this operation.
// Ideally, this would be the block in the current position, but if this
// is the last line, then use that.
if (UpdateTextPosition.HasFlag(DoTypes.Do))
{
context.Position =
new BlockPosition(
removedBlockIndex < context.Blocks.Count
? context.Blocks[removedBlockIndex].BlockKey
: context.Blocks[removedBlockIndex - 1].BlockKey,
0);
}
}
}
}
public void Redo(BlockCommandContext state)
{
Do(state);
}
public void Undo(BlockCommandContext context)
{
using (context.Blocks.AcquireLock(RequestLock.Write))
{
// Insert in the old block.
context.Blocks.Insert(removedBlockIndex, removedBlock);
// Set the last text position.
if (UpdateTextPosition.HasFlag(DoTypes.Undo))
{
context.Position = new BlockPosition(blockKey, removedBlock.Text.Length);
}
// Remove the blank block, if we added one.
if (addedBlankBlock != null)
{
context.Blocks.Remove(addedBlankBlock);
addedBlankBlock = null;
}
}
}
#endregion
#region Constructors
public DeleteBlockCommand(BlockKey blockKey)
{
this.blockKey = blockKey;
UpdateTextPosition = DoTypes.All;
}
#endregion
#region Fields
private Block addedBlankBlock;
private readonly BlockKey blockKey;
private Block removedBlock;
private int removedBlockIndex;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
namespace AuthorIntrusion.Plugins.Spelling.Common
{
/// <summary>
/// Defines the correcteness of a given word for a plugin.
/// </summary>
public enum WordCorrectness: byte
{
/// <summary>
/// Indicates that the corrected cannot be determined by the given
/// spelling plugin.
/// </summary>
Indeterminate,
/// <summary>
/// Indicates that the plugin has determined the word was correctly
/// spelled.
/// </summary>
Correct,
/// <summary>
/// Indicates that the plugin has determined that the word was
/// incorrect and needs correction.
/// </summary>
Incorrect,
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using AuthorIntrusion.Plugins.Spelling.Common;
using AuthorIntrusion.Plugins.Spelling.NHunspell.Interop;
namespace AuthorIntrusion.Plugins.Spelling.NHunspell
{
/// <summary>
/// A P/Invoke-based spelling plugin for Hunspell.
/// </summary>
public class PInvokeSpellingProjectPlugin: CommonSpellingProjectPlugin
{
#region Methods
public override IEnumerable<SpellingSuggestion> GetSuggestions(string word)
{
// Get the suggestions from Hunspell.
string[] words = hunspell.Suggest(word);
// Wrap each suggested word in a spelling suggestion.
var suggestions = new List<SpellingSuggestion>();
foreach (string suggestedWord in words)
{
var suggestion = new SpellingSuggestion(suggestedWord);
suggestions.Add(suggestion);
}
// Return the resulting suggestions.
return suggestions;
}
public override WordCorrectness IsCorrect(string word)
{
bool results = hunspell.CheckWord(word);
return results
? WordCorrectness.Correct
: WordCorrectness.Incorrect;
}
#endregion
#region Constructors
public PInvokeSpellingProjectPlugin(
string affixFilename,
string dictionaryFilename)
{
// Create the Hunspell wrapper.
hunspell = new Hunspell(affixFilename, dictionaryFilename);
}
#endregion
#region Fields
private readonly Hunspell hunspell;
#endregion
}
}
<file_sep>// Copyright 2012-2013 Mo<NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
namespace AuthorIntrusion.Common.Plugins
{
/// <summary>
/// Defines a controller that listens to changes to a block type change.
/// </summary>
public interface IBlockTypeProjectPlugin: IBlockAnalyzerProjectPlugin
{
#region Methods
/// <summary>
/// Indicates that a block changed its block type from oldBlockType into the
/// currently assigned one.
/// </summary>
/// <param name="block">The block.</param>
/// <param name="oldBlockType">Old type of the block.</param>
void ChangeBlockType(
Block block,
BlockType oldBlockType);
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Text;
using AuthorIntrusion.Common.Blocks;
using MfGames.Commands.TextEditing;
namespace AuthorIntrusion.Common.Commands
{
public class InsertTextFromBlock: MultipleBlockKeyCommand,
IInsertTextFromTextRangeCommand<BlockCommandContext>
{
#region Properties
public CharacterPosition CharacterBegin { get; private set; }
public CharacterPosition CharacterEnd { get; private set; }
public BlockPosition DestinationPosition { get; private set; }
public BlockKey SourceBlockKey { get; private set; }
#endregion
#region Methods
protected override void Do(
BlockCommandContext context,
Block block)
{
// Grab the text from the source line.
string sourceLine = context.Blocks[SourceBlockKey].Text;
int sourceBegin = CharacterBegin.GetCharacterIndex(
sourceLine, CharacterEnd, WordSearchDirection.Left);
int sourceEnd = CharacterEnd.GetCharacterIndex(
sourceLine, CharacterBegin, WordSearchDirection.Right);
string sourceText = sourceLine.Substring(
sourceBegin, sourceEnd - sourceBegin);
// Insert the text from the source line into the destination.
string destinationLine = block.Text;
var buffer = new StringBuilder(destinationLine);
int characterIndex =
DestinationPosition.TextIndex.GetCharacterIndex(destinationLine);
buffer.Insert(characterIndex, sourceText);
// Save the source text length so we can delete it.
sourceLength = sourceText.Length;
originalCharacterIndex = characterIndex;
// Set the line in the buffer.
destinationLine = buffer.ToString();
block.SetText(destinationLine);
}
protected override void Undo(
BlockCommandContext context,
Block block)
{
// Grab the line from the line buffer.
string lineText = block.Text;
var buffer = new StringBuilder(lineText);
// Normalize the character ranges.
buffer.Remove(originalCharacterIndex, sourceLength);
// Set the line in the buffer.
lineText = buffer.ToString();
block.SetText(lineText);
}
#endregion
#region Constructors
public InsertTextFromBlock(
BlockPosition destinationPosition,
BlockKey sourceBlockKey,
CharacterPosition characterBegin,
CharacterPosition characterEnd)
: base(destinationPosition.BlockKey)
{
DestinationPosition = destinationPosition;
SourceBlockKey = sourceBlockKey;
CharacterBegin = characterBegin;
CharacterEnd = characterEnd;
}
#endregion
#region Fields
private int originalCharacterIndex;
private int sourceLength;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.IO;
using System.Text;
using System.Xml;
using AuthorIntrusion.Common.Projects;
using MfGames.Extensions.System.IO;
namespace AuthorIntrusion.Common.Persistence
{
public abstract class PersistenceReaderWriterBase<TSettings>
{
#region Properties
public ProjectMacros Macros { get; set; }
public Project Project { get; set; }
public TSettings Settings { get; set; }
#endregion
#region Methods
/// <summary>
/// Creates the common XML settings for most writers.
/// </summary>
/// <returns></returns>
protected static XmlWriterSettings CreateXmlSettings()
{
var settings = new XmlWriterSettings
{
Encoding = Encoding.UTF8,
Indent = true,
IndentChars = "\t",
};
return settings;
}
/// <summary>
/// Gets the XML reader for a given file.
/// </summary>
/// <remarks>
/// It is responsiblity of the calling method to close the given reader.
/// </remarks>
/// <param name="fileInfo">The file info.</param>
/// <returns>An XML reader for the file.</returns>
protected XmlReader GetXmlReader(FileInfo fileInfo)
{
FileStream stream = fileInfo.Open(
FileMode.Open, FileAccess.Read, FileShare.Read);
XmlReader reader = XmlReader.Create(stream);
return reader;
}
/// <summary>
/// Gets the XML reader for a file, either the given project reader or
/// a constructed reader based on the filename if the filename expands
/// into a non-blank value.
/// </summary>
/// <param name="projectReader">The project reader.</param>
/// <param name="filename">The filename.</param>
/// <param name="createdReader">if set to <c>true</c> then the reader was created.</param>
/// <returns>The XML reader to use.</returns>
protected XmlReader GetXmlReader(
XmlReader projectReader,
string filename,
out bool createdReader)
{
// Try to resolve the filename. If this is null or empty, then we
// use the project reader.
string expandedFilename = Macros.ExpandMacros(filename);
if (string.IsNullOrWhiteSpace(expandedFilename))
{
createdReader = false;
return projectReader;
}
// We need to create a new reader.
var file = new FileInfo(expandedFilename);
XmlReader reader = GetXmlReader(file);
createdReader = true;
return reader;
}
/// <summary>
/// Gets the macro or project XML writer. If the given variable expands to
/// a value, an XML writer is created and returned. Otherwise, the given
/// project writer is used instead.
/// </summary>
/// <param name="projectWriter">The project writer.</param>
/// <param name="macros">The macros.</param>
/// <param name="variable">The variable.</param>
/// <param name="createdWriter">if set to <c>true</c> [created writer].</param>
/// <returns></returns>
protected static XmlWriter GetXmlWriter(
XmlWriter projectWriter,
ProjectMacros macros,
string variable,
out bool createdWriter)
{
// Expand the variable to get the filename.
string filename = macros.ExpandMacros(variable);
// If the value is null, then we use the project writer.
if (string.IsNullOrWhiteSpace(filename))
{
createdWriter = false;
return projectWriter;
}
// Create the writer and return it.
var file = new FileInfo(filename);
XmlWriter writer = GetXmlWriter(file);
createdWriter = true;
return writer;
}
/// <summary>
/// Constructs an XML writer and returns it.
/// </summary>
/// <param name="file">The file.</param>
/// <returns></returns>
protected static XmlWriter GetXmlWriter(FileInfo file)
{
// Make sure the parent directory exists for this writer.
file.EnsureParentExists();
// Create an XML writer for this file and return it.
XmlWriterSettings xmlSettings = CreateXmlSettings();
XmlWriter writer = XmlWriter.Create(file.FullName, xmlSettings);
// Start the writer's document tag.
writer.WriteStartDocument(true);
// Return the resulting writer.
return writer;
}
#endregion
#region Constructors
protected PersistenceReaderWriterBase(
PersistenceReaderWriterBase<TSettings> baseReader)
: this(baseReader.Project, baseReader.Settings, baseReader.Macros)
{
}
protected PersistenceReaderWriterBase(
Project project,
TSettings settings,
ProjectMacros macros)
{
Project = project;
Settings = settings;
Macros = macros;
}
#endregion
#region Fields
protected const string ProjectNamespace = XmlConstants.ProjectNamespace;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Text;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
using AuthorIntrusion.Common.Extensions;
using MfGames.Commands;
using MfGames.Commands.TextEditing;
namespace AuthorIntrusion.Common.Commands
{
public class InsertTextFromIndexedBlock: IBlockCommand,
IInsertTextFromTextRangeCommand<BlockCommandContext>
{
#region Properties
public bool CanUndo
{
get { return true; }
}
public TextPosition DestinationPosition { get; private set; }
public bool IsTransient
{
get { return false; }
}
public SingleLineTextRange Range { get; private set; }
public DoTypes UpdateTextPosition { get; set; }
public DoTypes UpdateTextSelection { get; set; }
protected int SourceBlockIndex { get; private set; }
#endregion
#region Methods
public void Do(BlockCommandContext context)
{
// Grab the destination block and make sure everything is locked properly.
Block block;
using (
context.Blocks.AcquireBlockLock(
RequestLock.Write,
RequestLock.Write,
(int) DestinationPosition.LinePosition,
out block))
{
// Grab the text from the source line.
int lineIndex,
sourceBegin,
sourceEnd;
string sourceLine;
Range.GetBeginAndEndCharacterIndices(
context.Blocks,
out lineIndex,
out sourceBegin,
out sourceEnd,
out sourceLine);
string sourceText = sourceLine.Substring(
sourceBegin, sourceEnd - sourceBegin);
// Insert the text from the source line into the destination.
string destinationLine = block.Text;
var buffer = new StringBuilder(destinationLine);
int characterIndex =
DestinationPosition.CharacterPosition.GetCharacterIndex(destinationLine);
buffer.Insert(characterIndex, sourceText);
// Save the source text length so we can delete it.
sourceLength = sourceText.Length;
originalCharacterIndex = characterIndex;
// Set the line in the buffer.
destinationLine = buffer.ToString();
block.SetText(destinationLine);
// Set the position of this command.
if (UpdateTextPosition.HasFlag(DoTypes.Do))
{
context.Position = new BlockPosition(block.BlockKey, characterIndex);
}
}
}
public void Redo(BlockCommandContext context)
{
Do(context);
}
public void Undo(BlockCommandContext context)
{
// Grab the destination block and make sure everything is locked properly.
Block block;
using (
context.Blocks.AcquireBlockLock(
RequestLock.Write,
RequestLock.Write,
(int) DestinationPosition.LinePosition,
out block))
{
// Grab the line from the line buffer.
string lineText = block.Text;
var buffer = new StringBuilder(lineText);
// Normalize the character ranges.
buffer.Remove(originalCharacterIndex, sourceLength);
// Set the line in the buffer.
lineText = buffer.ToString();
block.SetText(lineText);
// Set the position of this command.
if (UpdateTextPosition.HasFlag(DoTypes.Undo))
{
context.Position = new BlockPosition(
block.BlockKey, DestinationPosition.CharacterPosition);
}
}
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="InsertTextFromBlock" /> class.
/// </summary>
/// <param name="destinationPosition">The position to insert the text into.</param>
/// <param name="range">The range.</param>
public InsertTextFromIndexedBlock(
TextPosition destinationPosition,
SingleLineTextRange range)
{
DestinationPosition = destinationPosition;
Range = range;
}
#endregion
#region Fields
private int originalCharacterIndex;
private int sourceLength;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using MfGames.Commands.TextEditing;
namespace AuthorIntrusion.Common.Blocks
{
/// <summary>
/// Identifies a location within a specific block.
/// </summary>
public struct BlockPosition: IEquatable<BlockPosition>
{
#region Properties
public BlockKey BlockKey { get; private set; }
public CharacterPosition TextIndex { get; private set; }
#endregion
#region Methods
public bool Equals(BlockPosition other)
{
return BlockKey.Equals(other.BlockKey)
&& (int) TextIndex == (int) other.TextIndex;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
return obj is BlockPosition && Equals((BlockPosition) obj);
}
public override int GetHashCode()
{
unchecked
{
return (BlockKey.GetHashCode() * 397) ^ (int) TextIndex;
}
}
public override string ToString()
{
return string.Format(
"BlockPosition ({0}, {1})", BlockKey.Id.ToString("X8"), TextIndex.Index);
}
#endregion
#region Operators
public static bool operator ==(BlockPosition left,
BlockPosition right)
{
return left.Equals(right);
}
public static bool operator !=(BlockPosition left,
BlockPosition right)
{
return !left.Equals(right);
}
#endregion
#region Constructors
static BlockPosition()
{
Empty = new BlockPosition();
}
public BlockPosition(
BlockKey blockKey,
CharacterPosition textIndex)
: this()
{
BlockKey = blockKey;
TextIndex = textIndex;
}
public BlockPosition(
Block block,
CharacterPosition textIndex)
: this(block.BlockKey, textIndex)
{
}
public BlockPosition(
BlockKey blockKey,
int character)
: this(blockKey, (CharacterPosition) character)
{
}
public BlockPosition(
Block block,
int character)
: this(block.BlockKey, (CharacterPosition) character)
{
}
#endregion
#region Fields
/// <summary>
/// Gets the empty block position which points to an all zero key and position.
/// </summary>
public static readonly BlockPosition Empty;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
using MfGames.Commands;
using MfGames.Commands.TextEditing;
namespace AuthorIntrusion.Common.Commands
{
/// <summary>
/// Operation to insert text into a single block at a given position.
/// </summary>
public class InsertTextCommand: BlockPositionCommand
{
#region Properties
protected string Text { get; private set; }
#endregion
#region Methods
/// <summary>
/// Performs the command on the given block.
/// </summary>
/// <param name="context"></param>
/// <param name="block">The block to perform the action on.</param>
/// <param name="project">The project that contains the current state.</param>
protected override void Do(
BlockCommandContext context,
Block block)
{
// Save the previous text so we can undo it.
previousText = block.Text;
// Figure out what the new text string would be.
int textIndex = new CharacterPosition(TextIndex).GetCharacterIndex(
block.Text);
string newText = block.Text.Insert(textIndex, Text);
// Set the new text into the block. This will fire various events to
// trigger the immediate and background processing.
block.SetText(newText);
// After we insert text, we need to give the immediate editor plugins a
// chance to made any alterations to the output.
block.Project.Plugins.ProcessImmediateEdits(
context, block, textIndex + Text.Length);
// Set the new position in the buffer.
if (UpdateTextPosition.HasFlag(DoTypes.Do))
{
context.Position = new BlockPosition(BlockKey, textIndex + Text.Length);
}
}
protected override void Undo(
BlockCommandContext context,
Block block)
{
block.SetText(previousText);
// Set the new cursor position.
int textIndex = BlockPosition.TextIndex.GetCharacterIndex(previousText);
if (UpdateTextPosition.HasFlag(DoTypes.Undo))
{
context.Position = new BlockPosition(BlockPosition.BlockKey, textIndex);
}
}
#endregion
#region Constructors
public InsertTextCommand(
BlockPosition position,
string text)
: base(position)
{
Text = text;
}
public InsertTextCommand(
TextPosition textPosition,
string text)
: base(textPosition)
{
Text = text;
}
#endregion
#region Fields
private string previousText;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using System.Xml;
using AuthorIntrusion.Common.Blocks;
namespace AuthorIntrusion.Common.Persistence.Filesystem
{
public class FilesystemPersistenceStructureWriter:
PersistenceReaderWriterBase<FilesystemPersistenceSettings>
{
#region Methods
/// <summary>
/// Writes the structure file, to either the project Writer or the Structure
/// file depending on the persistence settings.
/// </summary>
/// <param name="projectWriter">The project Writer.</param>
public void Write(XmlWriter projectWriter)
{
// Figure out which Writer we'll be using.
bool createdWriter;
XmlWriter writer = GetXmlWriter(
projectWriter, Macros, Settings.StructureFilename, out createdWriter);
// Create an order list of block types so we have a reliable order.
var blockTypeNames = new List<string>();
blockTypeNames.AddRange(Project.BlockTypes.BlockTypes.Keys);
blockTypeNames.Sort();
// Start by creating the initial element.
writer.WriteStartElement("structure", ProjectNamespace);
writer.WriteElementString("version", "1");
// Write out the blocks types first.
writer.WriteStartElement("block-types", ProjectNamespace);
foreach (string blockTypeName in blockTypeNames)
{
// We don't write out system types since they are controlled via code.
BlockType blockType = Project.BlockTypes[blockTypeName];
if (blockType.IsSystem)
{
continue;
}
// Write out this item.
writer.WriteStartElement("block-type", ProjectNamespace);
// Write out the relevant fields.
writer.WriteElementString("name", ProjectNamespace, blockType.Name);
writer.WriteElementString(
"is-structural", ProjectNamespace, blockType.IsStructural.ToString());
// Finish up the item element.
writer.WriteEndElement();
}
writer.WriteEndElement();
// Finish up the tag.
writer.WriteEndElement();
// If we created the Writer, close it.
if (createdWriter)
{
writer.Dispose();
}
}
#endregion
#region Constructors
public FilesystemPersistenceStructureWriter(
PersistenceReaderWriterBase<FilesystemPersistenceSettings> baseWriter)
: base(baseWriter)
{
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Collections.Generic;
using System.Threading;
using AuthorIntrusion.Common.Blocks.Locking;
using AuthorIntrusion.Common.Plugins;
namespace AuthorIntrusion.Common.Blocks
{
/// <summary>
/// A block is the primary structural element inside a ownerCollection. It
/// represents various paragraphs (normal, epigraphs) as well as some
/// organizational units (chapters, scenes).
/// </summary>
public class Block: IPropertiesContainer
{
#region Properties
public BlockKey BlockKey { get; private set; }
/// <summary>
/// Gets or sets the type of the block.
/// </summary>
public BlockType BlockType
{
get { return blockType; }
}
/// <summary>
/// Gets the owner collection associated with this block.
/// </summary>
public ProjectBlockCollection Blocks { get; private set; }
public bool IsWriteLockHeld
{
get { return accessLock.IsWriteLockHeld; }
}
public Project Project
{
get { return Blocks.Project; }
}
/// <summary>
/// Gets the properties associated with the block.
/// </summary>
public PropertiesDictionary Properties { get; private set; }
/// <summary>
/// Gets or sets the text associated with the block.
/// </summary>
public string Text
{
get { return text; }
}
public TextSpanCollection TextSpans { get; private set; }
public int Version
{
get { return version; }
}
#endregion
#region Methods
public IDisposable AcquireBlockLock(RequestLock requestedBlockLock)
{
return AcquireBlockLock(RequestLock.Read, requestedBlockLock);
}
public IDisposable AcquireBlockLock(
RequestLock requestedCollectionLock,
RequestLock requestedBlockLock)
{
IDisposable acquiredLock = Blocks.AcquireBlockLock(
requestedCollectionLock, requestedBlockLock, this);
return acquiredLock;
}
/// <summary>
/// Acquires a lock on a block while using the given opaque lock object for
/// the collection lock. When the block's lock is disposed, so will the
/// collection lock.
///
/// <code>using (blocks.AcquireLock(accessLock)) {}</code>
/// </summary>
/// <returns>An opaque lock object that will release lock on disposal.</returns>
public IDisposable AcquireLock(
IDisposable collectionLock,
RequestLock requestedLock)
{
return new BlockLock(collectionLock, accessLock, requestedLock);
}
/// <summary>
/// Adds a flag that a plugin has performed its analysis on the block.
/// </summary>
/// <param name="plugin">The plugin.</param>
public void AddAnalysis(IBlockAnalyzerProjectPlugin plugin)
{
using (AcquireBlockLock(RequestLock.Write))
{
previouslyAnalyzedPlugins.Add(plugin);
}
}
/// <summary>
/// Clears the analysis state of a block to indicate that all analysis
/// needs to be completed on the task.
/// </summary>
public void ClearAnalysis()
{
using (AcquireBlockLock(RequestLock.Write))
{
previouslyAnalyzedPlugins.Clear();
}
}
/// <summary>
/// Clears the analysis for a single plugin.
/// </summary>
/// <param name="plugin">The plugin.</param>
public void ClearAnalysis(IBlockAnalyzerProjectPlugin plugin)
{
using (AcquireBlockLock(RequestLock.Write))
{
previouslyAnalyzedPlugins.Remove(plugin);
}
}
/// <summary>
/// Retrieves a snapshot of the current block analysis on the block.
/// </summary>
/// <returns></returns>
public HashSet<IBlockAnalyzerProjectPlugin> GetAnalysis()
{
using (AcquireBlockLock(RequestLock.Read))
{
var results =
new HashSet<IBlockAnalyzerProjectPlugin>(previouslyAnalyzedPlugins);
return results;
}
}
/// <summary>
/// Determines whether the specified block version is stale (the version had
/// changed compared to the supplied version).
/// </summary>
/// <param name="blockVersion">The block version.</param>
/// <returns>
/// <c>true</c> if the specified block version is stale; otherwise, <c>false</c>.
/// </returns>
public bool IsStale(int blockVersion)
{
// Ensure we have a lock in effect.
if (!accessLock.IsReadLockHeld
&& !accessLock.IsUpgradeableReadLockHeld
&& !accessLock.IsWriteLockHeld)
{
throw new InvalidOperationException(
"Cannot check block status without a read, upgradable read, or write lock on the block.");
}
// Determine if we have the same version.
return version != blockVersion;
}
/// <summary>
/// Indicates that the text spans of a block have changed significantly.
/// </summary>
public void RaiseTextSpansChanged()
{
Project.Blocks.RaiseTextSpansChanged(this);
}
/// <summary>
/// Sets the type of the block and fires the events to update the internal
/// structure. If the block type is identical, no events are fired.
/// </summary>
/// <param name="newBlockType">New type of the block.</param>
public void SetBlockType(BlockType newBlockType)
{
// Make sure we have a sane state.
if (newBlockType == null)
{
throw new ArgumentNullException("newBlockType");
}
if (Blocks.Project != newBlockType.Supervisor.Project)
{
throw new InvalidOperationException(
"Cannot assign a block type with a different Project than the block's Project.");
}
// We only do things if we are changing the block type.
bool changed = blockType != newBlockType;
if (changed)
{
// Assign the new block type.
BlockType oldBlockType = blockType;
blockType = newBlockType;
// Raise an event that the block type had changed. This is done
// before the plugins are called because they may make additional
// changes and we want to avoid recursion.
Project.Blocks.RaiseBlockTypeChanged(this, oldBlockType);
}
}
public void SetText(string newText)
{
// Verify that we have a write lock on this block.
if (!IsWriteLockHeld)
{
throw new InvalidOperationException(
"Cannot use SetText without having a write lock on the block.");
}
// TODO: This is disabled because inserting new lines doesn't properly cause events to be fired.
//// If nothing changed, then we don't have to do anything.
//if (newText == Text)
//{
// return;
//}
// Update the text and bump up the version of this block.
text = newText ?? string.Empty;
version++;
// Raise an event that we changed the text. We do this before processing
// the project plugins because the immediate editors may make additional
// changes that will also raise change events.
Project.Blocks.RaiseBlockTextChanged(this);
// Trigger the events for any listening plugins.
ClearAnalysis();
Project.Plugins.ProcessBlockAnalysis(this);
}
public override string ToString()
{
// Figure out a trimmed version of the text.
string trimmedText = text.Length > 20
? text.Substring(0, 17) + "..."
: text;
// Return a formatted version of the block.
return string.Format("{0} {1}: {2}", BlockKey, BlockType, trimmedText);
}
#endregion
#region Constructors
public Block(ProjectBlockCollection blocks)
: this(blocks, blocks.Project.BlockTypes.Paragraph, string.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Block" /> class.
/// </summary>
/// <param name="blocks">The ownerCollection.</param>
/// <param name="initialBlockType">Initial type of the block.</param>
/// <param name="text">The text.</param>
public Block(
ProjectBlockCollection blocks,
BlockType initialBlockType,
string text = "")
{
BlockKey = BlockKey.GetNext();
Blocks = blocks;
blockType = initialBlockType;
this.text = text;
Properties = new PropertiesDictionary();
TextSpans = new TextSpanCollection();
accessLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
previouslyAnalyzedPlugins = new HashSet<IBlockAnalyzerProjectPlugin>();
}
#endregion
#region Fields
private readonly ReaderWriterLockSlim accessLock;
private BlockType blockType;
/// <summary>
/// Contains the set of block analyzers that have previously processed
/// this block.
/// </summary>
private readonly HashSet<IBlockAnalyzerProjectPlugin>
previouslyAnalyzedPlugins;
private string text;
private volatile int version;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using AuthorIntrusion.Common;
using MfGames.HierarchicalPaths;
namespace AuthorIntrusion.Plugins.ImmediateBlockTypes
{
/// <summary>
/// The settings for the immediate block type settings. This controls which
/// text prefixes will alter the block types.
/// </summary>
[XmlRoot("immediate-block-types", Namespace = XmlConstants.ProjectNamespace)]
public class ImmediateBlockTypesSettings: IXmlSerializable
{
#region Properties
public IDictionary<string, string> Replacements { get; private set; }
public static HierarchicalPath SettingsPath { get; private set; }
#endregion
#region Methods
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
// We are already at the starting point of this element, so read until the
// end.
string elementName = reader.LocalName;
// Read until we get to the end element.
while (reader.Read())
{
// If we aren't in our namespace, we don't need to bother.
if (reader.NamespaceURI != XmlConstants.ProjectNamespace)
{
continue;
}
// If we got to the end of the node, then stop reading.
if (reader.LocalName == elementName)
{
return;
}
// Look for a key, if we have it, set that value.
if (reader.NodeType == XmlNodeType.Element
&& reader.LocalName == "replacement")
{
// Pull out the elements from the attribute string.
string prefix = reader["prefix"];
string blockTypeName = reader["block-type"];
// Insert the replacement into the dictionary.
Replacements[prefix] = blockTypeName;
}
}
}
public void WriteXml(XmlWriter writer)
{
// Write out a version field.
writer.WriteElementString("version", "1");
// Sort the list of words.
var prefixes = new List<string>();
prefixes.AddRange(Replacements.Keys);
prefixes.Sort();
// Write out the records.
foreach (string prefix in prefixes)
{
writer.WriteStartElement("replacement", XmlConstants.ProjectNamespace);
writer.WriteAttributeString("prefix", prefix);
writer.WriteAttributeString("block-type", Replacements[prefix]);
writer.WriteEndElement();
}
}
#endregion
#region Constructors
static ImmediateBlockTypesSettings()
{
SettingsPath = new HierarchicalPath("/Plugins/Immediate Block Types");
}
public ImmediateBlockTypesSettings()
{
Replacements = new Dictionary<string, string>();
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
namespace AuthorIntrusion.Common
{
/// <summary>
/// A marker interface to indicate that class should be used as a singleton
/// in the system.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class SingletonServiceAttribute: Attribute
{
}
}
<file_sep>// Copyright 2012-2013 Mo<NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Collections.Generic;
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
using AuthorIntrusion.Common.Plugins;
using MfGames.HierarchicalPaths;
namespace AuthorIntrusion.Plugins.Counter
{
/// <summary>
/// A controller to handle word counting.
/// </summary>
public class WordCounterProjectPlugin: IBlockTypeProjectPlugin
{
#region Properties
public string Key
{
get { return "Word Counter"; }
}
#endregion
#region Methods
/// <summary>
/// Analyzes the block and counts the word. Once counted, this updates
/// the block and all parent blocks with the altered change.
/// </summary>
/// <param name="block">The block.</param>
/// <param name="blockVersion">The block version of the initial request.</param>
public void AnalyzeBlock(
Block block,
int blockVersion)
{
// Grab counts from the current block text.
int newCount = 1;
int newWordCount;
int newCharacterCount;
int newNonWhitespaceCount;
string text = block.Text;
WordCounter.CountWords(
text, out newWordCount, out newCharacterCount, out newNonWhitespaceCount);
// Grab the existing counts from the current block, if we have one.
int oldCount;
int oldWordCount;
int oldCharacterCount;
int oldNonWhitespaceCount;
WordCounterPathUtility.GetCounts(
this,
block,
out oldCount,
out oldWordCount,
out oldCharacterCount,
out oldNonWhitespaceCount);
// Calculate the deltas between the values.
int delta = newCount - oldCount;
int wordDelta = newWordCount - oldWordCount;
int characterDelta = newCharacterCount - oldCharacterCount;
int nonWhitespaceDelta = newNonWhitespaceCount - oldNonWhitespaceCount;
// Build up a dictionary of changes so we can have a simple loop to
// set them in the various elements.
Dictionary<HierarchicalPath, int> deltas =
WordCounterPathUtility.GetDeltas(
this, block, delta, wordDelta, characterDelta, nonWhitespaceDelta);
// Get a write lock on the blocks list and update that block and all
// parent blocks in the document.
using (block.AcquireBlockLock(RequestLock.Write))
{
// Log that we are analyzing this block.
Log("BEGIN AnalyzeBlock: {0}: Words {1:N0}", block, newWordCount);
// First check to see if we've gotten stale.
if (block.IsStale(blockVersion))
{
return;
}
// Update the block and the document.
UpdateDeltas(block, deltas);
UpdateDeltas(block.Project, deltas);
// Log that we finished processing this block.
Log("END AnalyzeBlock: {0}: Words {1:N0}", block, newWordCount);
}
}
public void ChangeBlockType(
Block block,
BlockType oldBlockType)
{
// We need a write lock on the blocks while we make this change.
using (block.AcquireBlockLock(RequestLock.Write))
{
// Report what we're doing if we have logging on.
Log("ChangeBlockType: {0}: Old Type {1}", block, oldBlockType);
//// Figure out the deltas for this block.
//var deltas = new Dictionary<HierarchicalPath, int>();
//deltas[WordCounterPathUtility.GetPath(oldBlockType)] = -1;
//deltas[WordCounterPathUtility.GetPath(block.BlockType)] = 1;
//// Update the parent types.
//UpdateDeltas(block, deltas);
//UpdateDeltas(block.Project, deltas);
}
}
/// <summary>
/// Logs a message to the Logger property, if set.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="arguments">The arguments.</param>
private void Log(
string format,
params object[] arguments)
{
if (Logger != null)
{
Logger(format, arguments);
}
}
/// <summary>
/// Updates the properties inside the block with the given deltas.
/// </summary>
/// <param name="propertiesContainer">The block.</param>
/// <param name="deltas">The deltas.</param>
/// <param name="multiplier">The multiplier.</param>
private void UpdateDeltas(
IPropertiesContainer propertiesContainer,
IDictionary<HierarchicalPath, int> deltas,
int multiplier = 1)
{
foreach (HierarchicalPath path in deltas.Keys)
{
int delta = deltas[path] * multiplier;
Log(" Update Delta: {0}: {1} += {2}", propertiesContainer, path, delta);
propertiesContainer.Properties.AdditionOrAdd(path, delta);
}
}
#endregion
#region Fields
/// <summary>
/// If set, the given function will be called at key points in the
/// class.
/// </summary>
public static Action<string, object[]> Logger;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Blocks.Locking;
namespace AuthorIntrusion.Common.Plugins
{
public class BlockAnalyzer
{
#region Properties
public HashSet<IBlockAnalyzerProjectPlugin> Analysis { get; private set; }
public Block Block { get; private set; }
public IList<IBlockAnalyzerProjectPlugin> BlockAnalyzers { get; private set; }
public int BlockVersion { get; private set; }
#endregion
#region Methods
public void Run()
{
// Figure out which analyzers we need to actually run on the block.
var neededAnalyzers = new List<IBlockAnalyzerProjectPlugin>();
foreach (IBlockAnalyzerProjectPlugin blockAnalyzer in BlockAnalyzers)
{
if (!Analysis.Contains(blockAnalyzer))
{
neededAnalyzers.Add(blockAnalyzer);
}
}
// Loop through all the analyzers in the list and perform each one in turn.
ProjectBlockCollection blocks = Block.Project.Blocks;
foreach (IBlockAnalyzerProjectPlugin blockAnalyzer in neededAnalyzers)
{
// Check to see if the block had gone stale.
using (blocks.AcquireBlockLock(RequestLock.Read, Block))
{
if (Block.IsStale(BlockVersion))
{
// The block is stale, so we just dump out since there will be
// another task to reanalyze this block.
return;
}
}
// Perform the analysis on the given block.
blockAnalyzer.AnalyzeBlock(Block, BlockVersion);
// Once we're done analyzing the block, we need to add this
// analyzer to the list so we don't attempt to run it again.
Block.AddAnalysis(blockAnalyzer);
}
}
public override string ToString()
{
return string.Format(
"BlockAnalyzer (BlockKey {0}, Version {1})",
Block.BlockKey.Id.ToString("X8"),
BlockVersion);
}
#endregion
#region Constructors
public BlockAnalyzer(
Block block,
int blockVersion,
IList<IBlockAnalyzerProjectPlugin> blockAnalyzers,
HashSet<IBlockAnalyzerProjectPlugin> analysis)
{
Block = block;
BlockVersion = blockVersion;
BlockAnalyzers = blockAnalyzers;
Analysis = analysis;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Threading;
using AuthorIntrusion.Common.Blocks.Locking;
using AuthorIntrusion.Common.Events;
using MfGames.Locking;
namespace AuthorIntrusion.Common.Blocks
{
/// <summary>
/// A block collection that manages ownership of blocks along with processing
/// of both collection operations (insert, delete) and block operations (insert
/// text).
/// </summary>
public class ProjectBlockCollection: BlockCollection
{
#region Properties
/// <summary>
/// Gets the project associated with this collection.
/// </summary>
public Project Project { get; private set; }
#endregion
#region Events
public event EventHandler<BlockEventArgs> BlockTextChanged;
public event EventHandler<BlockEventArgs> BlockTypeChanged;
public event EventHandler<BlockEventArgs> TextSpansChanged;
#endregion
#region Methods
/// <summary>
/// Acquires a lock on the collection, of the requested type, and also a lock
/// on the block referenced by the index.
/// </summary>
/// <param name="blockIndex">The index of the block to lock.</param>
/// <param name="block">The block retrieved by the index.</param>
/// <param name="requestedBlockLock"></param>
/// <returns>An opaque lock object that will release the lock on disposal.</returns>
public IDisposable AcquireBlockLock(
RequestLock requestedBlockLock,
int blockIndex,
out Block block)
{
return AcquireBlockLock(
RequestLock.Read, requestedBlockLock, blockIndex, out block);
}
/// <summary>
/// Acquires a lock on the collection, of the requested type, and also a lock
/// on the block referenced by the index.
/// </summary>
/// <param name="requestedCollectionLock"></param>
/// <param name="blockIndex">The index of the block to lock.</param>
/// <param name="block">The block retrieved by the index.</param>
/// <param name="requestedBlockLock"></param>
/// <returns>An opaque lock object that will release the lock on disposal.</returns>
public IDisposable AcquireBlockLock(
RequestLock requestedCollectionLock,
RequestLock requestedBlockLock,
int blockIndex,
out Block block)
{
// Start by getting a read lock on the collection itself.
IDisposable collectionLock = AcquireLock(requestedCollectionLock);
// Grab the block via the index.
block = this[blockIndex];
// Get a read lock on the block and then return it.
IDisposable blockLock = block.AcquireLock(collectionLock, requestedBlockLock);
return blockLock;
}
public IDisposable AcquireBlockLock(
RequestLock requestedBlockLock,
BlockKey blockKey,
out Block block)
{
return AcquireBlockLock(
RequestLock.Read, requestedBlockLock, blockKey, out block);
}
public IDisposable AcquireBlockLock(
RequestLock requestedCollectionLock,
RequestLock requestedBlockLock,
BlockKey blockKey,
out Block block)
{
// Start by getting a read lock on the collection itself.
IDisposable collectionLock = AcquireLock(requestedCollectionLock);
// Grab the block via the index.
block = this[blockKey];
// Get a read lock on the block and then return it.
IDisposable blockLock = block.AcquireLock(collectionLock, requestedBlockLock);
return blockLock;
}
public IDisposable AcquireBlockLock(
RequestLock requestedBlockLock,
Block block)
{
return AcquireBlockLock(RequestLock.Read, requestedBlockLock, block);
}
public IDisposable AcquireBlockLock(
RequestLock requestedCollectionLock,
RequestLock requestedBlockLock,
Block block)
{
// Start by getting a read lock on the collection itself.
IDisposable collectionLock = AcquireLock(requestedCollectionLock);
// Get a read lock on the block and then return it.
IDisposable blockLock = block.AcquireLock(collectionLock, requestedBlockLock);
return blockLock;
}
/// <summary>
/// Acquires a lock of the specified type and returns an opaque lock object
/// that will release the lock when disposed.
///
/// <code>using (blocks.AcquireLock(RequestLock.Read)) {}</code>
/// </summary>
/// <returns>An opaque lock object that will release lock on disposal.</returns>
public IDisposable AcquireLock(RequestLock requestLock)
{
// Acquire the lock based on the requested type.
IDisposable acquiredLock;
switch (requestLock)
{
case RequestLock.Read:
acquiredLock = new NestableReadLock(accessLock);
break;
case RequestLock.UpgradableRead:
acquiredLock = new NestableUpgradableReadLock(accessLock);
break;
case RequestLock.Write:
acquiredLock = new NestableWriteLock(accessLock);
break;
default:
throw new InvalidOperationException(
"Could not acquire lock with unknown type: " + requestLock);
}
// Return the resulting lock.
return acquiredLock;
}
/// <summary>
/// Raises an event that a block's text had changed.
/// </summary>
/// <param name="block"></param>
public void RaiseBlockTextChanged(Block block)
{
EventHandler<BlockEventArgs> listeners = BlockTextChanged;
if (listeners != null)
{
var args = new BlockEventArgs(block);
listeners(this, args);
}
}
/// <summary>
/// Raises an event that a block's type had changed.
/// </summary>
/// <param name="block"></param>
/// <param name="oldBlockType"></param>
public void RaiseBlockTypeChanged(
Block block,
BlockType oldBlockType)
{
EventHandler<BlockEventArgs> listeners = BlockTypeChanged;
if (listeners != null)
{
var args = new BlockEventArgs(block);
listeners(this, args);
}
}
/// <summary>
/// Raises an event that a block's text spans had changed.
/// </summary>
/// <param name="block"></param>
public void RaiseTextSpansChanged(Block block)
{
EventHandler<BlockEventArgs> listeners = TextSpansChanged;
if (listeners != null)
{
var args = new BlockEventArgs(block);
listeners(this, args);
}
}
/// <summary>
/// Ensures the minimum blocks inside the collection.
/// </summary>
private void EnsureMinimumBlocks()
{
if (Count == 0)
{
var initialBlock = new Block(this);
Add(initialBlock);
}
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ProjectBlockCollection"/> class.
/// </summary>
/// <param name="project">The project.</param>
public ProjectBlockCollection(Project project)
{
// Assign the project so we have an association with the block.
Project = project;
// Set up the internal state.
accessLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
// Create the initial block item.
EnsureMinimumBlocks();
}
#endregion
#region Fields
private readonly ReaderWriterLockSlim accessLock;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
using MfGames.Commands;
using MfGames.Commands.TextEditing;
namespace AuthorIntrusion.Common.Commands
{
/// <summary>
/// A common baes for commands that function on a single block.
/// </summary>
public abstract class BlockKeyCommand: IBlockCommand
{
#region Properties
/// <summary>
/// Gets the key that identifies the block this command operates on.
/// </summary>
public BlockKey BlockKey { get; protected set; }
public virtual bool CanUndo
{
get { return true; }
}
public virtual bool IsTransient
{
get { return false; }
}
public LinePosition Line { get; private set; }
public DoTypes UpdateTextPosition { get; set; }
public DoTypes UpdateTextSelection { get; set; }
protected bool UseBlockKey { get; private set; }
#endregion
#region Methods
/// <summary>
/// Acquires the locks needed for a specific operation and then performs
/// UnlockedDo().
/// </summary>
public abstract void Do(BlockCommandContext context);
public void Redo(BlockCommandContext context)
{
Do(context);
}
public abstract void Undo(BlockCommandContext context);
/// <summary>
/// Performs the command on the given block.
/// </summary>
/// <param name="context"></param>
/// <param name="block">The block to perform the action on.</param>
protected abstract void Do(
BlockCommandContext context,
Block block);
protected abstract void Undo(
BlockCommandContext context,
Block block);
#endregion
#region Constructors
protected BlockKeyCommand(BlockKey blockKey)
{
BlockKey = blockKey;
UseBlockKey = true;
UpdateTextPosition = DoTypes.All;
}
protected BlockKeyCommand(LinePosition line)
{
Line = line;
UseBlockKey = false;
UpdateTextPosition = DoTypes.All;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
namespace AuthorIntrusion.Common.Blocks
{
/// <summary>
/// A supervisor class that manages block types for a given project.
/// </summary>
public class BlockTypeSupervisor
{
#region Properties
/// <summary>
/// Gets the <see cref="BlockType"/> with the specified block type name.
/// </summary>
/// <value>
/// The <see cref="BlockType"/>.
/// </value>
/// <param name="blockTypeName">Name of the block type.</param>
/// <returns>The associated block type.</returns>
public BlockType this[string blockTypeName]
{
get { return BlockTypes[blockTypeName]; }
}
/// <summary>
/// Gets the block types associated with this Supervisor.
/// </summary>
public IDictionary<string, BlockType> BlockTypes { get; private set; }
public BlockType Chapter
{
get { return this[ChapterName]; }
}
/// <summary>
/// Gets the standard block type associated with epigraphs.
/// </summary>
public BlockType Epigraph
{
get { return this[EpigraphName]; }
}
/// <summary>
/// Gets the standard block type for attributions.
/// </summary>
public BlockType EpigraphAttribution
{
get { return this[EpigraphAttributionName]; }
}
public BlockType Paragraph
{
get { return this[ParagraphName]; }
}
/// <summary>
/// Gets or sets the project associated with this block type Supervisor.
/// </summary>
public Project Project { get; private set; }
public BlockType Scene
{
get { return this[SceneName]; }
}
#endregion
#region Methods
/// <summary>
/// Adds the specified block type to the collection.
/// </summary>
/// <param name="blockTypeName">Name of the block type.</param>
/// <param name="isStructural">if set to <c>true</c> [is structural].</param>
/// <param name="isSystem">if set to <c>true</c> [is system].</param>
public void Add(
string blockTypeName,
bool isStructural,
bool isSystem = false)
{
var blockType = new BlockType(this)
{
Name = blockTypeName,
IsStructural = isStructural,
IsSystem = isSystem
};
BlockTypes.Add(blockTypeName, blockType);
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="BlockTypeSupervisor"/> class.
/// </summary>
/// <param name="project">The project.</param>
public BlockTypeSupervisor(Project project)
{
// Save the project so we can associated the Supervisor with its project.
Project = project;
// Create the standard project block types.
var paragraph = new BlockType(this)
{
Name = ParagraphName,
IsSystem = true,
IsStructural = false,
};
var story = new BlockType(this)
{
Name = StoryName,
IsSystem = true,
IsStructural = true,
};
var book = new BlockType(this)
{
Name = BookName,
IsSystem = true,
IsStructural = true,
};
var chapter = new BlockType(this)
{
Name = ChapterName,
IsSystem = true,
IsStructural = true,
};
var scene = new BlockType(this)
{
Name = SceneName,
IsSystem = true,
IsStructural = true,
};
var epigraph = new BlockType(this)
{
Name = EpigraphName,
IsSystem = true,
IsStructural = true,
};
var attribution = new BlockType(this)
{
Name = EpigraphAttributionName,
IsSystem = true,
IsStructural = true,
};
// Initialize the collection of block types.
BlockTypes = new Dictionary<string, BlockType>();
BlockTypes[ParagraphName] = paragraph;
BlockTypes[StoryName] = story;
BlockTypes[BookName] = book;
BlockTypes[ChapterName] = chapter;
BlockTypes[SceneName] = scene;
BlockTypes[EpigraphName] = epigraph;
BlockTypes[EpigraphAttributionName] = attribution;
}
#endregion
#region Fields
public const string BookName = "Book";
public const string ChapterName = "Chapter";
public const string EpigraphAttributionName = "Epigraph Attribution";
public const string EpigraphName = "Epigraph";
public const string ParagraphName = "Paragraph";
public const string SceneName = "Scene";
public const string StoryName = "Story";
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace AuthorIntrusion.Common.Blocks
{
/// <summary>
/// Defines a structural element for the organization of blocks. A block structure
/// defines the dynamic structure for grouping blocks together to form chapters,
/// scenes, and other elements that make up the common components of a novel or
/// story. Each structure is keyed off a specific block type.
/// </summary>
public class BlockStructure
{
#region Properties
/// <summary>
/// Gets or sets the block type that this structure represents.
/// </summary>
public BlockType BlockType { get; set; }
/// <summary>
/// Gets the nested structures underneath this block. This structure is
/// ignored if the BlockType.IsStructural is false.
/// </summary>
public IList<BlockStructure> ChildStructures
{
get { return new ReadOnlyCollection<BlockStructure>(childStructures); }
}
/// <summary>
/// Gets or sets the maximum occurances for this block structure.
/// </summary>
public int MaximumOccurances { get; set; }
/// <summary>
/// Gets or sets the minimum occurances for this structure.
/// </summary>
public int MinimumOccurances { get; set; }
public BlockStructure ParentStructure { get; set; }
#endregion
#region Methods
/// <summary>
/// Adds a child block structure to the structure's children.
/// </summary>
/// <param name="blockStructure"></param>
public void AddChild(BlockStructure blockStructure)
{
blockStructure.ParentStructure = this;
childStructures.Add(blockStructure);
}
/// <summary>
/// Determines whether this instance contains a child structure of the given block type.
/// </summary>
/// <param name="blockType">Type of the block.</param>
/// <returns>
/// <c>true</c> if [contains child structure] [the specified block type]; otherwise, <c>false</c>.
/// </returns>
public bool ContainsChildStructure(BlockType blockType)
{
return
ChildStructures.Any(childStructure => childStructure.BlockType == blockType);
}
/// <summary>
/// Gets the child structure associated with a given block type.
/// </summary>
/// <param name="blockType">Type of the block.</param>
/// <returns>A child structure of the given type.</returns>
/// <exception cref="System.IndexOutOfRangeException">Cannot find child block type: + blockType</exception>
public BlockStructure GetChildStructure(BlockType blockType)
{
foreach (BlockStructure childStructure in
ChildStructures.Where(
childStructure => childStructure.BlockType == blockType))
{
return childStructure;
}
throw new IndexOutOfRangeException(
"Cannot find child block type: " + blockType);
}
#endregion
#region Constructors
public BlockStructure()
{
// Set up the default values for a block structure.
MinimumOccurances = 1;
MaximumOccurances = Int32.MaxValue;
// Set up the inner collections.
childStructures = new List<BlockStructure>();
}
#endregion
#region Fields
private readonly IList<BlockStructure> childStructures;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using AuthorIntrusion.Common;
using MfGames.HierarchicalPaths;
namespace AuthorIntrusion.Plugins.Spelling.LocalWords
{
/// <summary>
/// Contains the serialiable settings for the Local Words plugin.
/// </summary>
[XmlRoot("local-words-settings", Namespace = XmlConstants.ProjectNamespace)]
public class LocalWordsSettings: IXmlSerializable
{
#region Properties
public HashSet<string> CaseInsensitiveDictionary { get; private set; }
public HashSet<string> CaseSensitiveDictionary { get; private set; }
#endregion
#region Methods
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
// We are already at the starting point of this element, so read until the
// end.
string elementName = reader.LocalName;
// Read until we get to the end element.
while (reader.Read())
{
// If we aren't in our namespace, we don't need to bother.
if (reader.NamespaceURI != XmlConstants.ProjectNamespace)
{
continue;
}
// If we got to the end of the node, then stop reading.
if (reader.LocalName == elementName)
{
return;
}
// Look for a key, if we have it, set that value.
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "sensitive":
string sensitive = reader.ReadString();
CaseSensitiveDictionary.Add(sensitive);
break;
case "insensitive":
string insensitive = reader.ReadString();
CaseInsensitiveDictionary.Add(insensitive);
break;
}
}
}
}
public void WriteXml(XmlWriter writer)
{
// Write out a version field.
writer.WriteElementString("version", "1");
// Sort the list of words.
var sortedInsensitiveWords = new List<string>();
sortedInsensitiveWords.AddRange(CaseInsensitiveDictionary);
sortedInsensitiveWords.Sort();
var sortedSensitiveWords = new List<string>();
sortedSensitiveWords.AddRange(CaseSensitiveDictionary);
sortedSensitiveWords.Sort();
// Write out the records.
foreach (string word in sortedInsensitiveWords)
{
writer.WriteElementString("insensitive", word);
}
foreach (string word in sortedSensitiveWords)
{
writer.WriteElementString("sensitive", word);
}
}
#endregion
#region Constructors
static LocalWordsSettings()
{
SettingsPath = new HierarchicalPath("/Plugins/Spelling/Local Words");
}
public LocalWordsSettings()
{
CaseInsensitiveDictionary = new HashSet<string>();
CaseSensitiveDictionary = new HashSet<string>();
}
#endregion
#region Fields
public static readonly HierarchicalPath SettingsPath;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
namespace AuthorIntrusion.Common.Events
{
/// <summary>
/// An event argument associated with a project.
/// </summary>
public class ProjectEventArgs: EventArgs
{
#region Properties
public Project Project { get; private set; }
#endregion
#region Constructors
public ProjectEventArgs(Project project)
{
Project = project;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Commands;
using MfGames.Commands;
using MfGames.GtkExt.TextEditor.Models;
namespace AuthorIntrusion.Gui.GtkGui.Commands
{
public class ProjectCommandWrapper: IWrappedCommand
{
#region Properties
public ProjectCommandAdapter Adapter { get; private set; }
public bool CanUndo
{
get { return command.CanUndo; }
}
public bool IsTransient
{
get { return command.IsTransient; }
}
#endregion
#region Methods
public void Do(BlockCommandContext context)
{
command.Do(context);
}
public void PostDo(OperationContext context)
{
Adapter.PostDo(context);
}
public void PostUndo(OperationContext context)
{
Adapter.PostUndo(context);
}
public void Redo(BlockCommandContext context)
{
command.Redo(context);
}
public void Undo(BlockCommandContext context)
{
command.Undo(context);
}
#endregion
#region Constructors
public ProjectCommandWrapper(
ProjectCommandAdapter adapter,
IUndoableCommand<BlockCommandContext> command)
{
Adapter = adapter;
this.command = command;
}
#endregion
#region Fields
private readonly IUndoableCommand<BlockCommandContext> command;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
using AuthorIntrusion.Common.Commands;
namespace AuthorIntrusion.Common.Plugins
{
/// <summary>
/// Indicates a project plugin controller that performs immediate changes to the
/// text while the user is editing.
/// </summary>
public interface IImmediateEditorProjectPlugin: IProjectPlugin
{
#region Methods
/// <summary>
/// Checks for immediate edits after the user makes a change to the block.
/// </summary>
/// <param name="context"></param>
/// <param name="block">The block.</param>
/// <param name="textIndex">Index of the text.</param>
void ProcessImmediateEdits(
BlockCommandContext context,
Block block,
int textIndex);
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
namespace AuthorIntrusion.Plugins.ImmediateCorrection
{
/// <summary>
/// A substitution that was registered with the system in one or more
/// configurations.
/// </summary>
public class RegisteredSubstitution: IComparable<RegisteredSubstitution>
{
#region Properties
public bool IsWholeWord
{
get { return (Options & SubstitutionOptions.WholeWord) != 0; }
}
#endregion
#region Methods
public int CompareTo(RegisteredSubstitution other)
{
int compare = String.Compare(Search, other.Search, StringComparison.Ordinal);
return compare;
}
#endregion
#region Constructors
public RegisteredSubstitution(
string search,
string replacement,
SubstitutionOptions options)
{
// Save the fields for the substitution.
Search = search;
Replacement = replacement;
Options = options;
}
#endregion
#region Fields
public readonly SubstitutionOptions Options;
public readonly string Replacement;
public readonly string Search;
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Diagnostics;
using AuthorIntrusion.Common.Plugins;
using StructureMap;
namespace AuthorIntrusion
{
/// <summary>
/// The resolver is an abstracted layer around an Inversion of Control/Dependency
/// Injection API. This is not a static singleton class since it is intended to be
/// used in a single entry application and then referenced again throughout the
/// system.
/// </summary>
public class EnvironmentResolver
{
#region Methods
/// <summary>
/// Gets a specific type of the given instance and returns it.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <returns>The TResult item.</returns>
public TResult Get<TResult>()
{
var result = ObjectFactory.GetInstance<TResult>();
return result;
}
/// <summary>
/// Loads and initializes the plugin manager with all the plugins that can
/// be found in the current environment.
/// </summary>
public void LoadPluginManager()
{
PluginManager.Instance = ObjectFactory.GetInstance<PluginManager>();
}
/// <summary>
/// Initializes StructureMap to scan the assemblies and setup all the
/// needed elements.
/// </summary>
/// <param name="init"></param>
private static void InitializeStructureMap(IInitializationExpression init)
{
init.Scan(
s =>
{
// Determine which assemblies contain types we need.
s.AssembliesFromApplicationBaseDirectory(
a => a.FullName.Contains("AuthorIntrusion"));
// List all the assemblies we need. Since most of the
// plugins are required to register IPlugin, we can just
// add those types.
s.AddAllTypesOf<IPlugin>();
});
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="EnvironmentResolver"/> class.
/// </summary>
public EnvironmentResolver()
{
// Set up StructureMap and loading all the plugins from the
// main directory.
ObjectFactory.Initialize(InitializeStructureMap);
string results = ObjectFactory.WhatDoIHave();
Debug.WriteLine(results);
ObjectFactory.AssertConfigurationIsValid();
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using MfGames.Commands;
namespace AuthorIntrusion.Common.Commands
{
/// <summary>
/// Defines the signature for an operation that changes the internal block
/// structure for the project. Examples of these commands would be inserting or
/// deleting text, changing block types, or the individual results of auto-correct.
/// </summary>
public interface IBlockCommand: IUndoableCommand<BlockCommandContext>
{
#region Properties
/// <summary>
/// Gets where the position should be updated when the command executes.
/// </summary>
DoTypes UpdateTextPosition { get; set; }
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Plugins;
namespace AuthorIntrusion.Plugins.ImmediateBlockTypes
{
/// <summary>
/// The plugin for an immediate editor that changes the block type as the author
/// is writing.
/// </summary>
public class ImmediateBlockTypesPlugin: IProjectPluginProviderPlugin
{
#region Properties
public bool AllowMultiple
{
get { return false; }
}
public string Key
{
get { return "Immediate Block Types"; }
}
#endregion
#region Methods
public IProjectPlugin GetProjectPlugin(Project project)
{
return new ImmediateBlockTypesProjectPlugin(project);
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using AuthorIntrusion.Common.Persistence.Filesystem;
using AuthorIntrusion.Common.Plugins;
using AuthorIntrusion.Common.Projects;
namespace AuthorIntrusion.Common.Persistence
{
/// <summary>
/// Defines a persistence plugin for handling reading and writing to the filesystem.
/// </summary>
public class FilesystemPersistencePlugin: IPersistencePlugin
{
#region Properties
public bool AllowMultiple
{
get { return true; }
}
public string Key
{
get { return "Filesystem Persistence"; }
}
#endregion
#region Methods
public bool CanRead(FileInfo projectFile)
{
bool results = projectFile.Extension == ".aiproj";
return results;
}
public IProjectPlugin GetProjectPlugin(Project project)
{
var projectPlugin = new FilesystemPersistenceProjectPlugin(project);
return projectPlugin;
}
public Project ReadProject(FileInfo projectFile)
{
// Open up an XML reader to pull out the critical components we
// need to finish loading the file.
FilesystemPersistenceSettings settings = null;
using (FileStream stream = projectFile.Open(FileMode.Open, FileAccess.Read))
{
using (XmlReader reader = XmlReader.Create(stream))
{
// Read until we get the file-persistent-settings file.
while (reader.Read())
{
// Ignore everything but the settings object we need to read.
if (reader.NamespaceURI != XmlConstants.ProjectNamespace
|| reader.NodeType != XmlNodeType.Element
|| reader.LocalName != FilesystemPersistenceSettings.XmlElementName)
{
continue;
}
// Load the settings object into memory.
var serializer = new XmlSerializer(typeof (FilesystemPersistenceSettings));
settings = (FilesystemPersistenceSettings) serializer.Deserialize(reader);
}
}
}
// If we finish reading the file without getting the settings, blow up.
if (settings == null)
{
throw new FileLoadException("Cannot load project: " + projectFile);
}
// Populate the macros we'll be using.
var macros = new ProjectMacros();
macros.Substitutions["ProjectDirectory"] = projectFile.Directory.FullName;
macros.Substitutions["ProjectFile"] = projectFile.FullName;
macros.Substitutions["DataDirectory"] = settings.DataDirectory;
macros.Substitutions["InternalContentDirectory"] =
settings.InternalContentDirectory;
macros.Substitutions["ExternalSettingsDirectory"] =
settings.ExternalSettingsDirectory;
// Load the project starting with the project. We create the project
// in batch mode to avoid excessive processing.
var project = new Project(ProjectProcessingState.Batch);
var projectReaderWriter = new FilesystemPersistenceProjectReader(
project, settings, macros);
projectReaderWriter.Read(projectFile);
// Since we created the project in batch mode, we need to change it
// back to interactive mode.
project.SetProcessingState(ProjectProcessingState.Interactive);
// Trigger any missing block analysis.
project.Plugins.ProcessBlockAnalysis();
// Return the resulting project.
return project;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using AuthorIntrusion.Common.Blocks;
namespace AuthorIntrusion.Common.Plugins
{
/// <summary>
/// Defines a controller process that analyzes a block in a background thread.
/// </summary>
public interface IBlockAnalyzerProjectPlugin: IProjectPlugin
{
#region Methods
/// <summary>
/// Analyzes the block and makes changes as needed.
/// </summary>
/// <param name="block">The block to analyze.</param>
/// <param name="blockVersion">The block version of the initial request.</param>
void AnalyzeBlock(
Block block,
int blockVersion);
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using AuthorIntrusion.Common.Blocks;
namespace AuthorIntrusion.Common.Events
{
public class BlockEventArgs: EventArgs
{
#region Properties
public Block Block { get; private set; }
public ProjectBlockCollection Blocks
{
get { return Block.Blocks; }
}
public Project Project
{
get { return Block.Project; }
}
#endregion
#region Constructors
public BlockEventArgs(Block block)
{
Block = block;
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 <NAME>
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.IO;
using Gtk;
namespace AuthorIntrusion.Gui.GtkGui
{
/// <summary>
/// Sets up the Gtk framework and starts up the application.
/// </summary>
internal static class GtkProgram
{
#region Methods
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static void Main(string[] args)
{
// Initial the Gtk GUI framework.
Application.Init("Author Intrusion", ref args);
// We use the Inversion of Control (IoC) container to resolve all the
// elements of the window. This lets everything wire up together without
// having a lot of maintenance or singletons.
var resolver = new EnvironmentResolver();
// Set up the environment.
resolver.LoadPluginManager();
// Create the main window, show its contents, and start the Gtk loop.
try
{
var projectManager = new ProjectManager();
var mainWindow = new MainWindow(projectManager);
mainWindow.ShowAll();
// If we have some arguments, try to load the file as project.
if (args.Length > 0)
{
var projectFile = new FileInfo(args[0]);
mainWindow.OpenProject(projectFile);
}
// Start running the application.
Application.Run();
}
catch (Exception exception)
{
Console.WriteLine("There was an exception");
Exception e = exception;
while (e != null)
{
Console.WriteLine("=== EXCEPTION");
Console.WriteLine(e);
e = e.InnerException;
}
throw;
}
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System;
using System.Collections.Generic;
using System.Linq;
namespace AuthorIntrusion.Common.Plugins
{
/// <summary>
/// Gathers and coordinates the various plugins used in the system. This includes
/// both project- and system-specific plugins.
/// </summary>
public class PluginManager
{
#region Properties
/// <summary>
/// Gets or sets the static singleton instance.
/// </summary>
public static PluginManager Instance { get; set; }
/// <summary>
/// Gets an unsorted list of block analyzers available in the system.
/// </summary>
public IPlugin[] Plugins { get; private set; }
#endregion
#region Methods
/// <summary>
/// Gets the plugin with the specified name.
/// </summary>
/// <param name="pluginName">Name of the plugin.</param>
/// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">Cannot find plugin: + pluginName</exception>
public IPlugin Get(string pluginName)
{
IEnumerable<IPlugin> namedPlugins = Plugins.Where(p => p.Key == pluginName);
foreach (IPlugin plugin in namedPlugins)
{
return plugin;
}
throw new IndexOutOfRangeException("Cannot find plugin: " + pluginName);
}
/// <summary>
/// Tries to get the given project plugin via the name.
/// </summary>
/// <param name="pluginName">Name of the plugin.</param>
/// <param name="plugin">The plugin, if found.</param>
/// <returns><c>true<c> if the plugin is found, otherwise </c>false</c>.</returns>
public bool TryGetProjectPlugin(
string pluginName,
out IProjectPluginProviderPlugin plugin)
{
// Go through all the project plugins and make sure they are both a
// project plugin and they match the name.
foreach (IPlugin projectPlugin in Plugins)
{
if (projectPlugin.Key == pluginName
&& projectPlugin is IProjectPluginProviderPlugin)
{
plugin = (IProjectPluginProviderPlugin) projectPlugin;
return true;
}
}
// We couldn't find it, so put in the default and return a false.
plugin = null;
return false;
}
#endregion
#region Constructors
public PluginManager(params IPlugin[] plugins)
{
// Save all the block analzyers into a private array.
Plugins = plugins;
// Once we have the plugins sorted, we need to allow the framework
// plugins to hook themselves up to the other plugins.
foreach (IPlugin plugin in plugins)
{
// See if this is a framework plugin (e.g., one that coordinates with
// other plugins).
var frameworkPlugin = plugin as IFrameworkPlugin;
if (frameworkPlugin == null)
{
continue;
}
// Build a list of plugins that doesn't include the framework plugin.
var relatedPlugins = new List<IPlugin>();
relatedPlugins.AddRange(plugins);
relatedPlugins.Remove(plugin);
// Register the plugins with the calling class.
frameworkPlugin.RegisterPlugins(relatedPlugins);
}
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using AuthorIntrusion.Common;
using AuthorIntrusion.Common.Actions;
using AuthorIntrusion.Common.Commands;
using AuthorIntrusion.Common.Plugins;
using AuthorIntrusion.Plugins.Spelling.Common;
using MfGames.Enumerations;
using MfGames.HierarchicalPaths;
namespace AuthorIntrusion.Plugins.Spelling.LocalWords
{
/// <summary>
/// Defines a "local words" dictionary plugin. This functions like Emacs'
/// LocalWords lines in a file in that it identifies correct spelling of files.
/// It has both a case sensitive and case insensitive version (the latter being
/// the same as all lowercase terms in Emacs).
/// </summary>
public class LocalWordsProjectPlugin: IProjectPlugin,
ISpellingProjectPlugin
{
#region Properties
public IBlockAnalyzerProjectPlugin BlockAnalyzer { get; set; }
public HashSet<string> CaseInsensitiveDictionary { get; private set; }
public HashSet<string> CaseSensitiveDictionary { get; private set; }
public string Key
{
get { return "Local Words"; }
}
public Importance Weight { get; set; }
private Project Project { get; set; }
#endregion
#region Methods
public IEnumerable<IEditorAction> GetAdditionalEditorActions(string word)
{
// We have two additional editor actions.
var addSensitiveAction = new EditorAction(
"Add case-sensitive local words",
new HierarchicalPath("/Plugins/Local Words/Add to Sensitive"),
context => AddToSensitiveList(context, word));
var addInsensitiveAction =
new EditorAction(
"Add case-insensitive local words",
new HierarchicalPath("/Plugins/Local Words/Add to Insensitive"),
context => AddToInsensitiveList(context, word));
// Return the resutling list.
var results = new IEditorAction[]
{
addSensitiveAction, addInsensitiveAction
};
return results;
}
public IEnumerable<SpellingSuggestion> GetSuggestions(string word)
{
// The local words controller doesn't provide suggestions at all.
return new SpellingSuggestion[]
{
};
}
public WordCorrectness IsCorrect(string word)
{
// First check the case-sensitive dictionary.
bool isCaseSensitiveCorrect = CaseSensitiveDictionary.Contains(word);
if (isCaseSensitiveCorrect)
{
return WordCorrectness.Correct;
}
// Check the case-insensitive version by making it lowercase and trying
// again.
word = word.ToLowerInvariant();
bool isCaseInsensitiveCorrect = CaseInsensitiveDictionary.Contains(word);
// The return value is either correct or indeterminate since this
// plugin is intended to be a supplemental spell-checking instead of
// a conclusive one.
return isCaseInsensitiveCorrect
? WordCorrectness.Correct
: WordCorrectness.Indeterminate;
}
/// <summary>
/// Retrieves the setting substitutions and rebuilds the internal list.
/// </summary>
public void ReadSettings()
{
// Clear out the existing settings.
CaseInsensitiveDictionary.Clear();
CaseSensitiveDictionary.Clear();
// Go through all of the settings in the various projects.
IList<LocalWordsSettings> settingsList =
Project.Settings.GetAll<LocalWordsSettings>(LocalWordsSettings.SettingsPath);
foreach (LocalWordsSettings settings in settingsList)
{
// Add the two dictionaries.
foreach (string word in settings.CaseInsensitiveDictionary)
{
CaseInsensitiveDictionary.Add(word);
}
foreach (string word in settings.CaseSensitiveDictionary)
{
CaseSensitiveDictionary.Add(word);
}
}
}
/// <summary>
/// Write out the settings to the settings.
/// </summary>
public void WriteSettings()
{
// Get the settings and clear out the lists.
var settings =
Project.Settings.Get<LocalWordsSettings>(LocalWordsSettings.SettingsPath);
settings.CaseInsensitiveDictionary.Clear();
settings.CaseSensitiveDictionary.Clear();
// Add in the words from the settings.
foreach (string word in CaseInsensitiveDictionary)
{
settings.CaseInsensitiveDictionary.Add(word);
}
foreach (string word in CaseSensitiveDictionary)
{
settings.CaseSensitiveDictionary.Add(word);
}
}
private void AddToInsensitiveList(
BlockCommandContext context,
string word)
{
// Update the internal dictionaries.
CaseInsensitiveDictionary.Add(word.ToLowerInvariant());
// Clear the spell-checking on the entire document and reparse it.
Project.Plugins.ClearAnalysis(BlockAnalyzer);
Project.Plugins.ProcessBlockAnalysis();
// Make sure the settings are written out.
WriteSettings();
}
private void AddToSensitiveList(
BlockCommandContext context,
string word)
{
// Update the internal dictionaries by removing it from the
// insensitive list and adding it to the sensitive list.
CaseInsensitiveDictionary.Remove(word.ToLowerInvariant());
CaseSensitiveDictionary.Add(word);
// Clear the spell-checking on the entire document and reparse it.
Project.Plugins.ClearAnalysis(BlockAnalyzer);
Project.Plugins.ProcessBlockAnalysis();
// Make sure the settings are written out.
WriteSettings();
}
#endregion
#region Constructors
public LocalWordsProjectPlugin(Project project)
{
// Save the variables so we can access them later.
Project = project;
// Create the collections we'll use.
CaseInsensitiveDictionary = new HashSet<string>();
CaseSensitiveDictionary = new HashSet<string>();
// Load in the initial settings.
ReadSettings();
}
#endregion
}
}
<file_sep>// Copyright 2012-2013 Moonfire Games
// Released under the MIT license
// http://mfgames.com/author-intrusion/license
using System.Collections.Generic;
using AuthorIntrusion.Common.Blocks;
namespace AuthorIntrusion.Plugins.Spelling
{
/// <summary>
/// Specialized splitter class that normalizes input and breaks each word apart
/// in a format usable by the spelling framework.
/// </summary>
public class SpellingWordSplitter
{
#region Methods
/// <summary>
/// Splits and normalizes the string for processing spell-checking.
/// </summary>
/// <param name="line">The line.</param>
/// <returns>A list of normalized words.</returns>
public IList<TextSpan> SplitAndNormalize(string line)
{
// Because we need to keep track of the start and stop text indexes,
// we loop through the string once and keep track of the last text span
// we are populating.
var textSpans = new List<TextSpan>();
TextSpan textSpan = null;
for (int index = 0;
index < line.Length;
index++)
{
// Grab the character for this line.
char c = line[index];
// Normalize some Unicode characters.
switch (c)
{
case '\u2018':
case '\u2019':
c = '\'';
break;
case '\u201C':
case '\u201D':
c = '"';
break;
}
// We need to determine if this is a word break or not. Word breaks
// happen with whitespace and punctuation, but there are special rules
// with single quotes.
bool isWordBreak = char.IsWhiteSpace(c) || char.IsPunctuation(c);
if (c == '\'')
{
// For single quotes, it is considered not a word break if there is
// a letter or digit on both sides of the quote.
bool isLetterBefore = index > 0 && char.IsLetterOrDigit(line[index - 1]);
bool isLetterAfter = index < line.Length - 1
&& char.IsLetterOrDigit(line[index + 1]);
isWordBreak = !isLetterAfter || !isLetterBefore;
}
// What we do is based on if we have a word break or not.
if (isWordBreak)
{
// If we have a text span, we need to finish it off.
if (textSpan != null)
{
textSpan.StopTextIndex = index;
textSpan = null;
}
}
else
{
// If we don't have a text span, then we need to create a new one.
// Otherwise, we bump up the index on the span.
if (textSpan == null)
{
// Create a new text span.
textSpan = new TextSpan
{
StartTextIndex = index,
StopTextIndex = index
};
// Add it to the collection.
textSpans.Add(textSpan);
}
else
{
// Update the existing text span.
textSpan.StopTextIndex = index;
}
}
}
// Finish up the last span, if we had one.
if (textSpan != null)
{
textSpan.StopTextIndex++;
}
// Return the list of text spans. We don't have to populate the strings
// because the calling class will do that for us.
return textSpans;
}
#endregion
}
}
|
f40a1e89e34217532c063f480a23e3e6c1ecfec5
|
[
"C#",
"Markdown"
] | 146 |
C#
|
PlumpMath/author-intrusion-cil
|
ba758fdabe341e052e1d6847e4262d5a876ea728
|
66e04281c75a1128e56d7fd3eeb718ad510be362
|
refs/heads/master
|
<file_sep># test5
this is a test package for laravel 5 package development
Installation:
Add the Test 5 package to your `composer.json` file
```json
{
"require": {
"amsify42/test5": "dev-master"
}
}
```
### Service Provider
In your app config, add the `Test5ServiceProvider` to the providers array.
```php
'providers' => [
'Amsify42\Test5\Test5ServiceProvider',
];
```
### Facade (optional)
If you want to make use of the facade, add it to the aliases array in your app config.
```php
'aliases' => [
'Test5' => 'Amsify42\Test5\Test5Facade',
];
```
### Publish file
```bash
$ php artisan vendor:publish
```
Now file with name test5.php will be copied in directory Config/ and you can add your settings
```php
return [
"message" => "Welcome to your new package"
];
```
### Add this line at the top of any class to use Test5
```php
use Test5;
```
### and use test functions
```php
Test5::testFunc();
Test5::testFunc()->testFunc2();
```
### or you can directly call Test5 without adding it at the top
```php
\Test5::testFunc();
\Test5::testFunc()->testFunc2();
```
<file_sep><?php
namespace Amsify42\Test5;
use Illuminate\Support\ServiceProvider;
use Illuminate\Routing\Router;
class Test5ServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
public function boot(){
$this->loadViewsFrom(realpath(__DIR__.'/../views'), 'amsify42');
$this->setupRoutes($this->app->router);
// this for conig
$this->publishes([
__DIR__.'/config/test5.php' => config_path('test5.php'),
]);
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function setupRoutes(Router $router){
$router->group(['namespace' => 'Amsify42\Test5\Http\Controllers'], function($router){
require __DIR__.'/Http/routes.php';
});
}
public function register() {
$this->registerTest5();
config([
'config/test5.php',
]);
}
private function registerTest5() {
$this->app->bind('Amsify42\Test5\Test5ServiceProvider',function($app){
return new Test5($app);
});
}
}
<file_sep><?php
namespace Amsify42\Test5\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Config;
class Test5Controller extends Controller {
/**
* Show the application welcome screen to the user.
*
* @return Response
*/
public function index() {
return view('amsify42::test5');
}
}
<file_sep><?php
Route::get('test5', 'Test5Controller@index');
<file_sep><?php
namespace Amsify42\Test5;
use Config;
class LaravelTest5 {
private $message;
public function __construct(){
$this->message = Config::get("test5.message");
echo 'Reached Constructor <br />';
echo 'Config Value: '.$this->message.'<br />';
}
public function testFunc() {
echo 'Reached Test Function 1 <br />';
return $this;
}
public function testFunc2() {
echo 'Reached Test Function 2';
}
}
<file_sep>@extends('amsify42::template')
@section('content')
@stop
|
0039f855e739357a4e0d978b48c213f251c97305
|
[
"Markdown",
"Blade",
"PHP"
] | 6 |
Markdown
|
amsify42/test5
|
b5f1d82eeecbef93041dfa01204eee5025fcd08f
|
3f7aebfe162c4bcbc2609206927f83ba08c72cce
|
refs/heads/master
|
<file_sep>extends layout
block content
.container.background-light.p3
p.mt4.center.cursive You are cordially invited to attend the marriage of
h1.center.mb0 Sarah
h6.center.mt0 Elizabeth Duty
p.center.mt2.mb2 —&—
h1.center.mt0.mb0 Aaron
h6.center.mt0.mb4 Howard English
hr
.row.clearfix.py2.center
.col.col-12.sm-col-6
.center.cursive When?
hr.eh
p Sunday February 28, 2016
p 4:00pm
.col.col-12.sm-col-6
hr.sm-hide.mt2.mb2
.center.cursive Where?
hr.eh
p Bridle Creek Ranch
p 5811 Roper Rd., Sperry Oklahoma
hr
h2.center R.S.V.P
if responded
h1.cursive.center Thanks!
p.center We'll see ya there!
else
form.center(action="submit" method="post")
label.block.cursive Email
input.field(required name="emal" placeholder="<EMAIL>")
<br>
<br>
label.block.cursive Phone
input.field(required name="phone" placeholder="1(800)-222-3333")
<br>
<br>
label.block.cursive Attending
input.field(required name="attending" placeholder="Yes, Heck yes, or Can't Make it?")
<br>
<br>
label.block.cursive Party Size
input.field(required name="partySize" placeholder="How many folks are you bringing?")
<br>
<br>
<br>
input.btn.btn-primary.center(type="submit" value="Party Time!")
.cursive.center.p4 #ForeverAnEnglish
<file_sep>var express = require('express');
var router = express.Router();
var Slack = require('node-slack');
const hookUrl = process.env.hookUrl || "";
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', {
title: 'Forever An English',
responded: false
});
});
router.post('/submit', function(req, res, next) {
if(hookUrl) {
var slack = new Slack(hookUrl);
slack.send({
"text": "ForeverAnEnglish.Com: " + JSON.stringify(req.body),
channel: "#service",
username: "HyphyBot"
});
} else {
console.log("No slack url... " + JSON.stringify(req.body));
}
res.render('index', {
title: 'Forever An English',
responded: true
});
});
module.exports = router;
<file_sep>doctype html
html
head
title= title
link(rel='stylesheet', href='http://d2v52k3cl9vedd.cloudfront.net/basscss/7.0.4/basscss.min.css')
link(rel='stylesheet', href='https://fonts.googleapis.com/css?family=Merriweather:400,300,700,900|Parisienne')
link(rel='stylesheet', href='/stylesheets/style.css')
body.background-dark
meta(name="viewport" content="width=device-width, initial-scale=1")
block content
|
cfa4bea95aa78d43b0b631fb873e6e3d3e073308
|
[
"JavaScript",
"Pug"
] | 3 |
JavaScript
|
ryanlabouve/ForeverAnEnglish
|
ed27876d9268e0bfbf3d4406ec757eab6576cad6
|
404a482841305d64abd11f6989a31ce10107d8a6
|
refs/heads/master
|
<file_sep>#ifndef GAME_H
#define GAME_H
//Inlcudes
#include <SDL2/SDL.h>
#include "Grid.h"
#define GAMEWIDTH 800
#define GAMEHEIGHT 800
typedef struct {
Grid grid;
}Game;
void GameInit(Game *game);
void GameClose(Game *game);
void GameTick(Game *game);
void GameRender(Game *game, SDL_Renderer *renderer);
#endif // GAME_H
<file_sep>#include "Game.h"
#include <stdio.h>
void GameInit(Game *game){
printf("Initializing the game\n");
InitGrid(&(*game).grid, 1000, 1000);
}
void GameClose(Game *game){
DestroyGrid(&(*game).grid);
}
void GameTick(Game *game){
GridTick(&game->grid);
}
void GameRender(Game *game, SDL_Renderer *renderer){
GridRender(&game->grid, renderer);
}
<file_sep>#ifndef GRID_H
#define GRID_H
#include <SDL2/SDL.h>
#define PRAY_THRESHHOLD 50
#define STARTING_HEALTH 100
typedef struct{
Uint8 type;
int health;
}Tile;
typedef struct {
Uint8 height, width;
Tile ***tileMap;
}Grid;
void InitGrid(Grid *grid, int, int);
void DestroyGrid(Grid *grid);
void GridRender(Grid *grid, SDL_Renderer *renderer);
void GridTick(Grid *grid);
void DoPredatorLogic(Grid *grid, int x, int y);
void DoPrayLogic(Grid *grid, int x, int y);
void moveTile(Grid *grid, int xSrc, int ySrc,int xDes,int yDes);
void getRandomXYInGrid(Grid *grid, int *x, int *y);
#endif // GRID_H
<file_sep># PredatorAndPrayC
Predator and pray written in C with SDL
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include <SDL2/SDL.h>
#include "Game.h"
int main(int argc, char** argv)
{
// Initialize SDL
SDL_Init(SDL_INIT_VIDEO);
// Open a 800x600 window and define an accelerated renderer
SDL_Window* window = SDL_CreateWindow("PredatorAndPray", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
GAMEWIDTH, GAMEHEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
// Initial renderer color
//SDL_SetRenderDrawColor(renderer, randCol(), randCol(), randCol(), 255);
bool running = true;
int ticksPerSecond = 10000;
int tickTime = 1000/ticksPerSecond;
int lastTime = 0, deltaTime = 0;
Uint32 lastSecond = 0, frames = 0;//Vars to hold render data like fps
SDL_Event event;
srand(time(NULL)); // randomize seed
//Init the game
Game game;
GameInit(&game);
while (running)
{
// Check for various events (keyboard, mouse, touch, close)
while (SDL_PollEvent(&event))
{
if (event.type == SDL_KEYDOWN)
{
const char* key = SDL_GetKeyName(event.key.keysym.sym);
if (strcmp(key, "Escape") == 0)
{
running = false;
}
}
else if (event.type == SDL_QUIT)
{
running = false;
}
}
int now = SDL_GetTicks();
deltaTime += now - lastTime;
lastTime = now;
if(deltaTime > tickTime)
{
deltaTime -= tickTime;
// Clear buffer
SDL_RenderClear(renderer);
//Run a tick
// fill the scene with white
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderClear(renderer);
//Draw the game here
GameRender(&game, renderer);
//Tick the game
GameTick(&game);
//Get ready for the next frame, and show current frame
SDL_RenderPresent(renderer);
deltaTime -= 0;
frames++;
if(lastSecond + 1000 < SDL_GetTicks()){
lastSecond += 1000;
printf("Frames last second: %u\n", frames);
frames = 0;
}
}
}
//Were closing the game. Cleanup the resources of the game too
GameClose(&game);
// Release any of the allocated resources
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
<file_sep>#include "Grid.h"
#include <stdio.h>
#include <stdlib.h>
#include "Game.h"
void InitGrid(Grid *grid, int height, int width){
int x,y, randomInt, count=0;
(*grid).height = height;
(*grid).width = width;
//Init the width of the array
(*grid).tileMap = malloc(sizeof(Tile*) * width);
for(x = 0; x < width; x++){
//for the current x init the height of the array
grid->tileMap[x] = malloc(sizeof(Tile) * height);
for(y = 0; y < height; y++){
grid->tileMap[x][y] = malloc(sizeof(Tile));
//printf("Creating tile at %i:%i with a value of 0\n", x, y);
randomInt = rand() % 100;
if(randomInt <= 10){
grid->tileMap[x][y]->type = 1;
}else if(randomInt <= 20) {
grid->tileMap[x][y]->type = 2;
}else{
grid->tileMap[x][y]->type = 0;
}
count++;
if(grid->tileMap[x][y]->type == 1){
grid->tileMap[x][y]->health = 1;
}else{
grid->tileMap[x][y]->health = STARTING_HEALTH;
}
}
}
//printf("The int at %i\n", count);
}
void DestroyGrid(Grid *grid){
int x;
for(x = 0; x < (*grid).width; x++){
//for the current x init the height of the array
free((*grid).tileMap[x]);
}
free((*grid).tileMap);
}
void GridRender(Grid *grid, SDL_Renderer *renderer){
//SDL_Rect rect = {2,2,20,20};
//SDL_RenderFillRect(renderer, &rect);
//Calculate the width and height of a single rectangle based on grid tilemap
int width = GAMEWIDTH, height = GAMEHEIGHT;
SDL_Rect rect;
int x,y;
width /= grid->width;
height /= grid->height;
//printf("Drawing the grid with rect size %i:%i\n", width, height);
//Set rect width and height
rect.w = width;
rect.h = height;
//Draw all tiles
for(x = 0; x < grid-> width; x++){
for(y = 0; y < grid->height; y++){
//Set the renderer color
switch(grid->tileMap[x][y]->type){
case 1:
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
break;
case 2:
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
break;
default:
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
break;
}
//Set the rect variables and render it
rect.x = x * width;
rect.y = y * height;
SDL_RenderFillRect(renderer, &rect);
}
}
}
void GridTick(Grid *grid){
int x,y;
for(x = 0; x < grid->width; x++){
for(y = 0; y < grid->height; y++){
if(grid->tileMap[x][y]->type != 0){//Its either a prey or predator
if(grid->tileMap[x][y]->type == 1){//Its a pray
DoPrayLogic(grid, x, y);
}else{//Its a predator
DoPredatorLogic(grid, x,y);
}
}
}
}
}
void DoPredatorLogic(Grid *grid, int x, int y){
grid->tileMap[x][y]->health--;//Lose health
if(grid->tileMap[x][y]->health == 0){
grid->tileMap[x][y]->type = 0; //The predator dies
}
int newX, newY;
getRandomXYInGrid(grid, &newX, &newY);
if(grid->tileMap[newX][newY]->type == 0){//Moving onto an empty tile
//printf("Predator moving onto tile %i:%i, with type %i\n", newX, newY, grid->tileMap[newX][newY]->type);
moveTile(grid, x, y, newX, newY);
}else if(grid->tileMap[newX][newY]->type == 1){//Moving onto a pray tile
grid->tileMap[newX][newY]->type = 2;//The pray is now a predator
//grid->tileMap[newX][newY]->health = STARTING_HEALTH;
grid->tileMap[x][y]->health += grid->tileMap[newX][newY]->health;
}//Else its a predator so we cant move
}
void DoPrayLogic(Grid *grid, int x, int y){
grid->tileMap[x][y]->health++;//Gain health
int newX = x, newY = y;
getRandomXYInGrid(grid, &newX, &newY);
if(grid->tileMap[x][y]->health >= PRAY_THRESHHOLD){//Check health threshhold
int count;
while(grid->tileMap[newX][newY]->type != 0 && count < 10){//Try 10 times for a random position if its empty
count++;
getRandomXYInGrid(grid, &newX, &newY);
}
if(count != 10){//We found a random position
grid->tileMap[newX][newY]->type = 1;
grid->tileMap[newX][newY]->health = 10;
grid->tileMap[x][y]->health = 10;
}
}
getRandomXYInGrid(grid, &newX, &newY);
if(grid->tileMap[newX][newY]->type == 0){//Moving onto an empty tile
moveTile(grid, x, y, newX, newY);
}//We can only move onto an empty tile
}
void moveTile(Grid *grid, int xSrc,int ySrc,int xDes,int yDes){
grid->tileMap[xDes][yDes]->health = grid->tileMap[xSrc][ySrc]->health;
grid->tileMap[xDes][yDes]->type = grid->tileMap[xSrc][ySrc]->type;
grid->tileMap[xSrc][ySrc]->type = 0;
}
void getRandomXYInGrid(Grid *grid, int *x, int *y){
*x += rand() % 3 - 1;
*y += rand() % 3 - 1;
//Make sure we dont move off the screen
if(*x < 0) *x = 0;
if(*x >= grid->width) *x = grid->width - 1;
if(*y < 0) *y = 0;
if(*y >= grid->height) *y = grid->height - 1;
//printf("Returned %i:%i for random numbers\n", *x, *y);
}
|
cc7e4995c256fb9f5635804d8129a76e78d9cdbe
|
[
"Markdown",
"C"
] | 6 |
Markdown
|
Stiixxy/PredatorAndPrayC
|
27d8b7b360653cf84fcdaf5d9475cac53661c489
|
b0403d55f7dcf2173a7538a16b3f4e91f5c095cb
|
refs/heads/master
|
<file_sep># gcp-cli
gcp-cli
|
ee5a4229d95e0c296017a0fa0d01c62da86f7aeb
|
[
"Markdown"
] | 1 |
Markdown
|
gazalinawaz/gcp-cli
|
d85fdb3e09344552fc01c03e5454df38c9a41c6c
|
f8be050d306dc6d0e621547c9289181e524ab3b0
|
refs/heads/master
|
<repo_name>dctxf/hexo-theme-Anatole<file_sep>/_config.yml
keywords: Hexo,HTML,dctxf,design,设计,前端
author: dctxf,<EMAIL>
description: Just for the tiny flame in my heart.
avatar: https://s.gravatar.com/avatar/a8c5452b5168fb1500c7e59129cb1ad5?s=80
twitter: dctxf
rss: rss.xml
weibo: dctmz
instagram: dctxf
github: dctxf
behance: dctxf
# Comment
duoshuo:
disqus: dctxf
|
57b42927bb43c8fde1b1441c09da70a027729f81
|
[
"YAML"
] | 1 |
YAML
|
dctxf/hexo-theme-Anatole
|
5f8c50620228fe40dfe8e0aa34d6ff5d8cf6aa19
|
bab1d47692dac65e763d31bd9cc8e0c63332600f
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Jul 27 07:26:07 2018
@author: <NAME>
title: start_calib
"""
#%% Imports
import numpy as np
from calib_main import calib_main
from load_pickle import load_pickle
#%% Version number
version_num = 'V9'
#%% data path
directory = 'F:\\Arbeit und Uni\\MasterArbeit\\'
# path to the pupil capture data
data_directory = directory + 'Pupil_VR_Recordings\\'
# path to the calibration data from the stimulus script
time_directory = directory + 'HTC_Vive_Recs\\Data\\'
#%% Configurations
disp_plots = 1
# 1. uncalibrated data; 2. GT after calibration
disp_what = [1, 1, 0]
# atm calculated data can't be saved
save_data = 0
# forst check the save directory for the plots
save_plots = 0
#%% choose data set
choose_dataset = 0
if choose_dataset == 0:
# specify the recording you want to calibrate
subj_name = 'olbe'
file_date = '2018_11_20'
file_num = '001'
# capture frequency in Hz
set_fps = 120
# left; right; both
use_eye = 'both'
#%% load calibration times from pickle file
mask_ind_cal,mask_ind_val = load_pickle(time_directory,subj_name,file_date,file_num)
#%% extract calibration grid
gt_px = mask_ind_cal[:,3:5]
#%% specify dots for calibration and validation
cal_dots = np.linspace(1,np.size(gt_px,0),np.size(gt_px,0));
val_dots = np.linspace(1,np.size(gt_px,0),np.size(gt_px,0));
#%% choose coefficents for design matrix
choose_coeff = 1
if choose_coeff == 1:
coeff_num_all = 6
cal_form_all_x = [['1','x','y','x^2','y^2','x*y']]
cal_form_all_y = [['1','x','y','x^2','y^2','x*y']]
cal_form_all = [cal_form_all_x, cal_form_all_y]
#%% screen resolutions
screen_width = np.nan
screen_height = np.nan
screen_dist = 1
#%% shorten input data and configs
class CalibConfig(object):
def __init__(self, disp_plots, disp_what, save_data, save_plots):
self.disp_plots = disp_plots
self.disp_what = disp_what
self.save_data = save_data
self.save_plots = save_plots
fct_cfg = CalibConfig(disp_plots, disp_what, save_data, save_plots)
class CalibInputValue(object):
def __init__(self, coeff_num_all, cal_form_all, version_num, data_directory,
time_directory, subj_name, file_date, file_num, mask_ind_cal,
mask_ind_val, cal_dots, val_dots, gt_px, set_fps, use_eye):
self.coeff_num_all = coeff_num_all
self.cal_form_all = cal_form_all
self.version_num = version_num
self.data_directory = data_directory
self.time_directory = time_directory
self.subj_name = subj_name
self.file_date = file_date
self.file_num = file_num
self.mask_ind_cal = mask_ind_cal
self.mask_ind_val = mask_ind_val
self.cal_dots = cal_dots
self.val_dots = val_dots
self.gt_px = gt_px
self.set_fps = set_fps
self.use_eye = use_eye
fct_in = CalibInputValue(coeff_num_all, cal_form_all, version_num, data_directory,
time_directory, subj_name, file_date, file_num, mask_ind_cal,
mask_ind_val, cal_dots, val_dots, gt_px, set_fps, use_eye)
class ScreenConfig(object):
def __init__(self, screen_width, screen_height, screen_dist):
self.screen_width = screen_width
self.screen_height = screen_height
self.screen_dist = screen_dist
screen_cfg = ScreenConfig(screen_width, screen_height, screen_dist)
#%% Output
fct_out = calib_main(fct_cfg,fct_in,screen_cfg)<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Jul 27 10:41:00 2018
@author: <NAME>
title: build_grid
"""
#%% Imports
import numpy as np
from calib_function import calib_function
from valid_function import valid_function
#%% main function
def build_grid(cal_data, val_data, ground_truth, cal_dots, val_dots, cal_form,
coeff_num):
# reshape fixation data coressponding do used training dots
cal_data_reshape = np.ndarray((np.size(cal_dots,0),np.size(ground_truth,0),2))
cal_data_reshape = cal_data[cal_dots,:,:]
# reshape GT data corresponding do used training dots
ground_truth_cal_reshape = np.ndarray((np.size(cal_dots,0),np.size(ground_truth,1)))
ground_truth_cal_reshape = ground_truth[cal_dots,:]
ground_truth_val_reshape = np.ndarray((np.size(val_dots,0),np.size(ground_truth,1)))
ground_truth_val_reshape = ground_truth[val_dots,:]
# reshape validation data coressponding do used validation dots
val_data_reshape = np.ndarray((np.size(val_dots,0),np.size(ground_truth,0),2))
val_data_reshape = val_data[val_dots,:,:]
# calibrate left eye
cal_coeff_left,cal_form_left = \
calib_function(cal_data_reshape[:,:,0], ground_truth_cal_reshape,
cal_form, coeff_num);
cal_grid_left = \
valid_function(val_data_reshape[:,:,0], cal_coeff_left, cal_form_left)
# calibrate right eye
cal_coeff_right,cal_form_right = \
calib_function(cal_data_reshape[:,:,1], ground_truth_cal_reshape,
cal_form, coeff_num);
cal_grid_right = \
valid_function(val_data_reshape[:,:,1], cal_coeff_right, cal_form_right)
#%% calculate mean grid and RMSE
cal_grid = np.ndarray((np.size(val_dots,0),np.size(cal_form,0),3))
# left
cal_grid[:,:,0] = cal_grid_left
# right
cal_grid[:,:,1] = cal_grid_right
# mean: x,y,z
cal_grid[:,0,2] = np.mean([cal_grid_left[:,0],cal_grid_right[:,0]], axis = 0)
cal_grid[:,1,2] = np.mean([cal_grid_left[:,1],cal_grid_right[:,1]], axis = 0)
# calculate RMSE and delta z
cal_diff = np.ndarray((np.size(ground_truth_val_reshape,0),4))
cal_diff[:,0:np.size(ground_truth,1)] = np.squeeze(cal_grid[:,:,2]) - \
ground_truth_val_reshape
if np.size(ground_truth,1) == 3:
cal_diff[:,3] = abs(cal_diff[:,2]);
else:
nanarray = np.ndarray((np.size(ground_truth_val_reshape,0),1))
nanarray.fill(np.nan)
cal_diff[:,3] = nanarray[:,0]
cal_diff[:,2] = cal_diff[:,0]**2 + cal_diff[:,1]**2
# Output
cal_coeff = np.ndarray((np.size(cal_form,0),np.size(cal_form[0][:],1),2))
cal_coeff[:,:,0] = cal_coeff_left[:,:]
cal_coeff[:,:,1] = cal_coeff_right[:,:]
cal_form = cal_form #[cal_form_left, cal_form_right];
return cal_coeff, cal_form, cal_grid, cal_diff<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Feb 27 13:16:58 2018
@author: VRLab
"""
import pickle
import numpy as np
def load_pickle(directory,subj_name,file_date,file_num):
name_list = ['_calib_', '_valid_']
path = directory + subj_name + '/'
for j in range(2):
file_name_cal = subj_name + name_list[j] + file_date + '_' + file_num
load_temp = pickle.load(open(path + file_name_cal + '.p', 'rb'))
data_temp = np.zeros((np.size(load_temp[0],0),5))
data_temp[:,0:1] = np.asarray(load_temp[0])
data_temp[:,3:5] = np.asarray(load_temp[1][:,0:2])
# assign a number to each datapoint and sort by time
data_temp[:,2] = np.linspace(1,np.size(load_temp[0],0),np.size(load_temp[0],0))
data_temp = data_temp[data_temp[:,0].argsort()]
# assign an order to each datapoint and sort by the number of each datapoint
data_temp[:,1] = np.linspace(1,np.size(load_temp[0],0),np.size(load_temp[0],0))
data_temp = data_temp[data_temp[:,2].argsort()]
if j == 0:
calib_data = data_temp
elif j == 1:
valid_data = data_temp
return calib_data,valid_data<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Jul 27 07:16:34 2018
@author: <NAME>
title: calib_main
"""
#%% Imports
from load_pupil import load_pupil
from build_val import build_val
from plot_results import plot_Grid_2D
from plot_results import plot_mask
from plot_results import plot_calib
from pix2deg import pix2deg
import numpy as np
import pickle
#%% shorten Output
class CalibReturnValue(object):
def __init__(self, fct_in, fct_cfg, csv_data, eye_data, masked_eye_data,
val_eye_data, masked_val_eye_data, cal_coeff, gt_deg,
fixation_cal_data, fixation_val_data, cal_grid, cal_diff):
self.fct_in = fct_in
self.fct_cfg = fct_cfg
# self.csv_data = csv_data
self.eye_data = eye_data
self.masked_eye_data = masked_eye_data
self.val_eye_data = val_eye_data
self.masked_val_eye_data = masked_val_eye_data
self.cal_coeff = cal_coeff
self.gt_deg = gt_deg
self.fixation_cal_data = fixation_cal_data
self.fixation_val_data = fixation_val_data
self.cal_grid = cal_grid
self.cal_diff = cal_diff
#%% define left and reight based on the used eye
# HTC: left = id1 right = id0
def change_left_right(use_eye,csv_data):
if use_eye == 'left':
print('Using Right Eye')
# eyedata
csv_data.id0_eyedata = csv_data.id1_eyedata
# capture_data
csv_data.id0_capturedata = csv_data.id1_capturedata
# frame_drops
csv_data.id0_rel_framedrops = csv_data.id1_rel_framedrops
csv_data.id0_abs_framedrops = csv_data.id1_abs_framedrops
# fps
csv_data.id0_real_fps = csv_data.id1_real_fps
elif use_eye == 'right':
print('Using Left Eye')
# eyedata
csv_data.id1_eyedata = csv_data.id0_eyedata
# capture_data
csv_data.id1_capturedata = csv_data.id0_capturedata
# frame_drops
csv_data.id1_rel_framedrops = csv_data.id0_rel_framedrops
csv_data.id1_abs_framedrops = csv_data.id0_abs_framedrops
# fps
csv_data.id1_real_fps = csv_data.id0_real_fps
elif use_eye == 'both':
print('Using Both Eye')
# eyedata
temp_id0_eyedata = csv_data.id0_eyedata
temp_id1_eyedata = csv_data.id1_eyedata
csv_data.id0_eyedata = temp_id1_eyedata
csv_data.id1_eyedata = temp_id0_eyedata
# capture_data
temp_id0_capturedata = csv_data.id0_capturedata
temp_id1_capturedata = csv_data.id1_capturedata
csv_data.id0_capturedata = temp_id1_capturedata
csv_data.id1_capturedata = temp_id0_capturedata
# frame_drops
temp_id0_rel_framedrops = csv_data.id0_rel_framedrops
temp_id1_rel_framedrops = csv_data.id1_rel_framedrops
csv_data.id0_rel_framedrops = temp_id1_rel_framedrops
csv_data.id1_rel_framedrops = temp_id0_rel_framedrops
temp_id0_abs_framedrops = csv_data.id0_abs_framedrops
temp_id1_abs_framedrops = csv_data.id1_abs_framedrops
csv_data.id0_abs_framedrops = temp_id1_abs_framedrops
csv_data.id1_abs_framedrops = temp_id0_abs_framedrops
# fps
temp_id0_real_fps = csv_data.id0_real_fps
temp_id1_real_fps = csv_data.id1_real_fps
csv_data.id0_real_fps = temp_id1_real_fps
csv_data.id1_real_fps = temp_id0_real_fps
return csv_data
#%% main function
def calib_main(fct_cfg, fct_in, screen_cfg):
#%% dont change these configs
fix_time = 1
use_filter = 0
window_size = 10
csv_data_input = 'pupil_positions.csv'
info_input = 'info.csv'
#%% load recorded data
csv_data = load_pupil(fct_in.data_directory, fct_in.file_date, fct_in.file_num,
csv_data_input, info_input, fix_time, fct_in.set_fps,
use_filter, window_size)
# choose which eye u want to use
csv_data = change_left_right(fct_in.use_eye,csv_data)
# save recorded data in new array
# eye_data(t,parameter,eye)
eye_data = np.ndarray((np.size(csv_data.id0_eyedata,0),np.size(csv_data.id0_eyedata,1),2))
eye_data[:,:,0] = csv_data.id0_eyedata
eye_data[:,:,1] = csv_data.id1_eyedata
real_fps = np.ndarray((2,))
real_fps[0] = csv_data.id0_real_fps
real_fps[1] = csv_data.id1_real_fps
print('Finished Loading')
#%% change gt_px from pixels to degree (gt_deg)
gt_deg = np.ndarray((np.shape(fct_in.gt_px)))
gt_deg[:,0],gt_deg[:,1] = pix2deg(fct_in.gt_px[:,0],fct_in.gt_px[:,1],screen_cfg,'3D')
#%% extract fixation data from eyedata
# calibration
mask_cal = np.zeros((np.size(eye_data,0),1), dtype = bool)
mask_ind_cal_temp = fct_in.mask_ind_cal
mask_ind_cal_temp[:,0] = mask_ind_cal_temp[:,0] - float(csv_data.info.loc[:,'Start Time (System)'][0])
fixation_cal_data = np.ndarray((np.size(fct_in.mask_ind_cal,0),2,2))
# save coordinates to i
cal_inds = [0] * np.size(fct_in.mask_ind_cal,0)
for i in range(np.size(mask_ind_cal_temp,0)):
cal_inds[i] = np.where(eye_data[:,0,0] > mask_ind_cal_temp[i,0])[0][0]
mask_cal[cal_inds[i]] = 1
fixation_cal_data = eye_data[cal_inds,3:5,:]
# validation
mask_val = np.zeros((np.size(eye_data,0),1), dtype = bool)
mask_ind_val_temp = fct_in.mask_ind_val
mask_ind_val_temp[:,0] = mask_ind_val_temp[:,0] - float(csv_data.info.loc[:,'Start Time (System)'][0])
fixation_val_data = np.ndarray((np.size(fct_in.mask_ind_val,0),2,2))
# save coordinates to i
val_inds = [0] * np.size(fct_in.mask_ind_val,0)
for i in range(np.size(mask_ind_cal_temp,0)):
val_inds[i] = np.where(eye_data[:,0,0] > mask_ind_val_temp[i,0])[0][0]
mask_val[val_inds[i]] = 1
fixation_val_data = eye_data[val_inds,3:5,:]
# change time values in the mask array to integers
mask_ind_cal = np.ndarray((np.size(cal_inds),4))
mask_ind_cal[:,0] = cal_inds
mask_ind_cal[:,1] = cal_inds
mask_ind_cal[:,2] = mask_ind_cal_temp[:,1]
mask_ind_cal[:,3] = mask_ind_cal_temp[:,2]
mask_ind_val = np.ndarray((np.size(val_inds),4))
mask_ind_val[:,0] = val_inds
mask_ind_val[:,1] = val_inds
mask_ind_val[:,2] = mask_ind_val_temp[:,1]
mask_ind_val[:,3] = mask_ind_val_temp[:,2]
# create masked eye_data
mask = mask_cal | mask_val
masked_eye_data = eye_data[mask[:,0],:,:]
# calibrate all dots
cal_coeff,cal_grid,val_eye_data,cal_diff = \
build_val(eye_data,real_fps,fixation_cal_data,fixation_val_data,
gt_deg,range(np.size(gt_deg,0)),range(np.size(gt_deg,0)),
fct_in.cal_form_all,fct_in.coeff_num_all)
print('Finished Calibrating')
# create mask with val_eye_data
masked_val_eye_data = val_eye_data[mask[:,0],:,:]
#%% plot results
if fct_cfg.disp_plots == 1:
if fct_cfg.disp_what[0] == 1:
plot_mask(mask_ind_cal, eye_data, masked_eye_data, fct_cfg.save_plots)
if fct_cfg.disp_what[1] == 1:
plot_Grid_2D(cal_grid, gt_deg, fct_cfg.save_plots)
if fct_cfg.disp_what[2] == 1:
plot_calib(masked_val_eye_data, val_eye_data, gt_deg, cal_grid, fct_cfg.save_plots)
print('Finished Plotting')
#%% save output data
fct_out = CalibReturnValue(fct_in, fct_cfg, csv_data, eye_data, masked_eye_data,
val_eye_data, masked_val_eye_data,cal_coeff, gt_deg,
fixation_cal_data, fixation_val_data, cal_grid, cal_diff)
#%% output
return fct_out
<file_sep># -*- coding: utf-8 -*-
"""
Created on Mon Aug 6 10:58:17 2018
@author: <NAME>
title: pix2deg
"""
#%% Imports
import numpy as np
#%% main function
def pix2deg(x_px,y_px,cfg,mode):
if mode == '2D':
x_rad = np.arctan((x_px * cfg.screen_width)/(cfg.screen_xres * cfg.screen_dist))
y_rad = np.arctan((y_px * cfg.screen_height)/(cfg.screen_yres * cfg.screen_dist))
x_deg = x_rad / np.pi * 180
y_deg = y_rad / np.pi * 180
elif mode == '3D':
x_rad = np.arctan(x_px / cfg.screen_dist)
y_rad = np.arctan(y_px / cfg.screen_dist)
x_deg = x_rad / np.pi * 180
y_deg = y_rad / np.pi * 180
return x_deg, y_deg
<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Jul 27 10:34:42 2018
@author: <NAME>
title: build_val
"""
#%% Imports
import numpy as np
from build_grid import build_grid
from valid_function import valid_function
#%% main function
def build_val(eye_data, fps, cal_data, val_data, ground_truth, cal_dots,
val_dots, cal_form, coeff_num):
# calibrate with the chosen dots
cal_coeff, cal_form, cal_grid, cal_diff = \
build_grid(cal_data, val_data, ground_truth, cal_dots, val_dots,
cal_form, coeff_num)
# validate the whole eyedata and save the calibrated eyedata
val_eye_data = np.ndarray((np.size(eye_data,0),10,2))
val_eye_data.fill(np.nan)
for i in range(2):
# time, worldframe, confidence
val_eye_data[:,0:3,i] = eye_data[:,0:3,i]
# validated x,y,z in °
if np.size(ground_truth,1) == 3:
val_eye_data[:,3:6,i] = \
valid_function(eye_data[:,3:5,i],cal_coeff[:,:,i],cal_form)
else:
val_eye_data[:,3:5,i] = \
valid_function(eye_data[:,3:5,i],cal_coeff[:,:,i],cal_form)
# pupil diameter
val_eye_data[:,6,i] = eye_data[:,5,i]
# v_x, v_y, v_z in °/s
if np.size(ground_truth,1) == 3:
val_eye_data[:,7:10,i] = \
np.vstack([[0, 0, 0], np.diff(val_eye_data[:,3:6,i], axis = 0)*fps[i]])
else:
val_eye_data[:,7:9,i] = \
np.vstack([[0, 0], np.diff(val_eye_data[:,3:5,i], axis = 0)*fps[i]])
return cal_coeff, cal_grid, val_eye_data, cal_diff
<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Jul 27 11:01:09 2018
@author: <NAME>
title: valid_function
"""
#%% Imports
import numpy as np
#%% main function
def valid_function(input_data,cal_coeff,cal_form):
output_val = np.ndarray((np.size(input_data,0),np.size(cal_form,0)))
for i in range(np.size(cal_form,0)):
val_comp = np.ndarray((np.size(input_data,0),np.size(cal_form[0][:],1)))
for j in range(np.size(cal_form[0][:],1)):
if cal_form[i][0][j] == '1':
val_comp[:,j] = \
cal_coeff[i,j] * np.ones((np.size(input_data,0),))
elif cal_form[i][0][j] == 'x':
val_comp[:,j] = \
cal_coeff[i,j] * input_data[:,0]
elif cal_form[i][0][j] == 'x^2':
val_comp[:,j] = \
cal_coeff[i,j] * input_data[:,0]**2
elif cal_form[i][0][j] == 'x^3':
val_comp[:,j] = \
cal_coeff[i,j] * input_data[:,0]**3
elif cal_form[i][0][j] == 'y':
val_comp[:,j] = \
cal_coeff[i,j] * input_data[:,1]
elif cal_form[i][0][j] == 'y^2':
val_comp[:,j] = \
cal_coeff[i,j] * input_data[:,1]**2
elif cal_form[i][0][j] == 'y^3':
val_comp[:,j] = \
cal_coeff[i,j] * input_data[:,1]**3
elif cal_form[i][0][j] == 'x*y':
val_comp[:,j] = \
cal_coeff[i,j] * input_data[:,0]*input_data[:,1]
elif cal_form[i][0][j] == 'x^2*y':
val_comp[:,j] = \
cal_coeff[i,j] * input_data[:,0]**2*input_data[:,1]
elif cal_form[i][0][j] == 'x*y^2':
val_comp[:,j] = \
cal_coeff[i,j] * input_data[:,0]*input_data[:,1]**2
elif cal_form[i][0][j] == 'x^2*y^2':
val_comp[:,j] = \
cal_coeff[i,j] * input_data[:,0]**2*input_data[:,1]**2
elif cal_form[i][0][j] == '0':
val_comp[:,j] = \
cal_coeff[i,j] * np.zeros((np.size(input_data,0),))
output_val[:,i] = np.sum(val_comp[:,:], axis = 1)
return output_val
<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Aug 2 11:56:40 2018
@author: <NAME>
title: calc_projection
"""
#%% Imports
import numpy as np
from copy import deepcopy
#%% main functions
def viewmtx(az,el,phi,target):
if phi>0:
d = np.sqrt(2)/2/np.tan(phi*np.pi/360)
else:
phi = 0
# Make sure data is in the correct range.
el = (((el+180)%360)+360%360)-180
if el>90:
el = 180-el
az = az + 180
elif el<-90:
el = -180-el
az = az + 180
az = (az%360)+360%360
#Convert from degrees to radians.
az = az*np.pi/180
el = el*np.pi/180
if 'target' not in locals():
target = 0.5 + np.sqrt(3)/2*np.asarray([[np.cos(el)*np.sin(az), -np.cos(el)*np.cos(az), np.sin(el)]])
# View transformation matrix:
# Formed by composing two rotations:
# 1) Rotate about the z axis -AZ radians
# 2) Rotate about the x axis (EL-pi/2) radians
T = np.asarray([[np.cos(az), np.sin(az), 0, 0],
[-np.sin(el)*np.sin(az), np.sin(el)*np.cos(az), np.cos(el), 0],
[np.cos(el)*np.sin(az), -np.cos(el)*np.cos(az), np.sin(el), 0],
[0, 0, 0, 1]])
# Default focal length.
f = d
# Transformation to move origin of object coordinate system to TARGET
eye = np.identity(4)
temp1 = eye[:,0:3]
temp2 = np.dot(T, np.append(-target,1))
temp2 = temp2.reshape(4,1)
O1 = np.append(temp1[:,:], temp2[:,:], axis=1)
# Perspective transformation
P = np.asarray([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, -1/f, d/f]])
# The perspective transformation above works because the graphics
# system divides by the homogenous length, w, before mapping to the screen.
# If the homegeous vector is given by V = [x,y,z,w] then the transformed
# point is U = [x/w y/w].
# Using f = d places the image plane through the origin of the object
# coordinate system, thus projecting the object onto this plane. Note only
# the x and y coordinates are used to draw the object in the graphics window.
# Form total transformation
return np.dot(P, np.dot(O1, T))
def calc_projection(input_3D,azimuth,elevation,angle,center):
temp_in = deepcopy(input_3D)
input_3D[:,1] = temp_in[:,2]
input_3D[:,2] = temp_in[:,1]
a = viewmtx(azimuth,elevation,angle,center);
m = np.size(input_3D,0)
x4d = np.vstack((input_3D[:,0], input_3D[:,1], input_3D[:,2], np.ones((m,))))
x2d = np.dot(a, x4d)
x2 = np.zeros((m,1))
y2 = np.zeros((m,1))
x2 = x2d[0,:]/x2d[3,:]
y2 = x2d[1,:]/x2d[3,:]
output_2D = np.transpose(np.vstack((x2, y2)))
return output_2D
#import numpy.matlib as npm
#gt_px = np.ndarray((27,3))
#gt_px[:,0] = 10 * np.hstack((-np.ones((9,)), np.zeros((9,)), np.ones((9,))))
#gt_px[:,1] = 10 * npm.repmat(np.hstack((-np.ones((3,)), np.zeros((3,)), np.ones((3,)))), 1, 3)
#gt_px[:,2] = 10 * npm.repmat(np.asarray([[-1,0,1]]), 1, 9)
#
#gt_px = calc_projection(gt_px,0,0,1,np.asarray([[0, 0, 0]]))
<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Jul 27 10:59:59 2018
@author: <NAME>
title: calib_function
"""
#%% Imports
import numpy as np
from sklearn.linear_model import LinearRegression
#%% main function
def calib_function(input_data, ground_truth, cal_form, coeff_num):
# create deisgn matrix
design_X = np.ndarray((np.size(input_data,0),np.size(cal_form[0][:],1),np.size(cal_form,0)))
for i in range(np.size(cal_form,0)):
x_comp = np.ndarray((np.size(input_data,0),np.size(cal_form[0][:],1)))
for j in range(np.size(cal_form[0][:],1)):
if cal_form[i][0][j] == '1':
x_comp[:,j] = \
np.ones((np.size(input_data,0),))
elif cal_form[i][0][j] == 'x':
x_comp[:,j] = \
input_data[:,0]
elif cal_form[i][0][j] == 'x^2':
x_comp[:,j] = \
input_data[:,0]**2
elif cal_form[i][0][j] == 'x^3':
x_comp[:,j] = \
input_data[:,0]**3
elif cal_form[i][0][j] == 'y':
x_comp[:,j] = \
input_data[:,1]
elif cal_form[i][0][j] == 'y^2':
x_comp[:,j] = \
input_data[:,1]**2
elif cal_form[i][0][j] == 'y^3':
x_comp[:,j] = \
input_data[:,1]**3
elif cal_form[i][0][j] == 'x*y':
x_comp[:,j] = \
input_data[:,0]*input_data[:,1]
elif cal_form[i][0][j] == 'x^2*y':
x_comp[:,j] = \
input_data[:,0]**2*input_data[:,1]
elif cal_form[i][0][j] == 'x*y^2':
x_comp[:,j] = \
input_data[:,0]*input_data[:,1]**2
elif cal_form[i][0][j] == 'x^2*y^2':
x_comp[:,j] = \
input_data[:,0]**2*input_data[:,1]**2
elif cal_form[i][0][j] == '0':
x_comp[:,j] = \
np.zeros((np.size(input_data,0),))
design_X[:,:,i] = x_comp[:,:]
cal_coeff = np.ndarray((np.size(cal_form,0),np.size(cal_form[0][:],1)))
design_Y = ground_truth
for i in range(np.size(cal_form,0)):
x_eye = design_X[:,:,i]
y_eye = design_Y[:,i]
regressor = LinearRegression(fit_intercept = False)
regressor.fit(x_eye, y_eye)
cal_coeff[i,:] = regressor.coef_
cal_form = cal_form
return cal_coeff, cal_form
<file_sep># PupilLabs_VR_Calibration
Python scripts used for Calibration of the PupilLabs Eyetrackers in our VR Setup.
To start the calibration run the 'calib_start' script.
<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Jul 31 10:52:39 2018
@author: <NAME>
title: plot_results
"""
#%% Imports
import matplotlib.pyplot as plt
import numpy as np
#%% close all old plots
plt.close('all')
plt.rc('axes', axisbelow=True)
#%% Main Functions
#%% calculate limits for eye_data plots
def calc_lims_eye_data(eye_data):
tmin = 0
tmax = np.ceil(np.max(eye_data[:,0,0]))
xmax = np.max(np.hstack((eye_data[:,3,0], eye_data[:,3,1])))*1.1
ymax = np.max(np.hstack((eye_data[:,4,0], eye_data[:,4,1])))*1.1
xmin = abs(np.min(np.hstack((eye_data[:,3,0], eye_data[:,3,1]))))*0.9
ymin = abs(np.min(np.hstack((eye_data[:,4,0], eye_data[:,4,1]))))*0.9
allmin = min(xmin, ymin)
allmax = max(xmax, ymax)
return tmin, tmax, allmin, allmax
#%% calculate limits for gt plots
def calc_lims_gt(gt):
mingt = -abs(np.min(gt))*1.2
maxgt = np.max(gt)*1.2
return mingt, maxgt
#%% plot uncalibrated data
def plot_mask(mask_ind, eye_data, masked_eye_data, save_plot):
f1 = plt.figure(1, figsize=(16,9))
tmin, tmax, allmin, allmax = calc_lims_eye_data(eye_data)
start = int(mask_ind[mask_ind[:,2]==1,0])
start_mask = np.where(masked_eye_data[:,0,0] > eye_data[start,0,0])[0][0]
if start <= 0:
start = 1
else:
start = start - 10
tstart = eye_data[start,0,0]
stop = int(mask_ind[mask_ind[:,2]==np.max(mask_ind[:,3]),1])
stop_mask = np.where(masked_eye_data[:,0,0] > eye_data[stop,0,0])[0][0]
if stop > np.size(eye_data, 0):
stop = np.size(eye_data, 0)
else:
stop = stop + 10
tstop = eye_data[stop,0,0]
title_list = ['left', 'right']
for i in range(2):
plt.subplot(2,3,3*i+1)
plt.title(title_list[i])
plt.xlim(tstart, tstop)
plt.ylim(allmin, allmax)
plt.xlabel('t in s')
plt.ylabel('x in a.u.')
plt.grid(linestyle='dashed')
plt.plot(eye_data[start:stop,0,i], eye_data[start:stop,3,i], c='b')
plt.scatter(masked_eye_data[start_mask:stop_mask,0,i],
masked_eye_data[start_mask:stop_mask,3,i], c='r',marker='o')
plt.subplot(2,3,3*i+2)
plt.title(title_list[i])
plt.xlim(tstart, tstop)
plt.ylim(allmin, allmax)
plt.xlabel('t in s')
plt.ylabel('y in a.u.')
plt.grid(linestyle='dashed')
plt.plot(eye_data[start:stop,0,i], eye_data[start:stop,4,i], c='b')
plt.scatter(masked_eye_data[start_mask:stop_mask,0,i],
masked_eye_data[start_mask:stop_mask,4,i], c='r',marker='o')
plt.subplot(2,3,3*i+3)
plt.title(title_list[i])
plt.xlim(allmin, allmax)
plt.ylim(allmin, allmax)
plt.xlabel('x in a.u.')
plt.ylabel('y in a.u.')
plt.grid(linestyle='dashed')
plt.plot(eye_data[start:stop,3,i], eye_data[start:stop,4,i], c='b')
plt.scatter(masked_eye_data[start_mask:stop_mask,3,i],
masked_eye_data[start_mask:stop_mask,4,i], c='r',marker='o')
f1.show()
if save_plot == 1:
f1.savefig('Pictures\\Mask.png', dpi = 500)
#%% plot calibrated 2D grid
def plot_Grid_2D(cal_grid, gt, save_plot):
f2 = plt.figure(2, figsize=(16,9))
mingt, maxgt = calc_lims_gt(gt)
plt.title('Calibrated Grid')
plt.xlim(mingt, maxgt)
plt.ylim(mingt, maxgt)
plt.xlabel('x in °')
plt.ylabel('y in °')
plt.grid(linestyle='dashed')
plt.scatter(gt[:,0],gt[:,1], c='k', marker='o')
plt.scatter(cal_grid[:,0,0],cal_grid[:,1,0], c='b' ,marker='x')
plt.scatter(cal_grid[:,0,1],cal_grid[:,1,1], c='r', marker='+')
plt.scatter(cal_grid[:,0,2],cal_grid[:,1,2], c='g', marker='d')
plt.legend(['gt','L','R','av'])
f2.show()
if save_plot == 1:
f2.savefig('Pictures\\Grid2D.png', dpi = 500)
#%% plot calibrated 3D grid
def plot_Grid_3D(cal_grid, gt, mean_or_all, save_plot):
f3 = plt.figure(3)
ax = f3.add_subplot(111, projection='3d')
mingt, maxgt = calc_lims_gt(gt)
color_list = ['b','r','g']
marker_list = ['x','+','d']
label_list = ['left','right','average']
ax.scatter(gt[:,0],gt[:,1],gt[:,2],c='k',marker='o',label='gt')
if mean_or_all == 1:
ax.scatter(cal_grid[:,0,2],cal_grid[:,1,2],cal_grid[:,2,2],
c=color_list[2],marker=marker_list[2],label=label_list[2])
elif mean_or_all == 2:
for i in range(0,3):
ax.scatter(cal_grid[:,0,i],cal_grid[:,1,i],cal_grid[:,2,i],
c=color_list[i],marker=marker_list[i],label=label_list[i])
for i in range(np.size(gt,0)):
ax.plot([gt[i,0], cal_grid[i,0,2]],[gt[i,1], cal_grid[i,1,2]],
[gt[i,2], cal_grid[i,2,2]],c='c',linestyle=':')
plt.legend()
plt.title('Calibrated Grid')
plt.xlim(mingt, maxgt)
plt.ylim(mingt, maxgt)
ax.set_zlim(mingt, maxgt)
plt.xlabel('x in °')
plt.ylabel('y in °')
ax.set_zlabel('z in a.u.')
plt.grid(linestyle='dashed')
f3.show()
if save_plot == 1:
f3.savefig('Pictures\\Grid3D.png', dpi = 500)
#%% plot calibrated eye_data (val_eye_data)
def plot_calib(masked_val_eye_data, val_eye_data, gt, cal_grid, save_plot):
f4 = plt.figure(4, figsize=(16,9))
tmin, tmax, allmin, allmax = calc_lims_eye_data(val_eye_data)
mingt, maxgt = calc_lims_gt(gt)
title_list = ['left', 'right']
for i in range(2):
plt.subplot(2,3,3*i+1)
plt.title(title_list[i])
plt.xlim(tmin, tmax)
plt.ylim(mingt, maxgt)
plt.xlabel('t in s')
plt.ylabel('x in a.u.')
plt.grid(linestyle='dashed')
plt.plot(val_eye_data[:,0,i], val_eye_data[:,3,i], c='b')
plt.scatter(masked_val_eye_data[:,0,i], masked_val_eye_data[:,3,i], c='r',marker='o')
plt.subplot(2,3,3*i+2)
plt.title(title_list[i])
plt.xlim(tmin, tmax)
plt.ylim(mingt, maxgt)
plt.xlabel('t in s')
plt.ylabel('y in a.u.')
plt.grid(linestyle='dashed')
plt.plot(val_eye_data[:,0,i], val_eye_data[:,4,i], c='b')
plt.scatter(masked_val_eye_data[:,0,i], masked_val_eye_data[:,4,i], c='r',marker='o')
plt.subplot(2,3,3*i+3)
plt.title(title_list[i])
plt.xlim(mingt, maxgt)
plt.ylim(mingt, maxgt)
plt.xlabel('x in a.u.')
plt.ylabel('y in a.u.')
plt.grid(linestyle='dashed')
plt.plot(val_eye_data[:,3,i], val_eye_data[:,4,i], c='b')
plt.scatter(masked_val_eye_data[:,3,i], masked_val_eye_data[:,4,i], c='r',marker='o')
plt.scatter(gt[:,0],gt[:,1],c='k',marker='o')
f4.show()
if save_plot == 1:
f4.savefig('Pictures\\val_eye.png', dpi = 500)
def plot_stream(val_eye_data, gt):
plt.ion()
f5 = plt.figure(5, figsize=(8,4))
tmin, tmax, allmin, allmax = calc_lims_eye_data(val_eye_data)
mingt, maxgt = calc_lims_gt(gt)
plt.xlim(tmin, tmax)
plt.ylim(mingt, maxgt)
plt.xlabel('t in s')
plt.ylabel('x in a.u.')
x = val_eye_data[:,3,0]
y = val_eye_data[:,4,0]
ax = f5.add_subplot(111)
line1, = ax.plot(x, y, 'b-')
for time in range(np.size(x)):
line1.set_ydata(np.sin(x + time))
f5.canvas.draw()
f5.canvas.flush_events()
|
b935887e0a82cd49677e7b696a6c19d1eaa9e283
|
[
"Markdown",
"Python"
] | 11 |
Markdown
|
PeterWolf93/PupilLabs_VR_Calibration
|
5904804d5eab83805cc1ded04b9de31239b5771a
|
cad0b9a9c1717d14e65f145640d1f02915b7632a
|
refs/heads/master
|
<repo_name>dalbirsrana/wordpress-custom-theme-development<file_sep>/jazzicons-dalbir/functions.php
<?php
// Please install the following two VS Code Extensions:
// PHP Intelephense
// WordPress Snippets
if ( ! function_exists( 'jazzicons_setup' ) ) :
function jazzicons_setup() {
add_theme_support( 'automatic-feed-links' );
add_theme_support( 'post-thumbnails' );
add_theme_support( 'title-tag' );
add_theme_support( 'post-formats', array('aside', 'gallery', 'quote', 'video') );
add_theme_support( 'custom-header', array(
'height' => '400',
'width' => '1800',
'uploads' => true,
'default-image' => get_template_directory_uri() . '/img/cropped-live-02.jpg',
) );
// Tell WP how many menu
register_nav_menus( array(
'menu-main' => 'Main Menu',
'menu-footer' => 'Footer Menu',
'menu-social' => 'Social Menu',
) );
}
endif;
add_action('after_setup_theme', 'jazzicons_setup');
function jazzicons_scripts_styles(){
$rand = rand(1, 9999999999);
wp_enqueue_style('jazzicons_style', get_stylesheet_uri(), '' , $rand );
wp_enqueue_style('jazzicons_fonts', 'https://fonts.googleapis.com/css?family=Lora:400,700&display=swap' );
// ARGS: handle, src, dependencies, version, in footer (boolean) ?
wp_enqueue_script( 'jazzicons_video', get_template_directory_uri() . '/js/responsive-video.js', array(), null, true );
}
add_action('wp_enqueue_scripts', 'jazzicons_scripts_styles');
<file_sep>/jazzicons-dalbir/header.php
<?php ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?> >
<div id="page" class="page">
<header class="site-header">
<h1 class="site-name">
<a href="<?php echo home_url(); ?>">
<?php bloginfo( 'name' ); ?>
</a>
</h1>
<div class="site-description">
<?php bloginfo( 'description' ) ?>
</div>
<?php
if ( has_nav_menu( 'menu-main' ) ) :
wp_nav_menu(
array(
'theme_location' => 'menu-main',
'menu_id' => 'main-menu',
'container' => 'nav',
)
);
endif;
?>
</header>
<main class="site-main">
<file_sep>/jazzicons-dalbir/template-parts/content.php
<?php ?>
<article class="<?php post_class(); ?>">
<h2 class="entry-title">
<?php
if ( !is_single() ) :
?>
<a href="<?php the_permalink( ); ?>">
<?php the_title(); ?>
</a>
<?php
else:
the_title();
endif;
?>
</h2>
<div class="entry-meta">
<span>Posted on</span>
<span class="entry-date"><?php the_date(); ?></span>
</div>
<?php if ( !is_single() ) : ?>
<div class="entry-thumbnail">
<?php the_post_thumbnail('medium'); ?>
</div>
<?php endif ?>
<div class="entry-content">
<?php
if ( is_single() ) :
the_content();
else:
the_excerpt();
endif;
?>
</div>
<footer class="entry-footer">
<div class="entry-category">
<span>Posted in: </span>
<?php the_category(' • '); ?>
</div>
<div class="entry-tags">
<span>Tagged: </span>
<?php the_tags(' ', '• '); ?>
</div>
</footer>
</article><file_sep>/jazzicons-dalbir/sass/navigation/_navigation.scss
/* common css for all navigation */
nav {
ul {
display: flex;
flex-flow: row wrap;
justify-content: center;
list-style-type: none;
margin: 0;
padding: 0;
}
li {
flex-grow: 1;
flex-shrink: 0;
padding: 0.4rem 1rem;
margin: 1px 0;
text-align: center;
}
a {
text-decoration: none;
}
}
/* header navigation */
.site-header {
nav {
li {
border: 1px solid #ccc;
}
}
}<file_sep>/jazzicons-dalbir/footer.php
<?php ?>
</main>
<footer class="site-footer">
<?php
if ( has_nav_menu( 'menu-footer' ) ) :
wp_nav_menu( array(
'theme_location' => 'menu-footer',
'menu_id' => 'footer-menu',
'container' => 'nav',
) );
endif;
?>
<div class="site-info">Site by Dalbir, content copyright <?php echo date( 'Y' ); ?></div>
</footer>
</div>
<?php wp_footer(); ?>
</body>
</html>
|
75e56124aefa0083f312a198f439844f543e9787
|
[
"SCSS",
"PHP"
] | 5 |
SCSS
|
dalbirsrana/wordpress-custom-theme-development
|
e80ec0e878100166870894270d57c76d526cb53c
|
34dcc461a228ec6b1b532b7f28eedbcc95f9bcdd
|
refs/heads/master
|
<repo_name>Preet-Maru/ActivitiesOfNiitSem6<file_sep>/README.md
# ActivitiesOfNiitSem6
Small Activities
|
bd6463895342126fb360a4a635bd2183e5c09e26
|
[
"Markdown"
] | 1 |
Markdown
|
Preet-Maru/ActivitiesOfNiitSem6
|
0db66b9dc6dcc43be44a58c9dc594b1c217394df
|
b709315fa8daf2cfd40854a6b0755fd7b4ee6655
|
refs/heads/master
|
<file_sep># testing-github
learning github
|
2962eb44bf105049b599f4c0783c2335ca54122e
|
[
"Markdown"
] | 1 |
Markdown
|
paulcao888/testing-github
|
ce82486ce19426c4b3bc1e954717fb573a4138ca
|
9c3b6ec52479b42fbef9217e0af2e2fb5a07992c
|
refs/heads/main
|
<file_sep># -
WUT数据结构实验
|
a68583000a66f7054a56e38d3508be15830ff08f
|
[
"Markdown"
] | 1 |
Markdown
|
TOTfan/-
|
ff73675d9646fc3635086a26d7d6bc4b48ff694b
|
9ffc6b1a90c9d3b1ccb71e2eaf3ffc312fcba116
|
refs/heads/master
|
<file_sep>[The Oak Zone](https://josephmedina96.github.io/Intermediate-Project-1/index.html "Professor Oak's Realm")
|
985860dd08039e0f57cdd9c854bf45f83686b5ae
|
[
"Markdown"
] | 1 |
Markdown
|
JosephMedina96/Intermediate-Project-1
|
a1567398cb62dc17d8d1e7110fc45522910626f2
|
d0f530fa1f75283d4aff48ec4b652ea0fd0d77b1
|
refs/heads/master
|
<file_sep># sakya
Sakya institute management
|
d2649dcae3af0ab8ff8a27205b96d593ba5c015e
|
[
"Markdown"
] | 1 |
Markdown
|
thusthara/sakya
|
fc139c364ab94ceb03e3efd41a7e9a0c85fa52e9
|
daec9f3b2b2c9f9b158292e532b07b7b025ed7c1
|
refs/heads/master
|
<file_sep>================
PyConES 2017 Web
================
Web page made for PyConES 2017, made with Django with :heart:.
.. image:: https://travis-ci.org/python-spain/PyConES-2017.svg?branch=master
:target: https://travis-ci.org/python-spain/PyConES-2017
Deploy with Docker
------------------
To deploy using docker, first we've to create a ``.env`` file with the
credentials of the database, secret key, etc.
.. code-block:: bash
$ cp env.example .env
The available environment variables are:
- ``POSTGRES_PASSWORD`` Postgres database password
- ``POSTGRES_DB`` Postgres database name
- ``DJANGO_SECRET_KEY`` Django secret key
- ``DJANGO_SETTINGS_MODULE`` Django settings module (eg. ``config.settings.production``)
- ``DATABASE_URL`` Url to connect to the database (eg. ``config.settings.production``)
- ``DJANGO_ALLOWED_HOSTS`` Host names allowed, separated by commas (eg. ``localhost,2017.es.pycon.org``))
- ``DJANGO_EMAIL_HOST`` Host for SMTP server
- ``DJANGO_EMAIL_HOST_USER`` User for SMTP server
- ``DJANGO_EMAIL_HOST_PASSWORD`` Password for SMTP server
- ``DJANGO_EMAIL_PORT`` Port for SMTP server
The default values are ready to run the containers in a development machine using **production
configuration**. Then, we've have to use Docker Compose to bring it up.
.. code-block:: bash
$ docker-compose up -d
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from pycones.blog.models import Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ['id', 'title', 'created', 'status']
list_filter = ('status',)
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from django.contrib.admin import ModelAdmin
from django.utils.translation import ugettext_lazy as _
from pycones.schedules.actions import download_speakers
from pycones.schedules.models import Day, Room, SlotKind, Slot, Presentation, Track
@admin.register(Slot)
class SlotAdmin(ModelAdmin):
list_display = ("id", "day", "start", "end", "kind", "room", "order", "get_content_title")
def get_content_title(self, instance):
if instance.content:
return instance.content.get_title()
return None
get_content_title.short_description = _("Title")
@admin.register(Track)
class TrackAdmin(ModelAdmin):
list_display = ("id", "day", "name")
@admin.register(Presentation)
class PresentationAdmin(ModelAdmin):
actions = [download_speakers, ]
admin.site.register(Day)
admin.site.register(Room)
admin.site.register(SlotKind)
<file_sep>
// Controller for the speakers widget, used in the creation
// of a new proposal.
class SpeakersController {
constructor($scope) {
this.scope = $scope;
}
$onInit() {
// List of speakers
this.speakers = [];
this.speakersSerialized = "";
if (this.value !== undefined && this.value !== "None" && this.value !== "" ) {
this.speakersSerialized = this.value;
this.speakers = JSON.parse(this.value);
} else {
// Adds new speaker
this.addNewSpeaker();
}
// Watch changes on speakers
this.scope.$watch("$ctrl.speakers", (value) => {
this.serializeSpeakers();
}, true);
}
addNewSpeaker() {
this.speakers.push({name: "", email: ""});
}
deleteSpeaker(index) {
this.speakers.splice(index, 1);
}
serializeSpeakers() {
this.speakersSerialized = JSON.stringify(this.speakers);
}
}
SpeakersController.$inject = ['$scope'];
export {SpeakersController};
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from pycones.speakers.actions import download_approved_speakers
from pycones.speakers.models import Speaker
@admin.register(Speaker)
class SpeakerAdmin(admin.ModelAdmin):
list_display = ["name", "email", "created"]
search_fields = ["name"]
actions = [download_approved_speakers]
<file_sep>import angular from 'angular';
import {SpeakersComponent} from './proposals.component';
// Proposals module
const proposals = angular
.module('proposals', [])
.component('speakers', SpeakersComponent);
export default proposals;
|
46327be19442037d9056278e8cb8961ef3bf6ede
|
[
"reStructuredText",
"JavaScript",
"Python"
] | 6 |
reStructuredText
|
vterron/PyConES-2017
|
d7c885a6a51f1b171b5d354e1a9f3f4343dfeda1
|
04934e64ed893718204181064fecaf1100ce6015
|
refs/heads/master
|
<file_sep>import React from 'react';
import './assets/styles/global.css'
import ArticlePreview from './components/card';
function App() {
return (
<ArticlePreview
title="Shift the overall look and fell by adding these wonderful touches to furniture in your home"
body="Ever been in a room and felt like something was missing? Perhaps it felt slightly bare and uninviting. I've got some simple tips to help you make any room feel complete."
nameUser="<NAME>"
date="28 Jun 2020"
avatar='https://github.com/NathanaelCruz/images_resource_projects/blob/master/Images/avatar-michelle.jpg?raw=true'
facebookLink="https://www.facebook.com/"
twitterLink="https://twitter.com/"
pinterestLink="https://br.pinterest.com/"
/>
)
}
export default App;
<file_sep>## Article Preview Component
### Challenger of the FrontMentor
For use, you will need the following steps.
1. After downloading the repository, install Node Modules using the command *Npm i or npm install*
2. After installing the dependencies, due to being a TS project, you need to install JQuery Types, with the command *npm i @ types / jquery*
3. With the dependencies installed and the type of Jquery, just start the project with *npm start*.
The composition of the challenge was carried out as a component in order to be reused within the development process.
View Deploy in [Vercel](https://article-preview-component-phi-five.vercel.app/)
<file_sep>import React from 'react';
import $ from 'jquery'
import ImageForArticle from '../../assets/images/drawers.jpg'
import IconFacebook from '../../assets/images/icon-facebook.svg'
import IconTwitter from '../../assets/images/icon-twitter.svg'
import IconPinterest from '../../assets/images/icon-pinterest.svg'
import './style.css'
const animationButton = () => {
let buttonForAnimate = $(".card-article-info-perfil-btn")
buttonForAnimate.toggleClass('active')
}
const animationSocialMedia = () => {
let cardArticlePerfilSocialMedia = $(".card-article-info-perfil-social")
let widthAnimationforSocialMedia = (window.screen.width < 767) ? '100%' : '53%'
cardArticlePerfilSocialMedia.toggleClass('active-social')
if(cardArticlePerfilSocialMedia.hasClass('active-social')){
$(".card-article-info-perfil-social").animate({
width: widthAnimationforSocialMedia,
'padding-left': '2rem',
}, 1000, "linear")
} else{
$(".card-article-info-perfil-social").animate({
width: '0%',
'padding-left': '0rem',
}, 1000, "linear")
}
animationButton()
}
interface ArticlePreviewProps {
title: string,
body: string,
nameUser: string,
date: string,
avatar: string,
facebookLink: string,
twitterLink: string,
pinterestLink: string
}
const ArticlePreview: React.FunctionComponent<ArticlePreviewProps> = (props) => {
return (
<section className="card-article">
<section className="card-article-image">
<img src={ImageForArticle} alt="Imagem do Artigo"/>
</section>
<section className="card-article-info">
<section className="card-article-info-details">
<h2 className="card-article-info-details-title">
{props.title}
</h2>
<p className="card-article-info-details-body">
{props.body}
</p>
</section>
<section className="card-article-info-perfil">
<section className="card-article-info-perfil-user">
<img src={props.avatar} alt="Imagem do perfil"/>
<section className="card-article-info-perfil-user-info">
<strong className="perfil-user-name">
{props.nameUser}
</strong>
<p className="perfil-user-data">
{props.date}
</p>
</section>
</section>
<section className="card-article-info-perfil-social">
<section className="perfil-social-content">
<p className="perfil-social-content-text">
SHARE
</p>
<a href={props.facebookLink} target="_blank" rel="noopener noreferrer">
<img src={IconFacebook} alt="Ícone Facebook"/>
</a>
<a href={props.twitterLink} target="_blank" rel="noopener noreferrer">
<img src={IconTwitter} alt="Ícone Twitter"/>
</a>
<a href={props.pinterestLink} target="_blank" rel="noopener noreferrer">
<img src={IconPinterest} alt="Ícone Pinterest"/>
</a>
</section>
</section>
<button type="button" aria-label="card-article-info-perfil-btn" className="card-article-info-perfil-btn" onClick={animationSocialMedia}>
<svg xmlns="http://www.w3.org/2000/svg" width="15" height="13"><path fill="#6E8098" d="M15 6.495L8.766.014V3.88H7.441C3.33 3.88 0 7.039 0 10.936v2.049l.589-.612C2.59 10.294 5.422 9.11 8.39 9.11h.375v3.867L15 6.495z"/></svg>
</button>
</section>
</section>
</section>
)
}
export default ArticlePreview;
|
103bb70c3ec336d5a8ed8f8fff4fb4b55450426f
|
[
"Markdown",
"TSX"
] | 3 |
Markdown
|
NathanaelCruz/Article-Preview-Component
|
e439cd43f7558abd23e00a804b50be5c286f7b3e
|
d84568ad2ebd83a1ba601c530452e797dff8af78
|
refs/heads/master
|
<file_sep>package pruning
import (
"fmt"
"github.com/nknorg/nkn/v2/chain/store"
"github.com/urfave/cli"
)
func pruningAction(c *cli.Context) error {
if c.NumFlags() == 0 {
cli.ShowSubcommandHelp(c)
return nil
}
switch {
case c.Bool("currentheight"):
cs, err := store.NewLedgerStore()
if err != nil {
return err
}
_, h, err := cs.GetCurrentBlockHashFromDB()
if err != nil {
return err
}
fmt.Println(h)
case c.Bool("startheights"):
cs, err := store.NewLedgerStore()
if err != nil {
return err
}
refCountStartHeight, pruningStartHeight := cs.GetPruningStartHeight()
fmt.Println(refCountStartHeight, pruningStartHeight)
case c.Bool("pruning"):
cs, err := store.NewLedgerStore()
if err != nil {
return err
}
if c.Bool("seq") {
err := cs.SequentialPrune()
if err != nil {
return err
}
} else if c.Bool("lowmem") {
err := cs.PruneStatesLowMemory(true)
if err != nil {
return err
}
} else {
err := cs.PruneStates()
if err != nil {
return err
}
}
case c.Bool("dumpnodes"):
cs, err := store.NewLedgerStore()
if err != nil {
return err
}
err = cs.TrieTraverse()
if err != nil {
return err
}
case c.Bool("verifystate"):
cs, err := store.NewLedgerStore()
if err != nil {
return err
}
err = cs.VerifyState()
if err != nil {
return err
}
default:
cli.ShowSubcommandHelp(c)
return nil
}
return nil
}
func NewCommand() *cli.Command {
return &cli.Command{
Name: "pruning",
Usage: "state trie pruning for nknd",
Description: "state trie pruning for nknd.",
ArgsUsage: "[args]",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "currentheight",
Usage: "current block height of offline db",
},
cli.BoolFlag{
Name: "startheights",
Usage: "start heights of refcount and pruning",
},
cli.BoolFlag{
Name: "pruning",
Usage: "prune state trie",
},
cli.BoolFlag{
Name: "seq",
Usage: "prune state trie sequential mode",
},
cli.BoolFlag{
Name: "lowmem",
Usage: "prune state trie low memory mode",
},
cli.BoolFlag{
Name: "dumpnodes",
Usage: "dump nodes of trie",
},
cli.BoolFlag{
Name: "verifystate",
Usage: "verify state of ledger",
},
},
Action: pruningAction,
OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error {
return cli.NewExitError("", 1)
},
}
}
<file_sep>export default {
BENEFICIARY_TOOLTIP: '新的收益会自动转到这个地址.',
Register_ID_Txn_Fee_TOOLTIP: '注册ID时的手续费.',
Low_Fee_Txn_Size_Per_Block_TOOLTIP: '低于最小手续费的打包区块大小.',
Num_Low_Fee_Txn_Per_Block_TOOLTIP: '低于最小手续费的打包区块数量.',
Min_Txn_Fee_TOOLTIP: '打包交易收取的最小手续费.',
}
<file_sep>package debug
import (
"fmt"
"os"
"github.com/nknorg/nkn/v2/api/httpjson/client"
nknc "github.com/nknorg/nkn/v2/cmd/nknc/common"
"github.com/urfave/cli"
)
func debugAction(c *cli.Context) (err error) {
if c.NumFlags() == 0 {
cli.ShowSubcommandHelp(c)
return nil
}
level := c.Int("level")
if level != -1 {
resp, err := client.Call(nknc.Address(), "setdebuginfo", 0, map[string]interface{}{"level": level})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
nknc.FormatOutput(resp)
}
return nil
}
func NewCommand() *cli.Command {
return &cli.Command{Name: "debug",
Usage: "blockchain node debugging",
Description: "With nknc debug, you could debug blockchain node.",
ArgsUsage: "[args]",
Flags: []cli.Flag{
cli.IntFlag{
Name: "level, l",
Usage: "log level 0-6",
Value: -1,
},
},
Action: debugAction,
OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error {
nknc.PrintError(c, err, "debug")
return cli.NewExitError("", 1)
},
}
}
<file_sep>export default {
Register_ID_Txn_Fee: '注册ID费用',
Low_Fee_Txn_Size_Per_Block: '低费率区块大小',
Num_Low_Fee_Txn_Per_Block: '低费率区块数量',
Min_Txn_Fee: '最小手续费',
}
<file_sep>package name
import (
"encoding/hex"
"fmt"
"os"
api "github.com/nknorg/nkn/v2/api/common"
"github.com/nknorg/nkn/v2/api/httpjson/client"
nknc "github.com/nknorg/nkn/v2/cmd/nknc/common"
"github.com/nknorg/nkn/v2/common"
"github.com/nknorg/nkn/v2/config"
"github.com/nknorg/nkn/v2/vault"
"github.com/urfave/cli"
)
func nameAction(c *cli.Context) error {
if c.NumFlags() == 0 {
cli.ShowSubcommandHelp(c)
return nil
}
walletName := c.String("wallet")
passwd := c.String("password")
myWallet, err := vault.OpenWallet(walletName, nknc.GetPassword(passwd))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
var txnFee common.Fixed64
fee := c.String("fee")
if fee == "" {
txnFee = common.Fixed64(0)
} else {
txnFee, _ = common.StringToFixed64(fee)
}
regFeeString := c.String("regfee")
var regFee common.Fixed64
if regFeeString == "" {
regFee = common.Fixed64(0)
} else {
regFee, _ = common.StringToFixed64(regFeeString)
}
nonce := c.Uint64("nonce")
var resp []byte
switch {
case c.Bool("reg"):
name := c.String("name")
if name == "" {
fmt.Println("name is required with [--name]")
return nil
}
txn, _ := api.MakeRegisterNameTransaction(myWallet, name, nonce, regFee, txnFee)
buff, _ := txn.Marshal()
resp, err = client.Call(nknc.Address(), "sendrawtransaction", 0, map[string]interface{}{"tx": hex.EncodeToString(buff)})
case c.Bool("transfer"):
name := c.String("name")
if name == "" {
fmt.Println("name is required with [--name]")
return nil
}
to := c.String("to")
if to == "" {
fmt.Println("transfer is required with [--to]")
return nil
}
var toBytes []byte
toBytes, err = hex.DecodeString(to)
if err != nil {
return err
}
txn, _ := api.MakeTransferNameTransaction(myWallet, name, nonce, txnFee, toBytes)
buff, _ := txn.Marshal()
resp, err = client.Call(nknc.Address(), "sendrawtransaction", 0, map[string]interface{}{"tx": hex.EncodeToString(buff)})
case c.Bool("del"):
name := c.String("name")
if name == "" {
fmt.Println("name is required with [--name]")
return nil
}
txn, _ := api.MakeDeleteNameTransaction(myWallet, name, nonce, txnFee)
buff, _ := txn.Marshal()
resp, err = client.Call(nknc.Address(), "sendrawtransaction", 0, map[string]interface{}{"tx": hex.EncodeToString(buff)})
case c.Bool("get"):
name := c.String("name")
if name == "" {
fmt.Println("name is required with [--name]")
return nil
}
resp, err = client.Call(nknc.Address(), "getregistrant", 0, map[string]interface{}{"name": name})
default:
cli.ShowSubcommandHelp(c)
return nil
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
nknc.FormatOutput(resp)
return nil
}
func NewCommand() *cli.Command {
return &cli.Command{
Name: "name",
Usage: "name registration",
Description: "With nknc name, you could register name for your address.",
ArgsUsage: "[args]",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "reg, r",
Usage: "register name for your address",
},
cli.BoolFlag{
Name: "del, d",
Usage: "delete name of your address",
},
cli.BoolFlag{
Name: "get, g",
Usage: "get register name info",
},
cli.BoolFlag{
Name: "transfer, t",
Usage: "transfer name to another address",
},
cli.StringFlag{
Name: "name",
Usage: "name",
},
cli.StringFlag{
Name: "wallet, w",
Usage: "wallet name",
Value: config.Parameters.WalletFile,
},
cli.StringFlag{
Name: "password, p",
Usage: "wallet password",
},
cli.StringFlag{
Name: "fee, f",
Usage: "transaction fee",
Value: "",
},
cli.Uint64Flag{
Name: "nonce",
Usage: "nonce",
},
cli.StringFlag{
Name: "regfee",
Usage: "regfee",
},
cli.StringFlag{
Name: "to",
Usage: "transfer name to addr",
},
},
Action: nameAction,
OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error {
nknc.PrintError(c, err, "name")
return cli.NewExitError("", 1)
},
}
}
<file_sep>package service
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
nknc "github.com/nknorg/nkn/v2/cmd/nknc/common"
"github.com/nknorg/nkn/v2/util/log"
"github.com/urfave/cli"
)
const requestTimeout = 5 * time.Second
func serviceAction(c *cli.Context) error {
if c.NumFlags() == 0 {
cli.ShowSubcommandHelp(c)
return nil
}
switch {
case c.Bool("list"):
var netClient = &http.Client{
Timeout: requestTimeout,
}
resp, err := netClient.Get("https://forum.nkn.org/t/1836.json?include_raw=1")
if err != nil {
log.Errorf("GET request: %v\n", err)
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Errorf("GET response: %v\n", err)
return err
}
var out = make(map[string]interface{})
err = json.Unmarshal(body, &out)
if err != nil {
log.Errorf("Unmarshal response: %v\n", err)
return err
}
fmt.Println(out["post_stream"].(map[string]interface{})["posts"].([]interface{})[0].(map[string]interface{})["raw"])
default:
cli.ShowSubcommandHelp(c)
return nil
}
return nil
}
func NewCommand() *cli.Command {
return &cli.Command{
Name: "service",
Usage: "NKN-based service",
Description: "NKN-based service.",
ArgsUsage: "[args]",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "list, ls",
Usage: "show nkn service list",
},
},
Action: serviceAction,
OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error {
nknc.PrintError(c, err, "service")
return cli.NewExitError("", 1)
},
}
}
<file_sep>package main
import (
"fmt"
"math/rand"
"os"
"sort"
"syscall"
"time"
"github.com/nknorg/nkn/v2/cmd/nknc/asset"
"github.com/nknorg/nkn/v2/cmd/nknc/common"
"github.com/nknorg/nkn/v2/cmd/nknc/debug"
"github.com/nknorg/nkn/v2/cmd/nknc/id"
"github.com/nknorg/nkn/v2/cmd/nknc/info"
"github.com/nknorg/nkn/v2/cmd/nknc/name"
"github.com/nknorg/nkn/v2/cmd/nknc/pruning"
"github.com/nknorg/nkn/v2/cmd/nknc/pubsub"
"github.com/nknorg/nkn/v2/cmd/nknc/service"
"github.com/nknorg/nkn/v2/cmd/nknc/wallet"
"github.com/nknorg/nkn/v2/util/log"
"github.com/urfave/cli"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func main() {
err := log.Init()
if err != nil {
log.Fatal(err)
}
defer func() {
if r := recover(); r != nil {
log.Fatalf("Panic: %+v", r)
}
}()
app := cli.NewApp()
app.Name = "nknc"
app.Version = common.Version
app.HelpName = "nknc"
app.Usage = "command line tool for blockchain"
app.UsageText = "nknc [global options] command [command options] [args]"
app.HideHelp = false
app.HideVersion = false
//global options
app.Flags = []cli.Flag{
common.NewIpFlag(),
common.NewPortFlag(),
}
//commands
app.Commands = []cli.Command{
*debug.NewCommand(),
*info.NewCommand(),
*wallet.NewCommand(),
*asset.NewCommand(),
*name.NewCommand(),
*pubsub.NewCommand(),
*id.NewCommand(),
*pruning.NewCommand(),
*service.NewCommand(),
}
sort.Sort(cli.CommandsByName(app.Commands))
sort.Sort(cli.FlagsByName(app.Flags))
if err := app.Run(os.Args); err != nil {
switch err.(type) {
case syscall.Errno:
os.Exit(int(err.(syscall.Errno)))
default:
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
}
<file_sep>export default {
Register_ID_Txn_Fee: 'Register ID txn fee',
Low_Fee_Txn_Size_Per_Block: 'Low fee txn size per block',
Num_Low_Fee_Txn_Per_Block: 'Num low fee txn per block',
Min_Txn_Fee: 'Min txn fee'
}
<file_sep>package id
import (
"context"
"encoding/hex"
"fmt"
"os"
api "github.com/nknorg/nkn/v2/api/common"
"github.com/nknorg/nkn/v2/api/httpjson/client"
nknc "github.com/nknorg/nkn/v2/cmd/nknc/common"
"github.com/nknorg/nkn/v2/common"
"github.com/nknorg/nkn/v2/config"
"github.com/nknorg/nkn/v2/vault"
"github.com/urfave/cli"
)
func generateIDAction(c *cli.Context) error {
if c.NumFlags() == 0 {
cli.ShowSubcommandHelp(c)
return nil
}
pubkeyHex := c.String("pubkey")
pubkey, err := hex.DecodeString(pubkeyHex)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
walletName := c.String("wallet")
passwd := c.String("<PASSWORD>")
myWallet, err := vault.OpenWallet(walletName, nknc.GetPassword(passwd))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
var txnFee common.Fixed64
fee := c.String("fee")
if fee == "" {
txnFee = common.Fixed64(0)
} else {
txnFee, err = common.StringToFixed64(fee)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
var regFee common.Fixed64
fee = c.String("regfee")
if fee == "" {
regFee = common.Fixed64(0)
} else {
regFee, err = common.StringToFixed64(fee)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
nonce := c.Uint64("nonce")
var resp []byte
switch {
case c.Bool("genid"):
account, err := myWallet.GetDefaultAccount()
if err != nil {
return err
}
walletAddr, err := account.ProgramHash.ToAddress()
if err != nil {
return err
}
remoteNonce, height, err := client.GetNonceByAddr(nknc.Address(), walletAddr)
if err != nil {
return err
}
if nonce == 0 {
nonce = remoteNonce
}
txn, err := api.MakeGenerateIDTransaction(context.Background(), pubkey, myWallet, regFee, nonce, txnFee, height+1)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
buff, err := txn.Marshal()
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
resp, err = client.Call(nknc.Address(), "sendrawtransaction", 0, map[string]interface{}{"tx": hex.EncodeToString(buff)})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
default:
cli.ShowSubcommandHelp(c)
return nil
}
nknc.FormatOutput(resp)
return nil
}
func NewCommand() *cli.Command {
return &cli.Command{
Name: "id",
Usage: "generate id for nknd",
Description: "With nknc id, you could generate ID.",
ArgsUsage: "[args]",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "genid",
Usage: "generate id",
},
cli.StringFlag{
Name: "pubkey",
Usage: "pubkey to generate id for, leave empty for local wallet pubkey",
},
cli.StringFlag{
Name: "wallet, w",
Usage: "wallet name",
Value: config.Parameters.WalletFile,
},
cli.StringFlag{
Name: "password, p",
Usage: "wallet password",
},
cli.StringFlag{
Name: "regfee",
Usage: "registration fee",
Value: "",
},
cli.StringFlag{
Name: "fee, f",
Usage: "transaction fee",
Value: "",
},
cli.Uint64Flag{
Name: "nonce",
Usage: "nonce",
},
},
Action: generateIDAction,
OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error {
nknc.PrintError(c, err, "id")
return cli.NewExitError("", 1)
},
}
}
<file_sep>package wallet
import (
"encoding/hex"
"fmt"
"os"
"github.com/nknorg/nkn/v2/api/httpjson/client"
nknc "github.com/nknorg/nkn/v2/cmd/nknc/common"
"github.com/nknorg/nkn/v2/common"
"github.com/nknorg/nkn/v2/crypto"
"github.com/nknorg/nkn/v2/config"
"github.com/nknorg/nkn/v2/util/password"
"github.com/nknorg/nkn/v2/vault"
"github.com/urfave/cli"
)
func showAccountInfo(wallet *vault.Wallet, verbose bool) {
const format = "%-37s %s\n"
account, _ := wallet.GetDefaultAccount()
fmt.Printf(format, "Address", "Public Key")
fmt.Printf(format, "-------", "----------")
address, _ := account.ProgramHash.ToAddress()
publicKey := account.PublicKey
fmt.Printf(format, address, hex.EncodeToString(publicKey))
if verbose {
fmt.Printf("\nSecret Seed\n-----------\n%s\n", hex.EncodeToString(crypto.GetSeedFromPrivateKey(account.PrivateKey)))
}
}
func getPassword(passwd string) []byte {
var tmp []byte
var err error
if passwd != "" {
tmp = []byte(passwd)
} else {
tmp, err = password.GetPassword("")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
return tmp
}
func getConfirmedPassword(passwd string) []byte {
var tmp []byte
var err error
if passwd != "" {
tmp = []byte(passwd)
} else {
tmp, err = password.GetConfirmedPassword()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
return tmp
}
func walletAction(c *cli.Context) error {
if c.NumFlags() == 0 {
cli.ShowSubcommandHelp(c)
return nil
}
// wallet file name
name := c.String("name")
if name == "" {
return fmt.Errorf("invalid wallet name")
}
// get password from the command line or from environment variable
passwd := c.String("password")
if passwd == "" {
passwd = os.Getenv("NKN_WALLET_PASSWORD")
}
// create wallet
if c.Bool("create") {
if common.FileExisted(name) {
return fmt.Errorf("CAUTION: '%s' already exists!\n", name)
}
wallet, err := vault.NewWallet(name, getConfirmedPassword(passwd))
if err != nil {
return err
}
showAccountInfo(wallet, false)
return nil
}
var hexFmt bool
switch format := c.String("restore"); format {
case "": // Not restore mode
break
case "hex":
hexFmt = true
fallthrough
case "bin":
if common.FileExisted(name) {
return fmt.Errorf("CAUTION: '%s' already exists!\n", name)
}
key, err := password.GetPassword("Input you Secret Seed")
if err != nil {
return err
}
if hexFmt {
if key, err = hex.DecodeString(string(key)); err != nil {
return fmt.Errorf("Invalid hex. %v\n", err)
}
}
wallet, err := vault.RestoreWallet(name, getPassword(passwd), key)
if err != nil {
return err
}
fmt.Printf("Restore %s wallet to %s\n", wallet.Address, name)
return nil
default:
return fmt.Errorf("--restore [hex | bin]")
}
// list wallet info
if item := c.String("list"); item != "" {
if item != "account" && item != "balance" && item != "verbose" && item != "nonce" && item != "id" {
return fmt.Errorf("--list [account | balance | verbose | nonce | id]")
} else {
wallet, err := vault.OpenWallet(name, getPassword(passwd))
if err != nil {
return err
}
var vbs bool
switch item {
case "verbose":
vbs = true
fallthrough
case "account":
showAccountInfo(wallet, vbs)
case "balance":
account, _ := wallet.GetDefaultAccount()
address, _ := account.ProgramHash.ToAddress()
resp, err := client.Call(nknc.Address(), "getbalancebyaddr", 0, map[string]interface{}{"address": address})
if err != nil {
return err
}
nknc.FormatOutput(resp)
case "nonce":
account, _ := wallet.GetDefaultAccount()
address, _ := account.ProgramHash.ToAddress()
resp, err := client.Call(nknc.Address(), "getnoncebyaddr", 0, map[string]interface{}{"address": address})
if err != nil {
return err
}
nknc.FormatOutput(resp)
case "id":
account, _ := wallet.GetDefaultAccount()
publicKey := account.PubKey()
pk := hex.EncodeToString(publicKey)
resp, err := client.Call(nknc.Address(), "getid", 0, map[string]interface{}{"publickey": pk})
if err != nil {
return err
}
nknc.FormatOutput(resp)
}
}
return nil
}
// change password
if c.Bool("changepassword") {
fmt.Printf("Wallet File: '%s'\n", name)
passwd, err := password.GetPassword("")
if err != nil {
return err
}
wallet, err := vault.OpenWallet(name, passwd)
if err != nil {
return err
}
fmt.Println("# input new password #")
newPassword, err := password.GetConfirmedPassword()
if err != nil {
return err
}
err = wallet.ChangePassword([]byte(passwd), newPassword)
if err != nil {
return err
}
fmt.Println("password changed")
return nil
}
return nil
}
func NewCommand() *cli.Command {
return &cli.Command{
Name: "wallet",
Usage: "user wallet operation",
Description: "With nknc wallet, you could control your asset.",
ArgsUsage: "[args]",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "create, c",
Usage: "create wallet",
},
cli.StringFlag{
Name: "list, l",
Usage: "list wallet information [account, balance, verbose, nonce]",
},
cli.StringFlag{
Name: "restore, r",
Usage: "restore wallet with [hex, bin] format PrivateKey",
},
cli.BoolFlag{
Name: "changepassword",
Usage: "change wallet password",
},
cli.BoolFlag{
Name: "reset",
Usage: "reset wallet",
},
cli.StringFlag{
Name: "name, n",
Usage: "wallet name",
Value: config.Parameters.WalletFile,
},
cli.StringFlag{
Name: "password, p",
Usage: "wallet password",
},
},
Action: walletAction,
OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error {
nknc.PrintError(c, err, "wallet")
return cli.NewExitError("", 1)
},
}
}
<file_sep>module github.com/nknorg/nkn/v2
go 1.13
require (
github.com/gin-contrib/sessions v0.0.0-20190512062852-3cb4c4f2d615
github.com/gin-gonic/gin v1.4.0
github.com/go-acme/lego/v3 v3.8.0
github.com/golang/protobuf v1.5.0
github.com/gorilla/securecookie v1.1.1
github.com/gorilla/websocket v1.4.0
github.com/howeyc/gopass v0.0.0-20170109162249-bf9dde6d0d2c
github.com/itchyny/base58-go v0.0.5
github.com/jpillora/backoff v1.0.0 // indirect
github.com/nknorg/consequential v0.0.0-20190823093205-a45aff4a218a
github.com/nknorg/nnet v0.0.0-20200521002812-357d1b11179f
github.com/nknorg/portmapper v0.0.0-20200114081049-1c03cdccc283
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/pbnjay/memory v0.0.0-20190104145345-974d429e7ae4
github.com/pborman/uuid v1.2.0
github.com/rdegges/go-ipify v0.0.0-20150526035502-2d94a6a86c40
github.com/syndtr/goleveldb v1.0.1-0.20200815110645-5c35d600f0ca
github.com/urfave/cli v1.22.1
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9
golang.org/x/time v0.0.0-20191024005414-555d28b269f0
)
<file_sep>export default {
BENEFICIARY_TOOLTIP: 'New amount will auto transfer to this address.',
Register_ID_Txn_Fee_TOOLTIP: 'Fee when registering ID.',
Low_Fee_Txn_Size_Per_Block_TOOLTIP: 'Packing block size below the minimum handling fee.',
Num_Low_Fee_Txn_Per_Block_TOOLTIP: 'The number of packed blocks below the minimum handling fee.',
Min_Txn_Fee_TOOLTIP: 'Minimum handling fee for packaged transactions.',
}
<file_sep>package node
import (
"encoding/json"
"errors"
"sync"
"time"
"github.com/golang/protobuf/proto"
"github.com/nknorg/nkn/v2/pb"
nnetnode "github.com/nknorg/nnet/node"
)
type RemoteNode struct {
*Node
localNode *LocalNode
nnetNode *nnetnode.RemoteNode
sharedKey *[sharedKeySize]byte
sync.RWMutex
height uint32
lastUpdateTime time.Time
}
func (remoteNode *RemoteNode) MarshalJSON() ([]byte, error) {
var out map[string]interface{}
buf, err := json.Marshal(remoteNode.Node)
if err != nil {
return nil, err
}
err = json.Unmarshal(buf, &out)
if err != nil {
return nil, err
}
out["height"] = remoteNode.GetHeight()
out["isOutbound"] = remoteNode.nnetNode.IsOutbound
out["roundTripTime"] = remoteNode.nnetNode.GetRoundTripTime() / time.Millisecond
return json.Marshal(out)
}
func NewRemoteNode(localNode *LocalNode, nnetNode *nnetnode.RemoteNode) (*RemoteNode, error) {
nodeData := &pb.NodeData{}
err := proto.Unmarshal(nnetNode.Node.Data, nodeData)
if err != nil {
return nil, err
}
node, err := NewNode(nnetNode.Node.Node, nodeData)
if err != nil {
return nil, err
}
if len(node.PublicKey) == 0 {
return nil, errors.New("nil public key")
}
sharedKey, err := localNode.computeSharedKey(node.PublicKey)
if err != nil {
return nil, err
}
remoteNode := &RemoteNode{
Node: node,
localNode: localNode,
nnetNode: nnetNode,
sharedKey: sharedKey,
}
return remoteNode, nil
}
func (remoteNode *RemoteNode) GetHeight() uint32 {
remoteNode.RLock()
defer remoteNode.RUnlock()
return remoteNode.height
}
func (remoteNode *RemoteNode) SetHeight(height uint32) {
remoteNode.Lock()
defer remoteNode.Unlock()
remoteNode.height = height
}
func (remoteNode *RemoteNode) GetLastUpdateTime() time.Time {
remoteNode.RLock()
defer remoteNode.RUnlock()
return remoteNode.lastUpdateTime
}
func (remoteNode *RemoteNode) SetLastUpdateTime(lastUpdateTime time.Time) {
remoteNode.Lock()
defer remoteNode.Unlock()
remoteNode.lastUpdateTime = lastUpdateTime
}
func (remoteNode *RemoteNode) CloseConn() {
remoteNode.nnetNode.Stop(nil)
}
func (remoteNode *RemoteNode) String() string {
return remoteNode.nnetNode.String()
}
<file_sep>package por
import (
"bytes"
"crypto/sha256"
"fmt"
"math/big"
"github.com/nknorg/nkn/v2/config"
"github.com/nknorg/nkn/v2/crypto"
"github.com/nknorg/nkn/v2/pb"
"github.com/nknorg/nnet/overlay/chord"
)
func VerifySigChain(sc *pb.SigChain, height uint32) error {
if err := VerifySigChainMeta(sc, height); err != nil {
return err
}
if err := VerifySigChainPath(sc, height); err != nil {
return err
}
if err := VerifySigChainSignatures(sc); err != nil {
return err
}
return nil
}
func VerifySigChainMeta(sc *pb.SigChain, height uint32) error {
if sc.Length() < 3 {
return fmt.Errorf("sigchain should have at least 3 elements, but only has %d", sc.Length())
}
if len(sc.Elems[0].Id) > 0 && !bytes.Equal(sc.SrcId, sc.Elems[0].Id) {
return fmt.Errorf("sigchain has wrong src id")
}
if !sc.IsComplete() {
return fmt.Errorf("sigchain is not complete")
}
if bytes.Equal(sc.Elems[0].Id, sc.Elems[1].Id) {
return fmt.Errorf("src and first relayer has the same ID")
}
if bytes.Equal(sc.Elems[sc.Length()-1].Id, sc.Elems[sc.Length()-2].Id) {
return fmt.Errorf("dest and last relayer has the same ID")
}
if len(sc.Elems[sc.Length()-1].NextPubkey) > 0 {
return fmt.Errorf("next pubkey in last sigchain elem should be empty")
}
if sc.Elems[0].Mining {
return fmt.Errorf("first sigchain element should have mining set to false")
}
if sc.Elems[sc.Length()-1].Mining {
return fmt.Errorf("last sigchain element should have mining set to false")
}
for i, e := range sc.Elems {
if i == 0 || i == sc.Length()-1 {
if len(e.Vrf) > 0 {
return fmt.Errorf("sigchain elem %d vrf should be empty", i)
}
if len(e.Proof) > 0 {
return fmt.Errorf("sigchain elem %d proof should be empty", i)
}
} else {
if len(e.Vrf) == 0 {
return fmt.Errorf("sigchain elem %d vrf should not be empty", i)
}
if len(e.Proof) == 0 {
return fmt.Errorf("sigchain elem %d proof should not be empty", i)
}
}
if !config.AllowSigChainHashSignature.GetValueAtHeight(height) {
if e.SigAlgo != pb.SigAlgo_SIGNATURE {
return fmt.Errorf("sigchain elem %d sig algo should be %v", i, pb.SigAlgo_SIGNATURE)
}
}
}
return nil
}
// VerifySigChainSignatures returns whether all signatures in sigchain are valid
func VerifySigChainSignatures(sc *pb.SigChain) error {
prevNextPubkey := sc.SrcPubkey
buff := bytes.NewBuffer(nil)
err := sc.SerializationMetadata(buff)
if err != nil {
return err
}
metaHash := sha256.Sum256(buff.Bytes())
prevHash := metaHash[:]
for i, e := range sc.Elems {
err := crypto.CheckPublicKey(prevNextPubkey)
if err != nil {
return fmt.Errorf("invalid pubkey %x: %v", prevNextPubkey, err)
}
if sc.IsComplete() && i == sc.Length()-1 {
h := sha256.Sum256(prevHash)
prevHash = h[:]
}
hash, err := e.Hash(prevHash)
if err != nil {
return err
}
switch e.SigAlgo {
case pb.SigAlgo_SIGNATURE:
err = crypto.Verify(prevNextPubkey, hash, e.Signature)
if err != nil {
return fmt.Errorf("signature %x is invalid: %v", e.Signature, err)
}
case pb.SigAlgo_HASH:
if !bytes.Equal(e.Signature, hash) {
return fmt.Errorf("signature %x is different from expected value %x", e.Signature, hash[:])
}
default:
return fmt.Errorf("unknown SigAlgo %v", e.SigAlgo)
}
if len(e.Vrf) > 0 {
ok := crypto.VerifyVrf(prevNextPubkey, sc.BlockHash, e.Vrf, e.Proof)
if !ok {
return fmt.Errorf("invalid vrf or proof")
}
prevHash = hash
} else {
prevHash = e.Signature
}
prevNextPubkey = e.NextPubkey
if sc.IsComplete() && i == sc.Length()-2 && len(e.NextPubkey) == 0 {
prevNextPubkey = sc.DestPubkey
}
}
return nil
}
func VerifySigChainPath(sc *pb.SigChain, height uint32) error {
var t big.Int
lastNodeID := sc.Elems[sc.Length()-2].Id
prevDistance := chord.Distance(sc.Elems[1].Id, lastNodeID, config.NodeIDBytes*8)
for i := 2; i < sc.Length()-1; i++ {
dist := chord.Distance(sc.Elems[i].Id, lastNodeID, config.NodeIDBytes*8)
if dist.Cmp(prevDistance) == 0 {
return fmt.Errorf("relayer %d and %d has the same ID", i-1, i)
}
(&t).Mul(dist, big.NewInt(2))
if t.Cmp(prevDistance) > 0 {
return fmt.Errorf("signature chain path is invalid")
}
prevDistance = dist
}
if config.SigChainVerifyFingerTableRange.GetValueAtHeight(height) {
// only needs to verify node to node hop, and no need to check last node to
// node hop because it could be successor
for i := 1; i < sc.Length()-3; i++ {
dist := chord.Distance(sc.Elems[i].Id, sc.DestId, config.NodeIDBytes*8)
fingerIdx := dist.BitLen() - 1
if fingerIdx < 0 {
return fmt.Errorf("invalid finger table index")
}
fingerStartID := chord.PowerOffset(sc.Elems[i].Id, uint32(fingerIdx), config.NodeIDBytes*8)
fingerEndID := chord.PowerOffset(sc.Elems[i].Id, uint32(fingerIdx+1), config.NodeIDBytes*8)
if !chord.BetweenLeftIncl(fingerStartID, fingerEndID, sc.Elems[sc.Length()-2].Id) && fingerIdx > 1 {
fingerStartID = chord.PowerOffset(sc.Elems[i].Id, uint32(fingerIdx-1), config.NodeIDBytes*8)
fingerEndID = chord.PowerOffset(sc.Elems[i].Id, uint32(fingerIdx), config.NodeIDBytes*8)
}
if !chord.BetweenLeftIncl(fingerStartID, fingerEndID, sc.Elems[i+1].Id) {
return fmt.Errorf("next hop is not in finger table range")
}
}
}
return nil
}
<file_sep>package common
import (
"bytes"
"encoding/json"
"fmt"
"net"
"os"
"strconv"
"github.com/nknorg/nkn/v2/config"
"github.com/nknorg/nkn/v2/util/password"
"github.com/urfave/cli"
)
var (
Ip string
Port string
Version string
)
func NewIpFlag() cli.Flag {
return cli.StringFlag{
Name: "ip",
Usage: "node's ip address",
Value: "localhost",
Destination: &Ip,
}
}
func NewPortFlag() cli.Flag {
return cli.StringFlag{
Name: "port",
Usage: "node's RPC port",
Value: strconv.Itoa(int(config.Parameters.HttpJsonPort)),
Destination: &Port,
}
}
func Address() string {
return "http://" + net.JoinHostPort(Ip, Port)
}
func PrintError(c *cli.Context, err error, cmd string) {
fmt.Println("Incorrect Usage:", err)
fmt.Println("")
cli.ShowCommandHelp(c, cmd)
}
func FormatOutput(o []byte) error {
var out bytes.Buffer
err := json.Indent(&out, o, "", "\t")
if err != nil {
return err
}
out.Write([]byte("\n"))
_, err = out.WriteTo(os.Stdout)
return err
}
func GetPassword(passwd string) []byte {
var tmp []byte
var err error
if passwd != "" {
tmp = []byte(passwd)
} else {
tmp, err = password.GetPassword("")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
return tmp
}
<file_sep>package info
import (
"fmt"
"os"
"github.com/nknorg/nkn/v2/api/httpjson/client"
nknc "github.com/nknorg/nkn/v2/cmd/nknc/common"
"github.com/urfave/cli"
)
func infoAction(c *cli.Context) (err error) {
if c.NumFlags() == 0 {
cli.ShowSubcommandHelp(c)
return nil
}
blockhash := c.String("blockhash")
txhash := c.String("txhash")
latestblockhash := c.Bool("latestblockhash")
height := c.Int("height")
blockcount := c.Bool("blockcount")
connections := c.Bool("connections")
neighbor := c.Bool("neighbor")
ring := c.Bool("ring")
state := c.Bool("state")
version := c.Bool("nodeversion")
balance := c.String("balance")
nonce := c.String("nonce")
id := c.String("id")
pretty := c.Bool("pretty")
var resp []byte
var output [][]byte
if height != -1 {
resp, err = client.Call(nknc.Address(), "getblock", 0, map[string]interface{}{"height": height})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
if pretty {
if p, err := PrettyPrinter(resp).PrettyBlock(); err == nil {
resp = p // replace resp if pretty success
} else {
fmt.Fprintln(os.Stderr, "Fallback to original resp due to PrettyPrint fail: ", err)
}
}
output = append(output, resp)
}
if c.String("blockhash") != "" {
resp, err = client.Call(nknc.Address(), "getblock", 0, map[string]interface{}{"hash": blockhash})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
if pretty {
if p, err := PrettyPrinter(resp).PrettyBlock(); err == nil {
resp = p // replace resp if pretty success
} else {
fmt.Fprintln(os.Stderr, "Fallback to original resp due to PrettyPrint fail: ", err)
}
}
output = append(output, resp)
}
if latestblockhash {
resp, err = client.Call(nknc.Address(), "getlatestblockhash", 0, map[string]interface{}{})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
output = append(output, resp)
}
if blockcount {
resp, err = client.Call(nknc.Address(), "getblockcount", 0, map[string]interface{}{})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
output = append(output, resp)
}
if connections {
resp, err = client.Call(nknc.Address(), "getconnectioncount", 0, map[string]interface{}{})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
output = append(output, resp)
}
if neighbor {
resp, err := client.Call(nknc.Address(), "getneighbor", 0, map[string]interface{}{})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
output = append(output, resp)
}
if ring {
resp, err := client.Call(nknc.Address(), "getchordringinfo", 0, map[string]interface{}{})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
output = append(output, resp)
}
if state {
resp, err := client.Call(nknc.Address(), "getnodestate", 0, map[string]interface{}{})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
output = append(output, resp)
}
if txhash != "" {
resp, err = client.Call(nknc.Address(), "gettransaction", 0, map[string]interface{}{"hash": txhash})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
if pretty {
if p, err := PrettyPrinter(resp).PrettyTxn(); err == nil {
resp = p // replace resp if pretty success
} else {
fmt.Fprintln(os.Stderr, "Output origin resp due to PrettyPrint fail: ", err)
}
}
output = append(output, resp)
}
if version {
resp, err = client.Call(nknc.Address(), "getversion", 0, map[string]interface{}{})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
output = append(output, resp)
}
if balance != "" {
resp, err := client.Call(nknc.Address(), "getbalancebyaddr", 0, map[string]interface{}{"address": balance})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
output = append(output, resp)
}
if nonce != "" {
resp, err := client.Call(nknc.Address(), "getnoncebyaddr", 0, map[string]interface{}{"address": nonce})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
output = append(output, resp)
}
if id != "" {
resp, err := client.Call(nknc.Address(), "getid", 0, map[string]interface{}{"publickey": id})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
output = append(output, resp)
}
for _, v := range output {
nknc.FormatOutput(v)
}
return nil
}
func NewCommand() *cli.Command {
return &cli.Command{
Name: "info",
Usage: "show blockchain information",
Description: "With nknc info, you could look up blocks, transactions, etc.",
ArgsUsage: "[args]",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "pretty, p",
Usage: "pretty print",
},
cli.StringFlag{
Name: "blockhash, b",
Usage: "hash for querying a block",
},
cli.StringFlag{
Name: "txhash, t",
Usage: "hash for querying a transaction",
},
cli.BoolFlag{
Name: "latestblockhash",
Usage: "latest block hash",
},
cli.IntFlag{
Name: "height",
Usage: "block height for querying a block",
Value: -1,
},
cli.BoolFlag{
Name: "blockcount, c",
Usage: "block number in blockchain",
},
cli.BoolFlag{
Name: "connections",
Usage: "connection count",
},
cli.BoolFlag{
Name: "neighbor",
Usage: "neighbor information of current node",
},
cli.BoolFlag{
Name: "ring",
Usage: "chord ring information of current node",
},
cli.BoolFlag{
Name: "state, s",
Usage: "current node state",
},
cli.BoolFlag{
Name: "nodeversion, v",
Usage: "version of connected remote node",
},
cli.StringFlag{
Name: "balance",
Usage: "balance of a address",
},
cli.StringFlag{
Name: "nonce",
Usage: "nonce of a address",
},
cli.StringFlag{
Name: "id",
Usage: "id from publickey",
},
},
Action: infoAction,
OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error {
nknc.PrintError(c, err, "info")
return cli.NewExitError("", 1)
},
}
}
<file_sep>package info
import (
"encoding/hex"
"encoding/json"
"fmt"
"github.com/golang/protobuf/proto"
"github.com/nknorg/nkn/v2/pb"
)
type PrettyPrinter []byte
func TxnUnmarshal(m map[string]interface{}) (interface{}, error) {
typ, ok := m["txType"]
if !ok {
return nil, fmt.Errorf("No such key [txType]")
}
pbHexStr, ok := m["payloadData"]
if !ok {
return m, nil
}
buf, err := hex.DecodeString(pbHexStr.(string))
if err != nil {
return nil, err
}
switch typ {
case pb.PayloadType_name[int32(pb.PayloadType_SIG_CHAIN_TXN_TYPE)]:
sigChainTxn := &pb.SigChainTxn{}
if err = proto.Unmarshal(buf, sigChainTxn); err == nil { // bin to pb struct of SigChainTxnType txn
m["payloadData"] = sigChainTxn.ToMap()
}
case pb.PayloadType_name[int32(pb.PayloadType_COINBASE_TYPE)]:
coinBaseTxn := &pb.Coinbase{}
if err = proto.Unmarshal(buf, coinBaseTxn); err == nil { // bin to pb struct of Coinbase txn
m["payloadData"] = coinBaseTxn.ToMap()
}
case pb.PayloadType_name[int32(pb.PayloadType_TRANSFER_ASSET_TYPE)]:
trans := &pb.TransferAsset{}
if err = proto.Unmarshal(buf, trans); err == nil { // bin to pb struct of Coinbase txn
m["payloadData"] = trans.ToMap()
}
case pb.PayloadType_name[int32(pb.PayloadType_GENERATE_ID_TYPE)]:
genID := &pb.GenerateID{}
if err = proto.Unmarshal(buf, genID); err == nil { // bin to pb struct of Coinbase txn
m["payloadData"] = genID.ToMap()
}
case pb.PayloadType_name[int32(pb.PayloadType_REGISTER_NAME_TYPE)]:
regName := &pb.RegisterName{}
if err = proto.Unmarshal(buf, regName); err == nil { // bin to pb struct of Coinbase txn
m["payloadData"] = regName.ToMap()
}
case pb.PayloadType_name[int32(pb.PayloadType_SUBSCRIBE_TYPE)]:
sub := &pb.Subscribe{}
if err = proto.Unmarshal(buf, sub); err == nil { // bin to pb struct of Coinbase txn
m["payloadData"] = sub.ToMap()
}
case pb.PayloadType_name[int32(pb.PayloadType_UNSUBSCRIBE_TYPE)]:
sub := &pb.Unsubscribe{}
if err = proto.Unmarshal(buf, sub); err == nil { // bin to pb struct of Coinbase txn
m["payloadData"] = sub.ToMap()
}
case pb.PayloadType_name[int32(pb.PayloadType_NANO_PAY_TYPE)]:
pay := &pb.NanoPay{}
if err = proto.Unmarshal(buf, pay); err == nil { // bin to pb struct of Coinbase txn
m["payloadData"] = pay.ToMap()
}
case pb.PayloadType_name[int32(pb.PayloadType_TRANSFER_NAME_TYPE)]:
fallthrough //TODO
case pb.PayloadType_name[int32(pb.PayloadType_DELETE_NAME_TYPE)]:
fallthrough //TODO
case pb.PayloadType_name[int32(pb.PayloadType_ISSUE_ASSET_TYPE)]:
fallthrough //TODO
default:
return nil, fmt.Errorf("Unknow txType[%s] for pretty print", typ)
}
return m, nil
}
func (resp PrettyPrinter) PrettyTxn() ([]byte, error) {
m := map[string]interface{}{}
err := json.Unmarshal(resp, &m)
if err != nil {
return nil, err
}
v, ok := m["result"]
if !ok {
return nil, fmt.Errorf("response No such key [result]")
}
if m["result"], err = TxnUnmarshal(v.(map[string]interface{})); err != nil {
return nil, err
}
return json.Marshal(m)
}
func (resp PrettyPrinter) PrettyBlock() ([]byte, error) {
m := map[string]interface{}{}
err := json.Unmarshal(resp, &m)
if err != nil {
return nil, err
}
ret, ok := m["result"]
if !ok {
return nil, fmt.Errorf("response No such key [result]")
}
txns, ok := ret.(map[string]interface{})["transactions"]
if !ok {
return nil, fmt.Errorf("result No such key [transactions]")
}
lst := make([]interface{}, 0)
for _, t := range txns.([]interface{}) {
if m, err := TxnUnmarshal(t.(map[string]interface{})); err == nil {
lst = append(lst, m)
} else {
lst = append(lst, t) // append origin txn if TxnUnmarshal fail
}
}
m["transactions"] = lst
return json.Marshal(m)
}
<file_sep>package asset
import (
"encoding/hex"
"fmt"
"os"
api "github.com/nknorg/nkn/v2/api/common"
"github.com/nknorg/nkn/v2/api/httpjson/client"
nknc "github.com/nknorg/nkn/v2/cmd/nknc/common"
"github.com/nknorg/nkn/v2/common"
"github.com/nknorg/nkn/v2/config"
"github.com/nknorg/nkn/v2/util/password"
"github.com/nknorg/nkn/v2/vault"
"github.com/urfave/cli"
)
const (
RANDBYTELEN = 4
)
func parseAddress(c *cli.Context) common.Uint160 {
if address := c.String("to"); address != "" {
pg, err := common.ToScriptHash(address)
if err != nil {
fmt.Println("invalid receiver address")
os.Exit(1)
}
return pg
}
fmt.Println("missing flag [--to]")
os.Exit(1)
return common.EmptyUint160
}
func assetAction(c *cli.Context) error {
if c.NumFlags() == 0 {
cli.ShowSubcommandHelp(c)
return nil
}
value := c.String("value")
if value == "" {
fmt.Println("asset amount is required with [--value]")
return nil
}
var txnFee common.Fixed64
fee := c.String("fee")
var err error
if fee == "" {
txnFee = common.Fixed64(0)
} else {
txnFee, err = common.StringToFixed64(fee)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
}
nonce := c.Uint64("nonce")
var resp []byte
switch {
case c.Bool("issue"):
walletName := c.String("wallet")
passwd := c.String("<PASSWORD>")
myWallet, err := vault.OpenWallet(walletName, getPassword(passwd))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
name := c.String("name")
if name == "" {
fmt.Println("asset name is required with [--name]")
return nil
}
symbol := c.String("symbol")
if name == "" {
fmt.Println("asset symbol is required with [--symbol]")
return nil
}
totalSupply, err := common.StringToFixed64(value)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
precision := uint32(c.Uint("precision"))
if precision > config.MaxAssetPrecision {
err := fmt.Errorf("precision is larger than %v", config.MaxAssetPrecision)
fmt.Fprintln(os.Stderr, err)
return err
}
txn, err := api.MakeIssueAssetTransaction(myWallet, name, symbol, totalSupply, precision, nonce, txnFee)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
buff, err := txn.Marshal()
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
resp, err = client.Call(nknc.Address(), "sendrawtransaction", 0, map[string]interface{}{"tx": hex.EncodeToString(buff)})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
case c.Bool("transfer"):
walletName := c.String("wallet")
passwd := c.String("<PASSWORD>")
myWallet, err := vault.OpenWallet(walletName, getPassword(passwd))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
receipt := parseAddress(c)
amount, err := common.StringToFixed64(value)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
if nonce == 0 {
remoteNonce, _, err := client.GetNonceByAddr(nknc.Address(), myWallet.Address)
if err != nil {
return err
}
nonce = remoteNonce
}
txn, err := api.MakeTransferTransaction(myWallet, receipt, nonce, amount, txnFee)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
buff, err := txn.Marshal()
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
resp, err = client.Call(nknc.Address(), "sendrawtransaction", 0, map[string]interface{}{"tx": hex.EncodeToString(buff)})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
default:
cli.ShowSubcommandHelp(c)
return nil
}
nknc.FormatOutput(resp)
return nil
}
func NewCommand() *cli.Command {
return &cli.Command{
Name: "asset",
Usage: "asset registration, issuance and transfer",
Description: "With nknc asset, you could control assert through transaction.",
ArgsUsage: "[args]",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "issue, i",
Usage: "issue asset",
},
cli.BoolFlag{
Name: "transfer, t",
Usage: "transfer asset",
},
cli.StringFlag{
Name: "wallet, w",
Usage: "wallet name",
Value: config.Parameters.WalletFile,
},
cli.StringFlag{
Name: "password, p",
Usage: "wallet password",
},
cli.StringFlag{
Name: "to",
Usage: "asset to whom",
},
cli.StringFlag{
Name: "value, v",
Usage: "asset amount in transfer asset or totalSupply in inssue assset",
Value: "",
},
cli.StringFlag{
Name: "fee, f",
Usage: "transaction fee",
Value: "",
},
cli.Uint64Flag{
Name: "nonce",
Usage: "nonce",
},
cli.StringFlag{
Name: "name",
Usage: "asset name",
},
cli.StringFlag{
Name: "symbol",
Usage: "asset symbol",
},
cli.UintFlag{
Name: "precision",
Usage: "asset precision",
},
},
Action: assetAction,
OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error {
nknc.PrintError(c, err, "asset")
return cli.NewExitError("", 1)
},
}
}
func getPassword(passwd string) []byte {
var tmp []byte
var err error
if passwd != "" {
tmp = []byte(passwd)
} else {
tmp, err = password.GetPassword("")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
return tmp
}
|
8177b5a229efb372d02a1d2fed8f59b214320f12
|
[
"Go Module",
"JavaScript",
"Go"
] | 18 |
Go Module
|
NKNetwork/nkn-core
|
191442ddc60f36d4a40a4b4f29fc6947caf542ad
|
bc515198b9b71f5d1e4f228c0af00c161f6a7c62
|
refs/heads/master
|
<repo_name>SpartacusIn21/SourceCodeControl<file_sep>/FuncModule/CPlusPlus/ELFhash.cpp
/**
* 著名ELF hash算法
*
*
* */
#include <iostream>
#include <string>
using namespace std;
unsigned int ELFHash(char *key)
{
unsigned int hash = 0;
unsigned int g = 0;
while (*key)
{
hash = (hash << 4) + (*key++);//hash左移4位,把当前字符ASCII存入hash低四位。
g=hash&0xf0000000L;
if (g)
{
//如果最高的四位不为0,则说明字符多余7个,现在正在存第7个字符,如果不处理,再加下一个字符时,第一个字符会被移出,因此要有如下处理。
//该处理,如果最高位为0,就会仅仅影响5-8位,否则会影响5-31位,因为C语言使用的算数移位
//因为1-4位刚刚存储了新加入到字符,所以不能>>28
hash ^= (g>> 24);
//上面这行代码并不会对X有影响,本身X和hash的高4位相同,下面这行代码&~即对28-31(高4位)位清零。
hash &= ~g;
}
}
//返回一个符号位为0的数,即丢弃最高位,以免函数外产生影响。(我们可以考虑,如果只有字符,符号位不可能为负)
return hash;
}
int main(){
string a="abc",b="12rfs";
cout << "hash(" << a << ")" << ELFHash((char*)a.c_str()) << endl << "hash(" << b << ")" << ELFHash((char*)b.c_str()) << endl;
return 0;
}
<file_sep>/FuncModule/CPlusPlus/algorithm_1.cpp
/*
@que:田忌赛马,每人的马数量为奇数,任何一匹马的速度都不相同;请写出一个方法,判断在某一组输入的情况下,田忌有没有可能赢。比如田忌马的速度分别为(30,37,38),齐王马的速度分别为(31,35,41)
@author:yangchun,chen
@date:3/26/2018
@iqiyi,shanghai
*/
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int arr1[] = {32,22,13};
int arr2[] = {23,25,78};
vector<int>v1(arr1,arr1+3);
vector<int>v2(arr2,arr2+3);
bool tianjisaima(vector<int>& v1/*田忌*/, vector<int>& v2/*齐王*/){
std::sort(v1.begin(),v1.end(),greater<int>());
std::sort(v2.begin(),v2.end(),greater<int>());
}
int main(){
//对田忌和齐王的马都按从大到小排序
tianjisaima(v1,v2);
for(auto &i:v1){
cout << i << " ";
}
cout << endl;
for(auto &i:v2){
cout << i << " ";
}
cout << endl;
//遍历两个vector,当田忌的速度大于齐王的,就统计加1,然后往右移动一个位置,否则只移动齐王的马的位置,直到所有的遍历结束
int count = 0;
int i=0,j=0;
while(i<v1.size() && j<v2.size()){
if(v1[i]<v2[j]){
j++;
}
else{
i++;
j++;
count++;
}
}
cout << "count:" << count << endl;
if(count >= (v1.size()/2+1)){
cout << "great!" << endl;
}
else{
cout << "ops!" << endl;
}
}
<file_sep>/FuncModule/CPlusPlus/Interview.cpp
来源:伯乐在线 - 王建敏
链接:http://blog.jobbole.com/52144/
以下是在编程面试中排名前 10 的算法相关的概念,我会通过一些简单的例子来阐述这些概念。由于完全掌握这些概念需要更多的努力,因此这份列表只是作为一个介绍。本文将从Java的角度看问题,包含下面的这些概念:
1. 字符串
2. 链表
3. 树
4. 图
5. 排序
6. 递归 vs. 迭代
7. 动态规划
8. 位操作
9. 概率问题
10. 排列组合
1. 字符串
如果IDE没有代码自动补全功能,所以你应该记住下面的这些方法。
toCharArray() // 获得字符串对应的char数组
Arrays.sort() // 数组排序
Arrays.toString(char[] a) // 数组转成字符串
charAt(int x) // 获得某个索引处的字符
length() // 字符串长度
length // 数组大小
2. 链表
在Java中,链表的实现非常简单,每个节点Node都有一个值val和指向下个节点的链接next。
class Node {
int val;
Node next;
Node(int x) {
val = x;
next = null;
}
}
链表两个著名的应用是栈Stack和队列Queue。
栈:
class Stack{
Node top;
public Node peek(){
if(top != null){
return top;
}
return null;
}
public Node pop(){
if(top == null){
return null;
}else{
Node temp = new Node(top.val);
top = top.next;
return temp;
}
}
public void push(Node n){
if(n != null){
n.next = top;
top = n;
}
}
}
队列:
class Queue{
Node first, last;
public void enqueue(Node n){
if(first == null){
first = n;
last = first;
}else{
last.next = n;
last = n;
}
}
public Node dequeue(){
if(first == null){
return null;
}else{
Node temp = new Node(first.val);
first = first.next;
if(last == temp) last = first;
return temp;
}
}
}
3. 树
这里的树通常是指二叉树,每个节点都包含一个左孩子节点和右孩子节点,像下面这样:
class TreeNode{
int value;
TreeNode left;
TreeNode right;
}
下面是与树相关的一些概念:
平衡 vs. 非平衡:平衡二叉树中,每个节点的左右子树的深度相差至多为1(1或0)。
满二叉树(Full Binary Tree):除叶子节点以为的每个节点都有两个孩子。
完美二叉树(Perfect Binary Tree):是具有下列性质的满二叉树:所有的叶子节点都有相同的深度或处在同一层次,且每个父节点都必须有两个孩子。
完全二叉树(Complete Binary Tree):二叉树中,可能除了最后一个,每一层都被完全填满,且所有节点都必须尽可能想左靠。
译者注:完美二叉树也隐约称为完全二叉树。完美二叉树的一个例子是一个人在给定深度的祖先图,因为每个人都一定有两个生父母。完全二叉树可以看成是可以有若干额外向左靠的叶子节点的完美二叉树。疑问:完美二叉树和满二叉树的区别?(参考:http://xlinux.nist.gov/dads/HTML/perfectBinaryTree.html)
4. 图
图相关的问题主要集中在深度优先搜索(depth first search)和广度优先搜索(breath first search)。
下面是一个简单的图广度优先搜索的实现。
1) 定义GraphNode
class GraphNode{
int val;
GraphNode next;
GraphNode[] neighbors;
boolean visited;
GraphNode(int x) {
val = x;
}
GraphNode(int x, GraphNode[] n){
val = x;
neighbors = n;
}
public String toString(){
return "value: "+ this.val;
}
}
2) 定义一个队列Queue
class Queue{
GraphNode first, last;
public void enqueue(GraphNode n){
if(first == null){
first = n;
last = first;
}else{
last.next = n;
last = n;
}
}
public GraphNode dequeue(){
if(first == null){
return null;
}else{
GraphNode temp = new GraphNode(first.val, first.neighbors);
first = first.next;
return temp;
}
}
}
3) 用队列Queue实现广度优先搜索
public class GraphTest {
public static void main(String[] args) {
GraphNode n1 = new GraphNode(1);
GraphNode n2 = new GraphNode(2);
GraphNode n3 = new GraphNode(3);
GraphNode n4 = new GraphNode(4);
GraphNode n5 = new GraphNode(5);
n1.neighbors = new GraphNode[]{n2,n3,n5};
n2.neighbors = new GraphNode[]{n1,n4};
n3.neighbors = new GraphNode[]{n1,n4,n5};
n4.neighbors = new GraphNode[]{n2,n3,n5};
n5.neighbors = new GraphNode[]{n1,n3,n4};
breathFirstSearch(n1, 5);
}
public static void breathFirstSearch(GraphNode root, int x){
if(root.val == x)
System.out.println("find in root");
Queue queue = new Queue();
root.visited = true;
queue.enqueue(root);
while(queue.first != null){
GraphNode c = (GraphNode) queue.dequeue();
for(GraphNode n: c.neighbors){
if(!n.visited){
System.out.print(n + " ");
n.visited = true;
if(n.val == x)
System.out.println("Find "+n);
queue.enqueue(n);
}
}
}
}
}
5. 排序
下面是不同排序算法的时间复杂度,你可以去wiki看一下这些算法的基本思想。
另外,这里有一些实现/演示:
《视觉直观感受 7 种常用的排序算法》
《视频: 6 分钟演示 15 种排序算法》
6. 递归 vs. 迭代
对程序员来说,递归应该是一个与生俱来的思想(a built-in thought),可以通过一个简单的例子来说明。
问题: 有n步台阶,一次只能上1步或2步,共有多少种走法。
步骤1:找到走完前n步台阶和前n-1步台阶之间的关系。
为了走完n步台阶,只有两种方法:从n-1步台阶爬1步走到或从n-2步台阶处爬2步走到。如果f(n)是爬到第n步台阶的方法数,那么f(n) = f(n-1) + f(n-2)。
f(0) = 0;
f(1) = 1;
步骤2: 确保开始条件是正确的。
public static int f(int n){
if(n <= 2) return n;
int x = f(n-1) + f(n-2);
return x;
}
递归方法的时间复杂度是n的指数级,因为有很多冗余的计算,如下:
f(5)
f(4) + f(3)
f(3) + f(2) + f(2) + f(1)
f(2) + f(1) + f(1) + f(0) + f(1) + f(0) + f(1)
f(1) + f(0) + f(1) + f(1) + f(0) + f(1) + f(0) + f(1)
直接的想法是将递归转换为迭代:
public static int f(int n) {
if (n <= 2){
return n;
}
int first = 1, second = 2;
int third = 0;
for (int i = 3; i <= n; i++) {
third = first + second;
first = second;
second = third;
}
return third;
}
对这个例子而言,迭代花费的时间更少,你可能也想看看Recursion vs Iteration。
7. 动态规划
动态规划是解决下面这些性质类问题的技术:
一个问题可以通过更小子问题的解决方法来解决(译者注:即问题的最优解包含了其子问题的最优解,也就是最优子结构性质)。
有些子问题的解可能需要计算多次(译者注:也就是子问题重叠性质)。
子问题的解存储在一张表格里,这样每个子问题只用计算一次。
需要额外的空间以节省时间。
爬台阶问题完全符合上面的四条性质,因此可以用动态规划法来解决。
public static int[] A = new int[100];
public static int f3(int n) {
if (n <= 2)
A[n]= n;
if(A[n] > 0)
return A[n];
else
A[n] = f3(n-1) + f3(n-2);//store results so only calculate once!
return A[n];
}
8. 位操作
位操作符:
或 与 亦或 左移 右移 非
1|0=1 1&0=0 1^0=1 0010<<2=1000 1100>>2=0011 ~1=0
获得给定数字n的第i位:( i 从 0 计数,并从右边开始)
public static boolean getBit(int num, int i){
int result = num & (1<<i);
if(result == 0){
return false;
}else{
return true;
}
例如,获得数字10的第2位:
i=1, n=10
1<<1= 10
1010&10=10
10 is not 0, so return true;
9. 概率问题
解决概率相关的问题通常需要很好的规划了解问题(formatting the problem),这里刚好有一个这类问题的简单例子:
一个房间里有50个人,那么至少有两个人生日相同的概率是多少?(忽略闰年的事实,也就是一年365天)
计算某些事情的概率很多时候都可以转换成先计算其相对面。在这个例子里,我们可以计算所有人生日都互不相同的概率,也就是:365/365 * 364/365 * 363/365 * ... * (365-49)/365,这样至少两个人生日相同的概率就是1 – 这个值。
public static double caculateProbability(int n){
double x = 1;
for(int i=0; i<n; i++){
x *= (365.0-i)/365.0;
}
double pro = Math.round((1-x) * 100);
return pro/100;
}
calculateProbability(50) = 0.97
10. 排列组合
组合和排列的区别在于次序是否关键。<file_sep>/FuncModule/CPlusPlus/MSOnlineTest/MSOnlineTest/main.cpp
#include <iostream>
#include<string>
using namespace std;
extern int Ques1(void);
extern int Ques2(void);
int main()
{
Ques1();
Ques2();
return 0;
}<file_sep>/README.md
# SourceCodeManagerWindows
Source Code Manager software fow windows system, this is a UI software developed by python tcl/tk!
Main functions of this software is to save code and find code more conveniently!
<file_sep>/FuncModule/CPlusPlus/BinaryTreeRightSideView.cpp
/*
FileName: BinaryTreeRightSizeView.cpp
Create Time: 2015/09/04
Modify Time:
Author: <NAME>
Owner: <NAME>
Place: 上海交通大学闵行校区微电子楼301室
Reference: https://leetcode.com/problems/binary-tree-right-side-view/
Description: (1)使用层次遍历算法输出从右边往左看到的二叉树的结点值;
*/
/*
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <---
/ \
2 3 <---
\ \
5 4 <---
You should return [1, 3, 4].
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
//两种方法思想类似,只是实现稍微不同
//方法1
vector<int> rightSideView(TreeNode* root) {//BFS算法,层次遍历
vector<int> ret;//用来存储输出结果
if(!root)return ret;
queue<TreeNode*>mQ;//新建队列
mQ.push(root);//入队列
while(!mQ.empty()){//当队列不为空时
ret.push_back(mQ.back()->val);//将队列中最后一个元素push_back到vector中,因为最后一个节点是始终是该层中从右边能看到的那个元素,这是由后面的遍历决定的
for(int i=mQ.size();i>0;i--){
TreeNode *tn=mQ.front();
mQ.pop();
if(tn->left)mQ.push(tn->left);//先让左子树入队,再让右子树入队,可保证队列中最后一个元素是满足要求的
if(tn->right)mQ.push(tn->right);
}
}
return ret;
}
//方法2(参考PrintNodeByLevel)
vector<int> rightSideView(TreeNode* root)
{
vector<int> ret;//用来存储输出结果
if(root == NULL)
return ret;
vector<TreeNode*> vec;
vec.push_back(root);
int cur = 0;
int last = 1;
while(cur < vec.size())//整个BT的Level层循环
{
last = vec.size();
while(cur < last)//当前Level层的各个节点循环
{
cout << vec[cur]->val << " ";
if(vec[cur]->left)
vec.push_back(vec[cur]->left);
if(vec[cur]->right)
vec.push_back(vec[cur]->right);
cur++;
}
ret.push_back(vec[cur-1]->val);
cout << endl;//输出一行后换行
}
return ret;
}
};<file_sep>/FuncModule/CPlusPlus/MSOnlineTest/Preliminary2/Ques2.cpp
/*
题3
描述
Given a sequence {an}, how many non-empty sub-sequence of it is a prefix of fibonacci sequence.
A sub-sequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
The fibonacci sequence is defined as below:
F1 = 1, F2 = 1
Fn = Fn-1 + Fn-2, n>=3
输入
One line with an integer n.
Second line with n integers, indicating the sequence {an}.
For 30% of the data, n<=10.
For 60% of the data, n<=1000.
For 100% of the data, n<=1000000, 0<=ai<=100000.
输出
One line with an integer, indicating the answer modulo 1,000,000,007.
样例提示
The 7 sub-sequences are:
{a2}
{a3}
{a2, a3}
{a2, a3, a4}
{a2, a3, a5}
{a2, a3, a4, a6}
{a2, a3, a5, a6}
样例输入
6
2 1 1 2 2 3
样例输出
7
*/
//
#include <iostream>
#include<string>
using namespace std;
int count = 0;//统计子集数目
bool isFib(int *Array,int len)
{
if(len <= 0)
{
return false;
}
else if(len == 1 && Array[0] == 1)
{
return true;
}
else if(len == 2 && Array[0] == 1 && Array[1] == 1)
{
return true;
}
else
{
for(int i = 2; i < len ; i++)
{
if(Array[i] != Array[i-1] + Array[i-2] || Array[i] == 0)
return false;
}
return true;
}
}
void trail(int a[],short int b[],int k,int n)
{
int j;
if (k<n)
{
trail(a,b,k+1,n);
b[k]=1-b[k];
trail(a,b,k+1,n);
}
else
{
int temp[10000] = {0};
int tempcount = 0;
for (j=0;j<n;j++)
{
if (b[j])
{
temp[tempcount] = b[j];
tempcount++;
}
}
if(isFib(temp, tempcount))//如果满足要求
{
count++;
}
}
}
int Ques2(void)
{
int n = 0;
cin >> n;//输入n
int *Fibonacci = new int[n];
short int b[10000] = {0};
int IndexF1 = 0,IndexF2=0;//用于记录数列的前两个位置
int temp = 0;
while(temp < n)
{
cin >> Fibonacci[temp];
temp ++;
}
trail(Fibonacci,b,0,n);
cout << count / 3 << endl;
return 0;
}
<file_sep>/FuncModule/CPlusPlus/TopK.cpp
/*
@ques:Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4] and k = 2, return 5.
@url:https://leetcode.com/problems/kth-largest-element-in-an-array/description/
@author:yangchun,chen
@date:3/29/2018
@iqiyi,shanghai
*/
class Solution {
public:
//一次快速排序,选取中间位置pos,pos左边的都比pos小,pos右边的都比pos大,根据这个特性如果pos跟k相等,就代表k值找到了
int QuickSelect(vector<int>& nums, int low, int high){
int index;
index = nums[low];
while(low < high){
while(low < high && nums[high] <= index){//如果是Top K小,改成nums[high] >= index
high--;
}
if(low < high){
nums[low++] = nums[high];
}
while(low < high && nums[low] > index){//如果是Top K小,改成nums[low] < index
low++;
}
if(low < high){
nums[high--] = nums[low];
}
nums[low] = index;
}
return low;
}
//判断k的位置跟当前快排选择的part的位置是否一致,不一致再递归调用
int kth(vector<int> &nums, int k, int low, int high){
int part = QuickSelect(nums,low,high);
if (part == k)
return nums[part];//如果是Top K元素值,返回nums[0:part]
else if(part+1 > k)
return kth(nums,k,low,part-1);
else
return kth(nums,k,part+1,high);
}
int findKthLargest(vector<int>& nums, int k) {
return kth(nums,k-1,0,nums.size()-1);//k-1是因为元素从0开始
}
};
<file_sep>/Project/CPlusPlus/RFCard_Operate_ReadMissile/RFCard_Operate_ReadMissile/ReflectiveCard.h
#pragma once
#if (defined(WIN32))
#include "rfm2g_windows.h"
#endif
#include "rfm2g_api.h"
#include <iostream>
using namespace std;
void RFM_Break();
//#define DEBUG_MissStruct80Bytes //弹道结构体为80Bytes
#define DEBUG_MissStruct520Bytes //弹道结构体为520Bytes
#ifdef DEBUG_MissStruct80Bytes //弹道结构体为80Bytes
struct MissilePosInfo//弹道坐标位置信息结构体,占用80Bytes,得修改为占用520Bytes的结构体格式
{
float CurrentTime;//弹道位置对应方位向时刻
float Position[3];//弹道坐标位置
float Velocity[3];//导弹在该弹道位置处三个速度分量
float Acceleration[3];//导弹在该弹道位置处三个加速度分量
float theta;
float psi;
float gamma;
float sOmegaX1;
float sOmegaY1;
float sOmegaZ1;
float sTheta;
float sSigma;
float sAlpha;
int counter;//当前弹道时刻的方位点数
};
#elif defined DEBUG_MissStruct520Bytes //弹道结构体为520Bytes
struct MissilePosInfo//弹道坐标位置信息结构体,占用80Bytes,得修改为占用520Bytes的结构体格式
{
float CurrentTime;//弹道位置对应方位向时刻
float Position[3];//弹道坐标位置
float Velocity[3];//导弹在该弹道位置处三个速度分量
float Acceleration[3];//导弹在该弹道位置处三个加速度分量
float theta;
float psi;
float gamma;
float sOmegaX1;
float sOmegaY1;
float sOmegaZ1;
float sTheta;
float sSigma;
float sAlpha;
float uiWaveWid; // 波门
float uiApcHight; // 预定成像高度,short占用两个字节,int占用4个字节
short Rsvd[214]; // 保留字
short usDataFlag; // 参数标志字
short usDataValid; // 数据有效标志
short counter; //当前弹道时刻的方位点数// 参数更新计数
short usSumCheck; // 参数校验
};
#else
printf("Debug Macro is wrong!\n");
#endif
class RFM_Card_Operate{
private:
RFM2G_BOOL byteSwap; /*获取大小端设置状态,为RFM2G_TRUE或RFM2G_FALSE*/
STDRFM2GCALL result_ByteSwap; /*大小端设置返回值*/
RFM2GEVENTINFO EventInfo_Receive; /* Info about received interrupts */
UINT OFFSET_WRT = 0x4000;//反射内存卡写地址——默认为0x3000
UINT OFFSET_RD = 0x3000;//反射内存卡读地址——默认为0x4000
protected:
public:
//反射内存卡公用参数变量
RFM2G_INT32 numDevice;
RFM2G_NODE OhterNodeID; /* OhterNodeID*/
char device[40]; /* Name of PCI RFM2G device to use */
RFM2GHANDLE Handle = 0;//反射内存卡句柄,非常重要
RFM2GCONFIG config; /*获取RFM2g配置结构*/
//反射内存卡公用函数
RFM_Card_Operate(RFM2G_INT32 numDevice_Para, RFM2G_NODE OhterNodeID_Para) :numDevice(numDevice_Para), OhterNodeID(OhterNodeID_Para){};
int RFM_Card_Init(rfm2gEventType EventType);//反射内存卡初始化
RFM2G_STATUS RFM_Card_EnableEvent(rfm2gEventType EventType);//Enable中断
RFM2G_STATUS RFM_Card_DisableEvent();//Disable中断
RFM2G_STATUS WaitForEvent();
RFM2G_STATUS RFM_Write_Missle(struct MissilePosInfo outbuffer,rfm2gEventType EventType);
RFM2G_STATUS RFM_Read_Missle(struct MissilePosInfo &inbuffer);
int StructCMP(struct MissilePosInfo Para1, struct MissilePosInfo Para2);//对比结构体大小
~RFM_Card_Operate();
};
<file_sep>/FuncModule/CPlusPlus/ACMCoder/SortInputString.cpp
/*
FileName: BinaryTree.cpp
Create Time: 2015/09/26
Modify Time:
Author: <NAME>
Owner: <NAME>
Place: 上海交通大学闵行校区微电子楼301室
Reference: http://acm.acmcoder.com/showproblem.php?pid=2000
Description:
*/
/*
Problem Description
输入三个字符后,按各字符的ASCII码从小到大的顺序输出这三个字符。
Input
输入数据有多组,每组占一行,有三个字符组成,之间无空格。
Output
对于每组输入数据,输出一行,字符中间用一个空格分开。
Sample Input
qwe
asd
zxc
Sample Output
e q w
a d s
c x z
*/
#include<iostream>
#include<cmath>
#include <iomanip>
using namespace std;
int SortInputString()
{
char Str[1000][3] = {0};
int count = 0;
while(cin>>Str[count])
{
for(int i = 0; i < 3; i++)
for(int j = 1; j < 3-i; j++)
{
if(Str[count][j] < Str[count][j-1])
{
Str[count][j] = Str[count][j] ^ Str[count][j-1];
Str[count][j-1] = Str[count][j] ^ Str[count][j-1];
Str[count][j] = Str[count][j] ^ Str[count][j-1];
}
}
count++;
}
for(int i = 0; i < count; i++)
{
cout << Str[i][0] << " " << Str[i][1] << " " << Str[i][2] << endl;
}
return 0;
}<file_sep>/FuncModule/CPlusPlus/MovingWay/main.cpp
/*
FileName: MovingWay
Create Time: 2015/09/16
Modify Time:
Author: <NAME>
Owner: <NAME>
Place: 上海交通大学闵行校区微电子楼301室
Reference:
Description: (1)华为机考题,大意是输入一个n*n的矩形char字符,其中'B'表示起点,'H'表示终点,'-'表示该路可通,'#'表示该路不通,对于输入的矩形字符判断从'B'到'H'是否存在路径;
(2)两点之间路径是否存在;
*/
/*
示例:
1.比如输入 B###
#---
---#
H---
则从B到H之间不通,输出'N'
2.比如输入 B-
-H
则从B到H之间通,输出'Y'
*/
#include<iostream>
#include<map>
using namespace std;
int R=0, C=0;
int endx,endy;
bool HaveRoad(char Map_Temp[400][400], int startx,int starty)//往Map_Temp相应位置写'r'表示已经读取过该位置
{
if(startx < 0 || startx >= R || starty < 0 || starty >= C)//当超出界限时返回false
{
return false;
}
else if( startx == endx && starty == endy)//表示找到相应的路径,返回true
{
return true;
}
else if((Map_Temp[startx+1][starty] == '-' || Map_Temp[startx+1][starty] == 'H') && Map_Temp[startx+1][starty] != 'r')//下一个为'-'或者'H'表示该路可走,但是不能等于'r',等于'r'表示该路径已经走过了,再走就会死循环
{
Map_Temp[startx+1][starty] = 'r';
return HaveRoad(Map_Temp, startx+1, starty);
}
else if((Map_Temp[startx][starty+1] == '-' || Map_Temp[startx][starty+1] == 'H') && Map_Temp[startx][starty+1] != 'r')
{
Map_Temp[startx][starty+1] = 'r';
return HaveRoad(Map_Temp, startx, starty+1);
}
else if((Map_Temp[startx-1][starty] == '-' || Map_Temp[startx-1][starty] == 'H') && Map_Temp[startx-1][starty] != 'r')
{
Map_Temp[startx-1][starty] = 'r';
return HaveRoad(Map_Temp, startx-1, starty);
}
else if((Map_Temp[startx][starty-1] == '-' || Map_Temp[startx][starty-1] == 'H') && Map_Temp[startx][starty-1] != 'r')
{
Map_Temp[startx][starty-1] = 'r';
return HaveRoad(Map_Temp, startx, starty-1);
}
else
{
return false;
}
}
int main()
{
int i,j;
char Map_Temp[400][400] = {0};
int startx,starty;
cin >> R;
cin >> C;
for(i = 0; i < R; i++)
{
cin >> Map_Temp[i];
}
//find B and H
for(i = 0; i < R; i++)
for(j = 0; j < C; j++)
{
if(Map_Temp[i][j] == 'B')
{
startx = i;
starty = j;
}
else if(Map_Temp[i][j] == 'H')
{
endx = i;
endy = j;
}
}
bool result = HaveRoad(Map_Temp, startx, starty);
if(result)
cout << "Y" << endl;
else
cout << "N" << endl;
return 0;
}<file_sep>/FuncModule/CPlusPlus/ACMCoder/TwoPointDis.cpp
/*
FileName: BinaryTree.cpp
Create Time: 2015/09/26
Modify Time:
Author: <NAME>
Owner: <NAME>
Place: 上海交通大学闵行校区微电子楼301室
Reference: http://acm.acmcoder.com/showproblem.php?pid=2001
Description:
*/
/*
Problem Description
输入两点坐标(X1,Y1),(X2,Y2),计算并输出两点间的距离。
Input
输入数据有多组,每组占一行,由4个实数组成,分别表示x1,y1,x2,y2,数据之间用空格隔开。
Output
对于每组输入数据,输出一行,结果保留两位小数。
Sample Input
0 0 0 1
0 1 1 0
Sample Output
1.00
1.41
*/
#include<iostream>
#include<cmath>
#include <iomanip>
using namespace std;
int TwoPointDis()
{
double x1,y1,x2,y2;
double Result[1000] = {0};
int count = 0;
while(cin>>x1>>y1>>x2>>y2)
{
Result[count++] = sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
}
for(int i = 0; i < count; i++)
cout<< fixed << setprecision(2) << Result[i] << endl;
return 0;
}<file_sep>/FuncModule/CPlusPlus/ListSorting/ListSorting/MergeSorting.cpp
/*
FileName: BubbleSorting.h
Create Time: 2015/09/04
Modify Time:
Author: <NAME>
Owner: <NAME>
Place: 上海交通大学闵行校区微电子楼301室
Reference: 《程序员面试宝典》——13.2.9 如何进行单链表排序
Description: (1)单链表的归并排序算法;
*/
#include<iostream>
#include"MergeSorting.h"
using namespace std;
void Merge(SqList SR, SqList &TR, int i, int m, int n)
{
int j,k;
for(j = m+1,k=i; i<=m&&j<=n; ++k)
{
if(SR.r[i] <= TR.r[j])
{
TR.r[k] = SR.r[i++];
}
else
{
TR.r[k] = SR.r[j++];
}
}
while(i <= m)
TR.r[k++] = SR.r[i++];
while(j <=n)
TR.r[k++] = SR.r[j++];
}
void MSort(SqList SR, SqList &TR1, int s, int t)
{
int m;
SqList TR2;
if(s == t)//这里输入有两个SqList是为了把其中一个用来当做数组存储变量
TR1.r[s] = SR.r[t];
else
{
m = (s+t)/2;
MSort(SR, TR2, s, m);
MSort(SR, TR2, m+1, t);
Merge(TR2, TR1, s, m, t);
}
}
void MergeSort(SqList &L)
{
MSort(L, L ,1, L.length);
}<file_sep>/FuncModule/CPlusPlus/MSOnlineTest/Preliminary1/Ques1.cpp
/*
题1
描述
Given a circle on a two-dimentional plane.
Output the integral point in or on the boundary of the circle which has the largest distance from the center.
输入
One line with three floats which are all accurate to three decimal places, indicating the coordinates of the center x, y and the radius r.
For 80% of the data: |x|,|y|<=1000, 1<=|r|<=1000
For 100% of the data: |x|,|y|<=100000, 1<=|r|<=100000
输出
One line with two integers separated by one space, indicating the answer.
If there are multiple answers, print the one with the largest x-coordinate.
If there are still multiple answers, print the one with the largest y-coordinate.
样例输入
1.000 1.000 5.000
样例输出
6 1
/*
Soure:http://hihocoder.com/contest/msbop2015round2a/problem/1
Date:4-25-2015
Author:Yangchun, Chen
*/
/*#include<stdio.h>
#include<iostream>
#include <string>
#include<cstdlib>
#include<vector>
#include<algorithm>
#include <math.h>
#include <algorithm>
using namespace std;
int main(void){
int count = 0;//count用于统计找到的点数
float MaxDis = 0;//用于统计满足条件的最远的距离
float x0 = 0, y0 =0, R = 0;//x0,y0,R分别为圆心点和半径
cin >> x0 >> y0 >> R;
int xMax = int(x0), yMax = int(y0);
//处理模块1
for(int x = floor(x0-R); x <= ceil(x0); x++)//x循环
{
int tempY = ceil(y0+sqrt(R*R-(x-x0)*(x-x0)));
for(int y = floor(x+y0-(x0-R)); y <= tempY; y++)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) <= R*R)//判断是否在圆内(包括边界)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) > MaxDis)
{
MaxDis = (x-x0)*(x-x0) + (y-y0)*(y-y0);
xMax = x;
yMax = y;
}
else if((x-x0)*(x-x0) + (y-y0)*(y-y0) == MaxDis)
{
if(x>xMax)
{
xMax = x;
yMax = y;
}
else if(y > yMax)
{
xMax = x;
yMax = y;
}
}
}
}
}
//处理模块2
for(int x = floor(x0); x <= ceil(x0+R); x++)//x循环
{
int tempY = ceil(y0+sqrt(R*R-(x-x0)*(x-x0)));
for(int y = floor(-x+x0+y0+R); y <= tempY; y++)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) <= R*R)//判断是否在圆内(包括边界)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) > MaxDis)
{
MaxDis = (x-x0)*(x-x0) + (y-y0)*(y-y0);
xMax = x;
yMax = y;
}
else if((x-x0)*(x-x0) + (y-y0)*(y-y0) == MaxDis)
{
if(x>xMax)
{
xMax = x;
yMax = y;
}
else if(y > yMax)
{
xMax = x;
yMax = y;
}
}
}
}
}
//处理模块3
for(int x = floor(x0-R); x <= ceil(x0); x++)//x循环
{
int tempY = floor(y0-sqrt(R*R-(x-x0)*(x-x0)));
for(int y = tempY; y <= ceil(-x+x0+y0-R); y++)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) <= R*R)//判断是否在圆内(包括边界)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) > MaxDis)
{
MaxDis = (x-x0)*(x-x0) + (y-y0)*(y-y0);
xMax = x;
yMax = y;
}
else if((x-x0)*(x-x0) + (y-y0)*(y-y0) == MaxDis)
{
if(x>xMax)
{
xMax = x;
yMax = y;
}
else if(y > yMax)
{
xMax = x;
yMax = y;
}
}
}
}
}
//处理模块4
for(int x = floor(x0); x <= ceil(x0+R); x++)//x循环
{
int tempY = floor(y0-sqrt(R*R-(x-x0)*(x-x0)));
for(int y = tempY; y <= ceil(x-x0+y0-R); y++)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) <= R*R)//判断是否在圆内(包括边界)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) > MaxDis)
{
MaxDis = (x-x0)*(x-x0) + (y-y0)*(y-y0);
xMax = x;
yMax = y;
}
else if((x-x0)*(x-x0) + (y-y0)*(y-y0) == MaxDis)
{
if(x>xMax)
{
xMax = x;
yMax = y;
}
else if(y > yMax)
{
xMax = x;
yMax = y;
}
}
}
}
}
cout << xMax << " " << yMax << endl;
return 0;
}*/
/*
#include<stdio.h>
#include<iostream>
#include <string>
#include<cstdlib>
#include<vector>
#include<algorithm>
#include <math.h>
#include <algorithm>
using namespace std;
int main(void){
int count = 0;//count用于统计找到的点数
float MaxDis = 0;//用于统计满足条件的最远的距离
float x0 = 0, y0 =0, R = 0;//x0,y0,R分别为圆心点和半径
cin >> x0 >> y0 >> R;
int xMax = int(x0), yMax = int(y0);
//处理模块1
for(int x = floor(x0-R); x <= ceil(x0); x++)//x循环
{
for(int y = floor(x+y0-(x0-R)); y <= ceil(y0+R); y++)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) <= R*R)//判断是否在圆内(包括边界)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) > MaxDis)
{
MaxDis = (x-x0)*(x-x0) + (y-y0)*(y-y0);
xMax = x;
yMax = y;
}
else if((x-x0)*(x-x0) + (y-y0)*(y-y0) == MaxDis)
{
if(x>xMax)
{
xMax = x;
yMax = y;
}
else if(y > yMax)
{
xMax = x;
yMax = y;
}
}
}
}
}
//处理模块2
for(int x = floor(x0); x <= ceil(x0+R); x++)//x循环
{
for(int y = floor(-x+x0+y0+R); y <= ceil(y0+R); y++)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) <= R*R)//判断是否在圆内(包括边界)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) > MaxDis)
{
MaxDis = (x-x0)*(x-x0) + (y-y0)*(y-y0);
xMax = x;
yMax = y;
}
else if((x-x0)*(x-x0) + (y-y0)*(y-y0) == MaxDis)
{
if(x>xMax)
{
xMax = x;
yMax = y;
}
else if(y > yMax)
{
xMax = x;
yMax = y;
}
}
}
}
}
//处理模块3
for(int x = floor(x0-R); x <= ceil(x0); x++)//x循环
{
for(int y = floor(y0-R); y <= ceil(-x+x0+y0-R); y++)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) <= R*R)//判断是否在圆内(包括边界)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) > MaxDis)
{
MaxDis = (x-x0)*(x-x0) + (y-y0)*(y-y0);
xMax = x;
yMax = y;
}
else if((x-x0)*(x-x0) + (y-y0)*(y-y0) == MaxDis)
{
if(x>xMax)
{
xMax = x;
yMax = y;
}
else if(y > yMax)
{
xMax = x;
yMax = y;
}
}
}
}
}
//处理模块4
for(int x = floor(x0); x <= ceil(x0+R); x++)//x循环
{
for(int y = floor(y0-R); y <= ceil(x-x0+y0-R); y++)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) <= R*R)//判断是否在圆内(包括边界)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) > MaxDis)
{
MaxDis = (x-x0)*(x-x0) + (y-y0)*(y-y0);
xMax = x;
yMax = y;
}
else if((x-x0)*(x-x0) + (y-y0)*(y-y0) == MaxDis)
{
if(x>xMax)
{
xMax = x;
yMax = y;
}
else if(y > yMax)
{
xMax = x;
yMax = y;
}
}
}
}
}
cout << xMax << " " << yMax << endl;
return 0;
}
*/
/*
#include<stdio.h>
#include<iostream>
#include <string>
#include<cstdlib>
#include<vector>
#include<algorithm>
#include <math.h>
#include <algorithm>
using namespace std;
int main(void){
int count = 0;//count用于统计找到的点数
float MaxDis = 0;//用于统计满足条件的最远的距离
float x0 = 0, y0 =0, R = 0;//x0,y0,R分别为圆心点和半径
cin >> x0 >> y0 >> R;
int xMax = int(x0), yMax = int(y0);
//处理模块1
for(int x = floor(x0-R); x <= ceil(x0); x++)//x循环
{
for(int y = floor(x+y0-(x0-R)); y <= ceil(y0+R); y++)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) < R*R)//判断是否在圆内(包括边界)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) > MaxDis)
{
MaxDis = (x-x0)*(x-x0) + (y-y0)*(y-y0);
xMax = x;
yMax = y;
}
}
else if(R*R - (x-x0)*(x-x0) - (y-y0)*(y-y0) > 0.001)
{
if(x>xMax)
{
xMax = x;
yMax = y;
}
else if(y > yMax)
{
xMax = x;
yMax = y;
}
}
}
}
//处理模块2
for(int x = floor(x0); x <= ceil(x0+R); x++)//x循环
{
for(int y = floor(-x+x0+y0+R); y <= ceil(y0+R); y++)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) < R*R)//判断是否在圆内(包括边界)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) > MaxDis)
{
MaxDis = (x-x0)*(x-x0) + (y-y0)*(y-y0);
xMax = x;
yMax = y;
}
}
else if(R*R - (x-x0)*(x-x0) - (y-y0)*(y-y0) > 0.001)
{
if(x>xMax)
{
xMax = x;
yMax = y;
}
else if(y > yMax)
{
xMax = x;
yMax = y;
}
}
}
}
//处理模块3
for(int x = floor(x0-R); x <= ceil(x0); x++)//x循环
{
for(int y = floor(y0-R); y <= ceil(-x+x0+y0-R); y++)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) < R*R)//判断是否在圆内(包括边界)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) > MaxDis)
{
MaxDis = (x-x0)*(x-x0) + (y-y0)*(y-y0);
xMax = x;
yMax = y;
}
}
else if(R*R - (x-x0)*(x-x0) - (y-y0)*(y-y0) > 0.001)
{
if(x>xMax)
{
xMax = x;
yMax = y;
}
else if(y > yMax)
{
xMax = x;
yMax = y;
}
}
}
}
//处理模块4
for(int x = floor(x0); x <= ceil(x0+R); x++)//x循环
{
for(int y = floor(y0-R); y <= ceil(x-x0+y0-R); y++)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) < R*R)//判断是否在圆内(包括边界)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) > MaxDis)
{
MaxDis = (x-x0)*(x-x0) + (y-y0)*(y-y0);
xMax = x;
yMax = y;
}
}
else if(R*R - (x-x0)*(x-x0) - (y-y0)*(y-y0) > 0.001)
{
if(x>xMax)
{
xMax = x;
yMax = y;
}
else if(y > yMax)
{
xMax = x;
yMax = y;
}
}
}
}
cout << xMax << " " << yMax << endl;
return 0;
}
*/
#include <iostream>
#include<string>
using namespace std;
int Ques1(void){
int count = 0;//count用于统计找到的点数
float MaxDis = 0;//用于统计满足条件的最远的距离
float x0 = 0, y0 =0, R = 0;//x0,y0,R分别为圆心点和半径
int xMax = 0, yMax = 0;
int x = 0, y =0;
//cin >> x0 >> y0 >> R;
scanf("%f %f %f", &x0, &y0, &R);
xMax = (x0);
yMax = (y0);
//处理模块1
for(x = floor(x0-R); x <= ceil(x0); x++)//x循环
{
for(y = floor(x+y0-(x0-R)); y <= ceil(y0+R); y++)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) <= R*R)//判断是否在圆内(包括边界)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) > MaxDis)
{
MaxDis = (x-x0)*(x-x0) + (y-y0)*(y-y0);
xMax = x;
yMax = y;
}
else if((x-x0)*(x-x0) + (y-y0)*(y-y0) == MaxDis && x>xMax)
{
xMax = x;
yMax = y;
}
else if((x-x0)*(x-x0) + (y-y0)*(y-y0) == MaxDis && y > yMax)
{
xMax = x;
yMax = y;
}
}
}
}
//处理模块2
for(x = floor(x0); x <= ceil(x0+R); x++)//x循环
{
for(y = floor(-x+x0+y0+R); y <= ceil(y0+R); y++)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) <= R*R)//判断是否在圆内(包括边界)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) > MaxDis)
{
MaxDis = (x-x0)*(x-x0) + (y-y0)*(y-y0);
xMax = x;
yMax = y;
}
else if((x-x0)*(x-x0) + (y-y0)*(y-y0) == MaxDis && x>xMax)
{
xMax = x;
yMax = y;
}
else if((x-x0)*(x-x0) + (y-y0)*(y-y0) == MaxDis && y > yMax)
{
xMax = x;
yMax = y;
}
}
}
}
//处理模块3
for(x = floor(x0-R); x <= ceil(x0); x++)//x循环
{
for(y = floor(y0-R); y <= ceil(-x+x0+y0-R); y++)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) <= R*R)//判断是否在圆内(包括边界)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) > MaxDis)
{
MaxDis = (x-x0)*(x-x0) + (y-y0)*(y-y0);
xMax = x;
yMax = y;
}
else if((x-x0)*(x-x0) + (y-y0)*(y-y0) == MaxDis && x>xMax)
{
xMax = x;
yMax = y;
}
else if((x-x0)*(x-x0) + (y-y0)*(y-y0) == MaxDis && y > yMax)
{
xMax = x;
yMax = y;
}
}
}
}
//处理模块4
for(x = floor(x0); x <= ceil(x0+R); x++)//x循环
{
for(y = floor(y0-R); y <= ceil(x-x0+y0-R); y++)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) <= R*R)//判断是否在圆内(包括边界)
{
if((x-x0)*(x-x0) + (y-y0)*(y-y0) > MaxDis)
{
MaxDis = (x-x0)*(x-x0) + (y-y0)*(y-y0);
xMax = x;
yMax = y;
}
else if((x-x0)*(x-x0) + (y-y0)*(y-y0) == MaxDis && x>xMax)
{
xMax = x;
yMax = y;
}
else if((x-x0)*(x-x0) + (y-y0)*(y-y0) == MaxDis && y > yMax)
{
xMax = x;
yMax = y;
}
}
}
}
//cout << xMax << " " << yMax << endl;
printf("%d %d\n", xMax, yMax);
printf("%d\n",18^22);
return 0;
}<file_sep>/FuncModule/CPlusPlus/ReverseLinkedList.cpp
/**
*
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
@author:yangchun,chen
@date:20180308
@Loc:IQIYI innovation building of Shanghai.
*
*/
#include <iostream>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x):val(x),next(NULL){}
};
ListNode *ReverseLinkedList(ListNode* head){
if(head == NULL || head->next == NULL){
return head;
}
//翻转链表需要三个指针,否则串不起来
ListNode *p = head->next,*q = head->next;
//将链表头next指向空
head->next = NULL;
//遍历并将链表翻转
while(p->next != NULL){
p = p->next;
q-> next = head;
head = q;
q = p;
}
q->next = head;
//两个节点的时候避免自己指向自己
if(p != q){
p->next = q;
}
return p;
}
int main(){
ListNode list[3] = {1,2,3};
list[0].next = &list[1];
list[1].next = &list[2];
list[2].next = NULL;
ListNode *p = ReverseLinkedList(list);
while(p){
cout << p->val << endl;
p = p->next;
}
return 0;
}
<file_sep>/FuncModule/CPlusPlus/ThreadPool/MyThreadPool.h
#pragma once
#include<list>
#include "MyMutex.h"
#include "MyStack.h"
#include "MyList.h"
#include"MyQueue.h"
#include "Singleton.h"
class CMyThread;
class CTask;
enum PRIORITY
{
NORMAL,
HIGH
};
class CBaseThreadPool
{
public:
virtual bool SwitchActiveThread(CMyThread*)=0;
};
class CMyThreadPool:public CBaseThreadPool
{
public:
CMyThreadPool(int num=5);//线程池中线程数量
~CMyThreadPool(void);
public:
virtual CMyThread* PopIdleThread();
virtual bool SwitchActiveThread(CMyThread*);
virtual CTask*GetNewTask();
public:
//priority为优先级。高优先级的任务将被插入到队首。
bool addTask(const std::function<BOOL()>& fun,PRIORITY priority,int id=-1);
bool addTask(CTask*t,PRIORITY priority);
bool removeTask(int id);
bool start();//开始调度。
bool destroyThreadPool();
bool clearThreadPool();
private:
int m_nThreadNum;
bool m_bIsExit;
CMyStack m_IdleThreadStack;//Stack是后进先出的结构,Idel线程无所谓哪一个,方便拿出就可
CMyList m_ActiveThreadList;//List是方便删除的结构,Active线程是同时运行的,并不知哪个线程先运行结束,所以要方便移除,用List最合适了
CMyQueue m_TaskQueue;//queue和deque是顺序结构,先进先出,如果任务优先级都相同的,就使用queue,如果有两种优先级,就使用deque,如果有若干优先级,就使用multimap
};
template class Singleton<CMyThreadPool>;
#define THREADPOOL_MGR Singleton<CMyThreadPool>::GetInstance()
<file_sep>/FuncModule/CPlusPlus/BinarySearch/BinarySearch.h
#include <iostream>
int BinarySearch(int num[], int arrSize,int number);
<file_sep>/FuncModule/CPlusPlus/Count_Primes.cpp
//法1:效率高
#include<iostream>
#include<math.h>
#include<stdlib.h>
using namespace std;
int countPrimes(int n){
if(n <= 2) return 0;
if(n == 3) return 1;
bool *prime = (bool *)malloc(sizeof(bool)*n);
int i = 0, j = 0;
int count = n-2;
int rt = sqrt(n);
for(int j =0; j < n; j++){//用于辨别prime[j]是不是素数,素数时为true,不是素数时为false
prime[j] = 1;
}
for( i = 2; i <=rt; i++){//大循环,因为第二个循环是i的平方开始的,所以这里要取到rt=sqrt(n)就行了
if(prime[i]){//如果prime[i]为false,i不是素数,之前已经计算过,就不用再次计算
for(j = i *i; j < n; j+=i){//使j=i*i开始,然后依次加上i,这样循环一遍就将prime中i*i,i*i+i,i*i+2*i...排除掉,并将count减1
if(prime[j]){//如果prime[j]为false,j不是素数,之前已经计算过,就不用再次计算
prime[j]=0;//j不是素数,将prime[j]置0
count--;//排除掉j
}
}
}
}
free(prime);
return count;
}
int main(){
cout << "Input Number:" << endl;
int N;
cin >> N;
int Count = countPrimes(N);
cout << Count << endl;
}
//法2:效率低
/* #include<iostream>
#include<math.h>
using namespace std;
//Solution 1
int CountPrimeNumbers(int n){//计算小于n的素数个数
unsigned int count = 0;//用于统计素数个数
bool flag = false;
int m = 0;
for(int i = 2; i < n; i++){
flag = true;
m = floor(sqrt((float)i));
for(int j = 2; j <= m; j++){
if(i % j == 0){
flag = false;
break;
}
}
if(flag == true){
count++;
}
}
cout << "Prime Numbers:" << count << endl;
}
int main(){
cout << "Input Number:" << endl;
int Number;//输入的数字,然后计算小于该数共有多少素数
cin >> Number;
CountPrimeNumbers(Number);
} */
<file_sep>/FuncModule/CPlusPlus/BinarySearch/makefile
main:main.o BinarySearch.o BinaryRecursionSearch.o
g++ -o main main.o BinarySearch.o BinaryRecursionSearch.o
main.o:BinarySearch.h BinaryRecursionSearch.o
BinarySearch.o:BinarySearch.h
BinaryRecursionSearch.o:BinaryRecursionSearch.h
<file_sep>/FuncModule/CPlusPlus/NumberOfDigitOne.cpp
/*
FileName: NumberOfDigitOne.cpp
Create Time: 2015/09/15
Modify Time:
Author: <NAME>
Owner: <NAME>
Place: 上海交通大学闵行校区微电子楼301室
Reference: https://leetcode.com/problems/number-of-digit-one/
Description: (1)统计小于等于n的所有非负整数中数字1出现的次数;
*/
class Solution {
public:
int countDigitOne(int n) {
int ones = 0;
for (long long m = 1; m <= n; m *= 10)
ones += (n/m + 8) / 10 * m + (n/m % 10 == 1) * (n%m + 1);//神算法
return ones;
}
// Explanation
// Let me use variables a and b to make the explanation a bit nicer.
// int countDigitOne(int n) {
// int ones = 0;
// for (long long m = 1; m <= n; m *= 10) {
// int a = n/m, b = n%m;
// ones += (a + 8) / 10 * m + (a % 10 == 1) * (b + 1);
// }
// return ones;
// }
// Go through the digit positions by using position multiplier m with values 1, 10, 100, 1000, etc.
// For each position, split the decimal representation into two parts, for example split n=3141592 into a=31415 and b=92 when we're at m=100 for analyzing the hundreds-digit. And then we know that the hundreds-digit of n is 1 for prefixes "" to "3141", i.e., 3142 times. Each of those times is a streak, though. Because it's the hundreds-digit, each streak is 100 long. So (a / 10 + 1) * 100 times(乘以100是因为个位十位有0~99共100种情况), the hundreds-digit is 1.
// Consider the thousands-digit, i.e., when m=1000. Then a=3141 and b=592. The thousands-digit is 1 for prefixes "" to "314", so 315 times. And each time is a streak of 1000 numbers. However, since the thousands-digit is a 1, the very last streak isn't 1000 numbers but only 593 numbers(依次以200,2000,20000为界来区分), for the suffixes "000" to "592". So (a / 10 * 1000) + (b + 1) times, the thousands-digit is 1.
// The case distincton between the current digit/position being 0, 1 and >=2 can easily be done in one expression. With (a + 8) / 10 you get the number of full streaks, and a % 10 == 1 tells you whether to add a partial streak.
};<file_sep>/FuncModule/CPlusPlus/ListSorting/ListSorting/MergeSorting.h
/*
FileName: BubbleSorting.h
Create Time: 2015/09/04
Modify Time:
Author: <NAME>
Owner: <NAME>
Place: 上海交通大学闵行校区微电子楼301室
Reference: 《程序员面试宝典》——13.2.9 如何进行单链表排序
Description: (1)单链表的归并排序算法;
*/
#ifndef _MERGESORTING_H_
#define _MERGESORTING_H_
#define MAXSIZE 1024
#define LENGTH 8
typedef struct
{
int r[MAXSIZE + 1];
int length;
}SqList;
void Merge(SqList SR, SqList &TR, int i, int m, int n);
void MSort(SqList SR, SqList &TR1, int s, int t);
void MergeSort(SqList &L);
#endif<file_sep>/Project/Python/monitor_process/readme.txt
监控QXClient.exe进程,在进程被启动后自动将qixiu.ini中日志等级log_level修改为2。<file_sep>/FuncModule/Java/Sorting/src/Sorting.java
/*
* 所有排序算法
*冒泡排序(bubble sort) — O(n^2)——已学
*鸡尾酒排序(Cocktail sort,双向的冒泡排序) — O(n^2)
*插入排序(insertion sort)— O(n^2)——已学
*桶排序(bucket sort)— O(n); 需要 O(k) 额外空间——不错,需学习
*计数排序(counting sort) — O(n+k); 需要 O(n+k) 额外空间——不错,需学习
*合并排序(merge sort)— O(nlog n); 需要 O(n) 额外空间——不错,需学习
*原地合并排序— O(n^2)
*二叉排序树排序 (Binary tree sort) — O(nlog n)期望时间; O(n^2)最坏时间; 需要 O(n) 额外空间
*鸽巢排序(Pigeonhole sort) — O(n+k); 需要 O(k) 额外空间
*基数排序(radix sort)— O(n·k); 需要 O(n) 额外空间
*Gnome 排序— O(n^2)
*图书馆排序— O(nlog n) with high probability,需要 (1+ε)n额外空间
*/
/*
* @Date: 4-24-2015
* @author <NAME>
* 排序算法
* (1)Selection_Sorting:选择排序
* (2)Bubble_Sorting:冒泡排序
* (3)Insert_Sorting:插入排序
*/
public class Sorting {
public static void main(String[] args) {
// TODO 自动生成的方法存根
int [] intArray1 = {1, 23, 45, 32, 0, 100, 3, 5, 33};
int [] intArray2 = {1, 23, 45, 32, 0, 100, 3, 5, 33};
int [] intArray3 = {38, 65, 97, 76, 13, 27, 49};
int [] intArray4 = {38, 65, 97, 76, 13, 27, 49};
int [] intArray5 = {38, 65, 97, 76, 13, 27, 49};
int [] intArray6 = {38, 65, 97, 76, 13, 27, 49};
System.out.print("选择排序:");
System.out.println();//回车换行
Selection_Sorting(intArray1);
System.out.println();//回车换行
System.out.println();//回车换行
System.out.print("冒泡排序:");
System.out.println();//回车换行
Bubble_Sorting(intArray2);
System.out.println();//回车换行
System.out.println();//回车换行
System.out.print("插入排序:");
System.out.println();//回车换行
Insert_Sorting(intArray3);
System.out.println();//回车换行
System.out.println();//回车换行
System.out.print("快速排序:");//非常重要,因为效率高被频繁使用
System.out.println();//回车换行
System.out.print("排序前的数组元素");
for(int a:intArray4){//遍历数组
System.out.print(a + " ");
}
Quick_Sorting(intArray4, 0, intArray4.length-1);
System.out.println();//回车换行
System.out.print("排序后的数组元素");
for(int a:intArray4){//遍历数组
System.out.print(a + " ");
}
System.out.println();//回车换行
System.out.println();//回车换行
System.out.print("归并排序:");//非常重要,被众多公司频繁使用
System.out.println();//回车换行
System.out.print("排序前的数组元素");
for(int a:intArray5){//遍历数组
System.out.print(a + " ");
}
System.out.println();//回车换行
Merge_Sorting(intArray5, 0, intArray5.length - 1);
System.out.print("排序后的数组元素");
for(int a:intArray5){//遍历数组
System.out.print(a + " ");
}
System.out.println();//回车换行
System.out.println();//回车换行
System.out.print("希尔排序:");//非常重要,被众多公司频繁使用
System.out.println();//回车换行
System.out.print("排序前的数组元素");
for(int a:intArray6){//遍历数组
System.out.print(a + " ");
}
System.out.println();//回车换行
Shell_Sorting(intArray5, intArray5.length);
System.out.print("排序后的数组元素");
for(int a:intArray5){//遍历数组
System.out.print(a + " ");
}
System.out.println();//回车换行
System.out.println();//回车换行
}
public static void Selection_Sorting(int[] Array){//选择排序法(因为通过第二层遍历的时候每次都选择最小的或者最大的数据)
int keyvalue;
int index;
int temp;
System.out.print("排序前的数组元素");
for(int a:Array){//遍历数组
System.out.print(a + " ");
}
System.out.println();//回车换行
for(int i = 0; i < Array.length; i++){
index = i;
keyvalue = Array[i];
for(int j = i; j < Array.length; j++){//遍历一次选择最小的数据
if(Array[j] < keyvalue){//如果比keyvalue小,就更新index和keyvalue
index = j;
keyvalue = Array[j];
}
}
temp = Array[i];//交换遍历的最小值跟i位置的值
Array[i] = Array[index];
Array[index] = temp;
}
System.out.print("排序后的数组元素");
for(int a:Array){//遍历数组
System.out.print(a + " ");
}
}
public static void Bubble_Sorting(int [] Array){//冒泡排序
System.out.print("排序前的数组元素");
for(int a:Array){//遍历数组
System.out.print(a + " ");
}
System.out.println();//回车换行
for(int i = 0; i < Array.length; i++){
for(int j = 0; j < Array.length - i - 1; j++){
if(Array[j] > Array[j+1]){
Array[j] = Array[j] ^ Array[j+1];
Array[j+1] = Array[j] ^ Array[j+1];
Array[j] = Array[j] ^ Array[j+1];
}
}
}
System.out.print("排序后的数组元素");
for(int a:Array){//遍历数组
System.out.print(a + " ");
}
}
public static void Insert_Sorting(int [] Array){//插入排序
int i,j;
int temp;
System.out.print("排序前的数组元素");
for(int a:Array){//遍历数组
System.out.print(a + " ");
}
System.out.println();//回车换行
for(i = 1; i < Array.length; i++){
temp = Array[i];
for(j = i - 1; j >= 0; j--){
if(temp < Array[j]){
Array[j+1]= Array[j];//这个相当于将大的元素往高位移
}
else
break;
}
Array[j+1] = temp;//在对应位置上插入新加入的元素Array[i]
}
System.out.print("排序后的数组元素");
for(int a:Array){//遍历数组
System.out.print(a + " ");
}
}
public static void Quick_Sorting(int [] Array, int low, int high){//快速排序,参考《程序员面试宝典》
int i, j;
int index;
if(low>= high)
return;
/*************一趟排序,根据index=array[i]的大小,以index为界限, 将区间分为小于index的区间和大于index的区间****************/
i = low;
j = high;
index = Array[i];//存储Array[i]到index变量
while(i < j){//分区,根据i和j来将待排序数据分成两区间,其中j所在区间大于i所在区间
while(i < j&& Array[j] >= index)//保证前面部分值都小于j所指向元素,然后依次递减j
j--;
if(i < j)
Array[i++] = Array[j];//满足该条件说明Array[j] < index,那么就将j所指向的元素放到i对应的区间中去
while(i < j&& Array[i] < index)//然后对比i所指向元素是否小于index,将i指针往j指针靠拢
i++;
if(i < j)
Array[j--] = Array[i];//满足该条件说明 Array[i] >= index,将i所指向的元素替换到j指针所指向位置
}
Array[i] = index;
/****************************************************************************************************/
Quick_Sorting(Array, low, i - 1);//注意high的值
Quick_Sorting(Array, i+1, high);//注意low的值
}
public static void Merge(int [] Array, int p, int q, int r){//归并排序——合并,参考《程序员面试宝典》
int i,j,k,n1,n2;
n1 = q - p + 1;
n2 = r - q;
int []L = new int[n1];
int []R = new int[n2];
/**********将两子表的值拷贝到数组L和R中*********/
for(i = 0,k = p; i<n1; i++, k++){
L[i] = Array[k];
}
for(i = 0,k = q+1; i<n2; i++, k++){
R[i] = Array[k];
}
/****************************************/
/**********比较两子表L、R大小,按大小顺序回赋给array数组*********/
for(k = p, i=0, j=0; i<n1 && j<n2; k++){
if(L[i]>R[j]){//这是降序排列,改为<为升序排列
Array[k] = L[i];
i++;
}
else{
Array[k] = R[j];
j++;
}
}
if(i<n1){//满足i<n1说明上面for循环是由于j>=n2导致终止的,说明L中剩余的值都小于R中元素,直接按顺序复制给array就行(按这种算法, L和R中的元素都是有序的)
for(j=i; j<n1; j++, k++){
Array[k]=L[j];
}
}
if(j<n2){//同上
for(i=j; i<n2; i++, k++){
Array[k]=R[i];
}
}
/**********************************************/
}
public static void Merge_Sorting(int [] Array, int p, int r){//归并排序——递归划分子表、合并
if(p<r){
int q = (p + r)/2;
Merge_Sorting(Array, p, q);//递归划分子表,直到为单个元素为止
Merge_Sorting(Array, q+1, r);//递归划分子表,直到为单个元素为止
Merge(Array, p, q, r); //合并半子表
}
}
public static void Shell_Sorting(int [] array, int length){//希尔排序,简单明了,给力
int i,j;
int h;
int temp;
for(h=length/2; h>0; h=h/2){//这里h为数组长度依次除2向上取整
for(i=h; i<length; i++){//直接插入排序
temp = array[i];//赋值i位置值给temp
for(j=i-h; j>=0; j-=h){//如果temp(i位置对应数组数据)比j=i-h*n(n为整数)小,就交换temp和j处的数据,否则继续下一次循环
if(temp<array[j]){//这里<号排出来的是升序,改为>变成降序
array[j+h] = array[j];
}
else{
break;
}
}
array[j+h] = temp;//回赋temp值给相应的j+h位置
}
}
}
}
<file_sep>/FuncModule/CPlusPlus/MSOnlineTest/Preliminary3/Ques3.cpp
/*
题目3 : 质数相关
时间限制:2000ms
单点时限:1000ms
内存限制:256MB
描述
两个数a和 b (a<b)被称为质数相关,是指a × p = b,这里p是一个质数。一个集合S被称为质数相关,是指S中存在两个质数相关的数,否则称S为质数无关。如{2, 8, 17}质数无关,但{2, 8, 16}, {3, 6}质数相关。现在给定一个集合S,问S的所有质数无关子集中,最大的子集的大小。
输入
第一行为一个数T,为数据组数。之后每组数据包含两行。
第一行为N,为集合S的大小。第二行为N个整数,表示集合内的数。
输出
对于每组数据输出一行,形如"Case #X: Y"。X为数据编号,从1开始,Y为最大的子集的大小。
数据范围
1 ≤ T ≤ 20
集合S内的数两两不同且范围在1到500000之间。
小数据
1 ≤ N ≤ 15
大数据
1 ≤ N ≤ 1000
样例输入
3
5
2 4 8 16 32
5
2 3 4 6 9
3
1 2 3
样例输出
Case #1: 3
Case #2: 3
Case #3: 2
*/<file_sep>/CodingPartner/setup.py
from distutils.core import setup
setup(
name='CodingPartner',
version='',
packages=['FuncPack.txtManage', 'FuncPack.Project_Manage', 'FuncPack.FuncModule_Manage', 'PathPack.Path'],
url='',
license='',
author='chenyangchun',
author_email='<EMAIL>',
description='This is a software designed to manage different kinds of source code in order to accumulate function module so that we come become a coding okami from a loser!'
)
<file_sep>/FuncModule/CPlusPlus/RotateList.cpp
/*
FileName: RotateList.cpp
Create Time: 2015/09/04
Modify Time:
Author: <NAME>
Owner: <NAME>
Place: 上海交通大学闵行校区微电子楼301室
Reference: https://leetcode.com/problems/rotate-list/
Description: (1)List翻转末尾K个节点到首端;
*/
/*
例程:
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
//这里定义三个指针即可,p指针指向前k个Node的头,q指向前k个Node的尾,然后将head指向q->next,然后l指向list倒数第二个指针,接下来将p->next=p,q->next=NULL即可。
if(head == NULL || k == 0)//如果为空或者K=0直接返回head即可
return head;
//统计List节点数
int NodeNums = 1;
ListNode* tempNode = head;
while((tempNode = tempNode->next) != NULL)
{
NodeNums++;
}
//计算截断的节点位置,这个需要好好理清思路
int count = NodeNums - k - 1;//公式1
if((count < 0) && (k % NodeNums == 0))//当count<0且k能整除List节点数时,说明不需要做出改变
{
return head;
}
else if((count < 0) && (k % NodeNums != 0))//当count<0且k不能整除List节点数时,需要计算统计截断位置
{
count = NodeNums - k % NodeNums-1;//公式2——其实跟公式1是一样的
}
//将后端K个节点提到List前端来
ListNode* p=head,*q=head,*l=head;
while(count>0)
{
q = q->next;
count--;
}
l = head = q->next;
while(l->next != NULL)
{
l = l ->next;
}
l -> next = p;
q -> next = NULL;
return head;
}
};<file_sep>/FuncModule/CPlusPlus/BinarySearch/BinarySearch.cpp
/**
@author:yangchun,chen
@date:2018.3.7
@算法要求:(1)必须采用顺序存储结构(已排序);(2)必须按关键字大小有序排列。
*/
#include "BinarySearch.h"
using namespace std;
int BinarySearch(int num[], int arrSize,int number){
if(num == NULL || arrSize == 0){
return -1;
}
int start,end,mid;
start = 0;
end = arrSize - 1;
while(start <= end){
mid = (start + end) / 2;
if(num[mid] == number){
return mid;
}
else if(num[mid] > number){
end = mid - 1;
}
else{
start = mid + 1;
}
}
return -1;
}
<file_sep>/FuncModule/CPlusPlus/algorithm_2.cpp
/*
@que:一个二叉树,数的节点组成一个数组、作为方法的输入,每个节点里除了和其他节点的关联关系字段之外,还有当前节点在显示器上的坐标,其中y坐标一定等于当前节点在树中的层数(例如y坐标等于2则一定是在树的第二层);请写一个方法判断在显示这个树时,有没有树枝会交叉。
@author:yangchun,chen
@date:3/26/2018
@pudong,shanghai
*/
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
struct TreeNode{
int x,y;
TreeNode *left;
TreeNode *right;
TreeNode(int x,int y):x(x),y(y),left(nullptr),right(nullptr){}
};
/*参考LevelTraverseOfBt工程层次遍历*/
bool LayerTraversal(TreeNode *root){
if(!root){
return true;
}
vector<TreeNode *> vec;
int cur = 0,last = 0;
TreeNode *last_node = root;
vec.push_back(root);
bool result = false;
//遍历整棵树
while(cur < vec.size()){
last = vec.size();
//遍历二叉树的一层
while(cur < last){
//如果位于同一层,而且左边的节点x值比右边的大,树枝就会有交叉
if(last_node->y == vec[cur]->y){
result = last_node->x > vec[cur]->x;
if(result)
break;
}
last_node = vec[cur];
//将下一层的节点入队列
if(vec[cur]->left){
vec.push_back(vec[cur]->left);
}
if(vec[cur]->right){
vec.push_back(vec[cur]->right);
}
cur++;
}
if(result){
break;
}
}
return result;
}
int main(){
TreeNode n1(1,0);
TreeNode n2(9,1);
TreeNode n3(10,1);
TreeNode n4(4,2);
TreeNode n5(5,2);
n1.left = &n2;
n1.right = &n3;
n2.left = &n4;
n2.right = &n5;
bool result = LayerTraversal(&n1);
cout << "The binary tree " << (result ? "has " : "don't have ") << "overlap area!" << endl;
return 0;
}
<file_sep>/FuncModule/CPlusPlus/UDPTest/udptestDlg.cpp
// udptestDlg.cpp : implementation file
//
#include "stdafx.h"
#include "udptest.h"
#include "udptestDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define BUFFER_LEN 8192
unsigned char RcvBuffer[BUFFER_LEN];
unsigned int port;
int m_rcvport=5000;
CString GetLocalIP(int ipIndex)
{
//获取版本和本机IP地址 获取本机第ipIndex个IP地址
char r_iplist[16][256];
int i=0;
WORD wVersionRequested;
WSADATA wsaData;
char name[255];
PHOSTENT hostinfo;
wVersionRequested = MAKEWORD( 2, 0 );
if ( WSAStartup( wVersionRequested, &wsaData ) == 0 )
{
if( gethostname ( name, sizeof(name)) == 0)
{
if((hostinfo = gethostbyname(name)) != NULL)
{
for (i=0;i<16; i++ )
{
_tcscpy(r_iplist[i], inet_ntoa( *(IN_ADDR*)hostinfo->h_addr_list[i] ));
if ( hostinfo->h_addr_list[i] + hostinfo->h_length >= hostinfo->h_name )
break;
}
//ip = inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list);
}
}
WSACleanup();
}
return r_iplist[ipIndex];
}
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CUdptestDlg dialog
CUdptestDlg::CUdptestDlg(CWnd* pParent /*=NULL*/)
: CDialog(CUdptestDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CUdptestDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CUdptestDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CUdptestDlg)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CUdptestDlg, CDialog)
//{{AFX_MSG_MAP(CUdptestDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
ON_WM_TIMER()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CUdptestDlg message handlers
BOOL CUdptestDlg::OnInitDialog()
{
CDialog::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)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
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
//CIPAddressCtrl* pWnd=(CIPAddressCtrl*)GetDlgItem(IDC_IPADDRESS1);
//pWnd->SetWindowText("127.0.0.1");
CString strIP=GetLocalIP(0);
SetDlgItemText(IDC_IPADDRESS1,strIP);
m_MySocket=new MySocket(this);
m_MySocket->Create(m_rcvport,SOCK_DGRAM);
SetTimer(100,200,0);
return TRUE; // return TRUE unless you set the focus to a control
}
void CUdptestDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::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 CUdptestDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (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
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CUdptestDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CUdptestDlg::OnReceive(MySocket *psock)
{
int datalength;
CString SAddress;
datalength=psock->ReceiveFrom(RcvBuffer,BUFFER_LEN,SAddress,port,0);//接收UDP传输数据
}
BOOL CUdptestDlg::DestroyWindow()
{
// TODO: Add your specialized code here and/or call the base class
delete m_MySocket;
return CDialog::DestroyWindow();
}
void CUdptestDlg::OnButton1()
{
// TODO: Add your control notification handler code here
CString strIP;
GetDlgItemText(IDC_IPADDRESS1,strIP);
char Buffer[256];
Buffer[0]=0x55;
Buffer[1]=0xAA;
m_MySocket->SendTo(Buffer,2,5000,strIP,0);//发送数据
}
void CUdptestDlg::OnTimer(UINT nIDEvent)
{
// TODO: Add your message handler code here and/or call default
//刷新实时数据显示
CString strTemp;
strTemp.Format("%02x %02x %02x %02x %02x %02x %02x %02x",RcvBuffer[0],RcvBuffer[1],RcvBuffer[2],RcvBuffer[3],RcvBuffer[4],RcvBuffer[5],RcvBuffer[6],RcvBuffer[7]);
strTemp.MakeUpper();
SetDlgItemText(IDC_EDIT1,strTemp);
CDialog::OnTimer(nIDEvent);
}
<file_sep>/Project/Python/monitor_process/monitor_process_ex_py3.py
#date: 2017/12/15
__author__ = 'chenyangchun'
import os
import time
import subprocess
import configparser
import psutil
import sys
import codecs
from winreg import *
import msvcrt
#将qixiu.ini日志等级修改为2
def ChangeLogLev(Path,sec,key,val='0'):
if not os.path.exists(Path):
print(Path+"does not exist!")
return
cf = configparser.ConfigParser()
cf.read(Path)
#print(Path)
#cf.readfp(codecs.open(Path,"r","gb2312"))
log_level = cf.get(sec,key)
print(key+":"+log_level)
if key=='on_line':
if log_level=='0':
val='1'
elif log_level=='1':
val='0'
if int(log_level) > 1:
return
else:
print(key+" changed to:"+val)
cf.set(sec,key,val)
cf.write(open(Path,"w"))
#cf.write(codecs.open(Path,"w+","gb2312"))
process_name = 'QXClient.exe'
sleep_time = 60
#检测QXClient并返回进程是否运行以及进程路径
def monitor_QXClient():
#Listing Processes which are not responding
process_list = os.popen('tasklist"').read().strip().split('\n')
bQXClientIsRunning = False
qixiu_ini_path = ""
for process in process_list:
if process.startswith(process_name):
bQXClientIsRunning = True
pn = process.split(' ')
for i in pn:
if i.isdigit():
pid = i
break
print("QXClient ProcessId:"+pid)
p = psutil.Process(int(pid))
#QXClient.exe进程路径
path = p.exe()
#print(path)
qixiu_ini_path = path[:-len(process_name)]+'qixiu.ini'
print(qixiu_ini_path)
return bQXClientIsRunning,qixiu_ini_path
#获取爱奇艺PC客户端QyClient目录qixiu下的qixiu.ini文件路径
def getQiXiuPath():
regpath = "SOFTWARE\\Wow6432Node\\QiYi\\QiSu"
installkey = "HDir"
reg = OpenKey(HKEY_LOCAL_MACHINE, regpath)
QyClientPath,type = QueryValueEx(reg, installkey)
print("QyCient Path:"+QyClientPath)
qixiu_ini_path = QyClientPath+"\\QYAppPlugin\\qixiu\\qixiu.ini"
print("qixiu.ini path:"+qixiu_ini_path)
return qixiu_ini_path
def readInput(default="No order inputed,qixiu.ini will be changed inmediately!", timeout=30):
start_time = time.time()
sys.stdout.write(('(%d秒自动跳过,q:退出,o:修改on_line字段,l:用默认编辑器打开player.log文件,enter:立即改变log_level字段值):' % (timeout)))
sys.stdout.flush()
input = ''
while True:
ini=msvcrt.kbhit()
try:
if ini:
chr = msvcrt.getche()
if ord(chr) == 13: # enter_key
break
elif ord(chr) >= 32:
input += chr.decode()
except Exception as e:
pass
if len(input) == 13 or time.time() - start_time > timeout:
break
if len(input) > 0:
return input+''
else:
return default
if __name__ == '__main__':
while True:
bQXClientIsRunning,qixiu_ini_path = monitor_QXClient()
if not bQXClientIsRunning:#如果QXClient.exe未在运行,就修改QyClient目录下的qixiu.ini文件
qixiu_ini_path = getQiXiuPath()
print("QXlient.exe is not running!")
else:
print("QXClient.exe is running!")
ChangeLogLev(qixiu_ini_path,'common','log_level','2')
print ("Input 'Enter' to change qixiu.ini inmediately!")
s = readInput()
print("\nInput Order:"+s)
if s.strip()=='q':
print ("Quit!")
break
elif s.strip()=='o':
ChangeLogLev(qixiu_ini_path,'common','on_line')
elif s.strip()=='l':
ini_name="qixiu.ini"
os.startfile(qixiu_ini_path[:-len(ini_name)]+"player.log")
print("Open player.log with default IDE!")
else:
pass
print("\n")
<file_sep>/FuncModule/CPlusPlus/SearchTree.cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
vector<int> temp;
int LevelTravase(TreeNode* root, int level)
{
if(root == NULL || level < 0)
return 0;
else if(level == 0)
{
temp.push_back(root->val);
return 1;
}
return LevelTravase(root->left, level-1) + LevelTravase(root->right, level-1);
}
vector<vector<int>> levelOrder(TreeNode* root) {
for(int level = 0; ; level++)
{
if(!LevelTravase(root,level))
break;
result.push_back(temp);
temp.clear();
}
return result;
}
TreeNode* Find(TreeNode* root, TreeNode*p)//Find the p TreeNode in BST root
{
if(root == NULL)
return NULL;
else if(p->val < root->val)
{
return Find(root->left, p);
}
else if(p->val > root->val)
{
return Find(root->right, p);
} vector<vector<int>> result;
else
return root;
}
/**
@question:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//二叉树的lowest common ancestor(LCA)的查找函数lowestCommonAncestor,深刻理解递归调用中局部变量和return语句层层返回的机制,大师级代码
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == p || root == q || root == NULL) return root;//1 这份代码最骚的地方在第一个判断这里,比如从root分成两个分支,如果p和q都不在左分支,那么最终递归后左分支返回NULL,结果就从右分支查找了
TreeNode *left = lowestCommonAncestor(root->left, p, q), *right = lowestCommonAncestor(root->right, p, q);//后序遍历,这里left和right都是局部变量,每调用一次都会创建一次,但是通过//1和//2保证了找到的节点会层层返回到最开始的root节点那层的lowestCommonAncestor函数,大师级代码
return left && right ? root : left ? left : right;//2
}
};<file_sep>/FuncModule/CPlusPlus/UDPTest/udptest.h
// udptest.h : main header file for the UDPTEST application
//
#if !defined(AFX_UDPTEST_H__F3CCB4A9_E2FF_47A6_8B35_4F84D0ECE78B__INCLUDED_)
#define AFX_UDPTEST_H__F3CCB4A9_E2FF_47A6_8B35_4F84D0ECE78B__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CUdptestApp:
// See udptest.cpp for the implementation of this class
//
class CUdptestApp : public CWinApp
{
public:
CUdptestApp();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CUdptestApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CUdptestApp)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_UDPTEST_H__F3CCB4A9_E2FF_47A6_8B35_4F84D0ECE78B__INCLUDED_)
<file_sep>/Project/Python/monitor_process/monitor_process_py3.py
#date: 2017/12/15
__author__ = 'chenyangchun'
import os
import time
import subprocess
import configparser
import psutil
import sys
import codecs
from winreg import *
#将qixiu.ini日志等级修改为2
def ChangeLogLev(Path,logLevel='2'):
if not os.path.exists(Path):
print(Path+"does not exist!")
return
cf = configparser.ConfigParser()
cf.read(Path)
#print(Path)
#cf.readfp(codecs.open(Path,"r","gb2312"))
log_level = cf.get('common','log_level')
print("log_level:"+log_level)
if int(log_level) > 1:
return
else:
print("log_level changed to:"+logLevel)
cf.set('common','log_level',logLevel)
cf.write(open(Path,"w"))
#cf.write(codecs.open(Path,"w+","gb2312"))
process_name = 'QXClient.exe'
sleep_time = 60
#检测QXClient并返回进程是否运行以及进程路径
def monitor_QXClient():
#Listing Processes which are not responding
process_list = os.popen('tasklist"').read().strip().split('\n')
bQXClientIsRunning = False
qixiu_ini_path = ""
for process in process_list:
if process.startswith(process_name):
bQXClientIsRunning = True
pn = process.split(' ')
for i in pn:
if i.isdigit():
pid = i
break
print(pid)
p = psutil.Process(int(pid))
#QXClient.exe进程路径
path = p.exe()
#print(path)
qixiu_ini_path = path[:-len(process_name)]+'qixiu.ini'
print(qixiu_ini_path)
return bQXClientIsRunning,qixiu_ini_path
#获取爱奇艺PC客户端QyClient目录qixiu下的qixiu.ini文件路径
def getQiXiuPath():
regpath = "SOFTWARE\\Wow6432Node\\QiYi\\QiSu"
installkey = "HDir"
reg = OpenKey(HKEY_LOCAL_MACHINE, regpath)
QyClientPath,type = QueryValueEx(reg, installkey)
print("QyCient Path:"+QyClientPath)
qixiu_ini_path = QyClientPath+"\\QYAppPlugin\\qixiu\\qixiu.ini"
print(qixiu_ini_path)
return qixiu_ini_path
if __name__ == '__main__':
while True:
bQXClientIsRunning,qixiu_ini_path = monitor_QXClient()
if not bQXClientIsRunning:#如果QXClient.exe未在运行,就修改QyClient目录下的qixiu.ini文件
qixiu_ini_path = getQiXiuPath()
print("QXlient.exe is not running!")
else:
print("QXClient.exe is running!")
ChangeLogLev(qixiu_ini_path)
time.sleep(sleep_time)
<file_sep>/FuncModule/CPlusPlus/AddTwoNumbers.cpp
/*
@ques:You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
@author:yangchun,chen
@date:3/25/2018
@pudong district,shanghai
*/
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
//如果l1或l2为空,直接返回
if(l1 == NULL){
return l2;
}
if(l2 == NULL){
return l1;
}
//存储链表投指针到head
ListNode *head = l1;
//存储两位数字相加的十位和个位
int dec = 0,unit = 0;
//遍历l1和l2,对应节点的值相加,并向前进位,直到next为空
while(l1 != NULL && l2 != NULL){
int temp = l1->val + dec + l2->val;
dec = temp / 10;
unit = temp %10;
l1->val = unit;
if(l1->next !=NULL && l2->next != NULL){
l1 = l1->next;
l2 = l2->next;
}
else{
break;
}
}
//将l1指向下个节点,这样就只需对l1进行操作了
if(l1->next == NULL){
l1->next = l2->next;
}
//遍历l1,遍历节点的值需加上之前l1和l2节点的进位值
while(l1->next != NULL){
int temp = l1->next->val + dec;
dec = temp / 10;
unit = temp % 10;
l1->next->val = unit;
l1 = l1->next;
}
//如果遍历到了l1链表尾,还是有进位,需要新建一个节点存储进位值
if(dec > 0){
ListNode *newnode = new ListNode(dec);
l1->next = newnode;
}
return head;
}
};
<file_sep>/FuncModule/CPlusPlus/Dec2Hex.cpp
UINT32 Dec2Hex(CString addr_dec)//将输入的10进制转换成对应的十六进制,如输入1000转换成0x1000
{
std::map <CString, UINT32> Hex2Dec_map;//map
CString hexstr[16] = {_TEXT("0"), _TEXT("1"), _TEXT("2"), _TEXT("3"),_TEXT("4"),_TEXT("5"),_TEXT("6"),_TEXT("7"),_TEXT("8"),_TEXT("9"),_TEXT("a"),_TEXT("b"),_TEXT("c"),_TEXT("d"),_TEXT("e"), _TEXT("f")};
CString hexstr_others[6] = {_TEXT("A"),_TEXT("B"),_TEXT("C"),_TEXT("D"),_TEXT("E"), _TEXT("F")};
for(int i = 0; i < 16; i++){
Hex2Dec_map.insert(std::make_pair(hexstr[i], i));
}
for(int i = 0; i < 6; i++){
Hex2Dec_map.insert(std::make_pair(hexstr_others[i], i+10));
}
CString str_addr_dec = addr_dec;
char RlCardMaxAddr_char[20];
UINT32 temp_hex = 0;
int Bits = addr_dec.GetLength();
int count = Bits;
for(int i = 0; i < Bits; i++)
{
/*temp_hex += temp_dec / (UINT32)(pow(10.0, Bits-1)) * (UINT32)pow(16.0, Bits-1);
temp_dec -= (UINT32)(pow(10.0, Bits-1));*/
temp_hex += Hex2Dec_map[CString(addr_dec[i])] * (UINT32)pow(16.0, --count);
}
return temp_hex;
}<file_sep>/CodingPartner/Main/main.py
'''
FileName: CodingPartner
Create Time: 2015/08
Modify Time:
Author: <NAME>
Owner: <NAME>
Place: Shanghai Jiao Tong University, Min Hang district.
Reference:
Description: (1)Can based on document ReadMe.txt record, according to the keywords to search the corresponding code path, convenient query and management of files
'''
__author__ = 'JD'
#Main Function
# import sys
# sys.path.append("..\\FuncPack\\txtManage")
# sys.path.append("..\\PathPack\\Path")
# sys.path.append("..\\\Main_UI")
from Main_UI import *
from tkinter import *
from PathPack.Path import *
import PathPack.Path.__init__
import subprocess
import os
from tkinter import filedialog
def SetDefaultWorkingFile(entry_query):#Get File Directory
Path = filedialog.askdirectory()
if os.path.exists(Path) and Path != "":
entry_query.insert(0, Path)
class SetDefaultPath:
#Flow:
#(1)First: Judge whether there under the
def __init__(self):
self.DefaultPath = "C:\\Users\\Public\\Coding Partner\\DefaultPath.txt"
self.DefaultDir = "C:\\Users\\Public\\Coding Partner"
self.Init()
def SetDefaultWorkingFile_OK(self):
Path = self.entry_PATH.get()
if Path != "":
if os.path.exists(Path):
if self.Combobox_Dir.get() == "Existed":
os.mkdir(self.DefaultDir)
DefaultPath = self.DefaultDir + "\\DefaultPath.txt"
fid = open(DefaultPath, "wt")
Path = Path+"/"
fid.write(Path)#This str should get from UI set
fid.close()
PathPack.Path.__init__.AbsolutePath = Path
PathPack.Path.__init__.Path_Assig_Value()
elif self.Combobox_Dir.get() == "New":
os.mkdir(self.DefaultDir)
DefaultPath = self.DefaultDir + "\\DefaultPath.txt"
fid = open(DefaultPath, "wt")
if not os.path.exists(Path + "/Coding_Partner"):
os.mkdir(Path + "/Coding_Partner")
Path = Path + "/Coding_Partner/"
fid.write(Path)#This str should get from UI set
fid.close()
PathPack.Path.__init__.AbsolutePath = Path
PathPack.Path.__init__.Path_Assig_Value()
self.PathSetUI.destroy()
def CancelButtonFunc(self):
self.PathSetUI.destroy()
sys.exit()
def Init(self):
if not os.path.exists(self.DefaultPath):
#result = askyesno("Attention","Do You Want Create A New Working Directory?")
#if result == YES:
self.PathSetUI = Tk()
self.PathSetUI.title("Select Working Directory")
self.PathSetUI.resizable(False,False)
self.PathSetUI.protocol ("WM_DELETE_WINDOW", self.CancelButtonFunc)
self.label_DirSelect = Label(self.PathSetUI,anchor = "nw",text="Directory Type")
self.label_DirSelect.grid(row=0, column=0,sticky=W, columnspan = 2)
cmbEditComboList_Dir = ["New", "Existed"]
self.Combobox_Dir = Combobox(self.PathSetUI, values = cmbEditComboList_Dir, state = 'readonly') #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.Combobox_Dir.set("Existed");
self.Combobox_Dir.grid(row=0, column = 2, columnspan = 2)
self.label_PATH = Label(self.PathSetUI,anchor = "nw",text="PATH") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_PATH.grid(row=0, column=4,sticky=W, columnspan = 3)
self.entry_PATH = Entry(self.PathSetUI,width = 60, bd =5)
self.entry_PATH.grid(row=0, column=7, columnspan = 6)
self.button_SetPath = Button(self.PathSetUI, text = "Open", command = lambda:SetDefaultWorkingFile( self.entry_PATH))#tied the entry to the button, when the button is being clicked, function KeywordQuery will be called.
self.button_SetPath.grid(row=0, column=13)
self.button_ok = Button(self.PathSetUI, text = " OK ", command = self.SetDefaultWorkingFile_OK)#tied the entry to the button, when the button is being clicked, function KeywordQuery will be called.
self.button_ok.grid(row=1, column=4, columnspan = 4)
self.button_cacel = Button(self.PathSetUI, text = "CACEL", command = self.CancelButtonFunc)#tied the entry to the button, when the button is being clicked, function KeywordQuery will be called.
self.button_cacel.grid(row=1, column=8, columnspan = 4)
#make the current main window lay in the middle of screen
self.PathSetUI.update_idletasks()
w = self.PathSetUI.winfo_screenwidth()
h = self.PathSetUI.winfo_screenheight()
size = tuple(int(_) for _ in self.PathSetUI.geometry().split('+')[0].split('x'))
x = w/2 - size[0]/2
y = h/2 - size[1]/2
self.PathSetUI.geometry("%dx%d+%d+%d" % (size + (x, y)))
self.PathSetUI.mainloop()
else:
fid = open(self.DefaultPath, "r")
line = fid.readline()
fid.close()
PathPack.Path.__init__.AbsolutePath = line
PathPack.Path.__init__.Path_Assig_Value()
class MainWindow:
#Set a new default Directory or select existed directory
QuriedResultList = [] #Queried result will be in this list variable
#Later the GUI related code will be packaging and be putted in Main_UI directory
#GUI Related
############################################Query GUI Related###############################################################
#input gui entry contorl
if __name__ == "__main__":
WindowsCodingPartnerPath = SetDefaultPath()
frmMain = Tk()
frmMain.title("Coding Partner")
frmMain.resizable(False,False)
label_query = Label(frmMain,anchor = "nw",text="Enter Keyword") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
label_query.grid(row=0, sticky=W, columnspan = 3)
entry_query = Entry(frmMain,width = 95, bd =5, fg = 'blue')
entry_query.grid(row=0, column=3, columnspan = 2)
button_query = Button(frmMain, text = "query", command = lambda:KeywordQuery(entry_query.get(),Text_result))#tied the entry to the button, when the button is being clicked, function KeywordQuery will be called.
button_query.grid(row=0, column=5)
#output gui entry contol
label_result = Label(frmMain,anchor = "s",text="Queried Results") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
label_result.grid(row=2, column=0, sticky=W)
Text_result = Text(frmMain, width = 95, height = 15)
Text_result.grid(row=2, column=3, columnspan = 2)
#Bind the ENTER key to Entry to execute KeywordQuery function
# create a popup menu
def ShowInExplorer():
selectedPath = Text_result.get('sel.first', 'sel.last')
#judge whether the path exists
if os.path.exists(selectedPath):
if os.path.isdir(selectedPath):
subprocess.Popen(r'explorer /select,"{0}"'.format(selectedPath))
else:
showwarning("Warning","\'"+selectedPath+"\'"+" do not exist")#show a warning MessageBox
def OpenwithIDE():
selectedPath = Text_result.get('sel.first', 'sel.last')
#judge whether the path exists
if os.path.exists(selectedPath):
if os.path.isfile(selectedPath):
os.startfile(selectedPath)
else:
showwarning("Warning","\'"+selectedPath+"\'"+" do not exist")#show a warning MessageBox
menu = Menu(frmMain, tearoff=0)
menu.add_command(label="show in windows explorer", command=ShowInExplorer)
menu.add_command(label="open with related IDE", command=OpenwithIDE)
def Text_result_callback(event):
menu.post(event.x_root, event.y_root)
Text_result.bind('<Button-3>', Text_result_callback)
#Bind the ENTER key to Entry to execute KeywordQuery function
def callback(event):
KeywordQuery(entry_query.get(), Text_result)
entry_query.bind('<KeyRelease>', callback)#<KeyRelease>
############################################Add Record GUI Related######################################################
button_Manage_Record = Button(frmMain, text="Manage Record", command= lambda:Call_Manage_Record_GUI(frmMain))
button_Manage_Record.grid(row=4, column=3, rowspan = 2)
button_Manage_Dir = Button(frmMain, text = "Manage Directory", command = lambda:Call_Manage_Dir_GUI(frmMain))#Button used to add record in Record.txt
button_Manage_Dir.grid(row=4, column=4, rowspan = 2)
######################################################End###############################################################
#make the current main window lay in the middle of screen
frmMain.update_idletasks()
w = frmMain.winfo_screenwidth()
h = frmMain.winfo_screenheight()
size = tuple(int(_) for _ in frmMain.geometry().split('+')[0].split('x'))
x = w/2 - size[0]/2
y = h/2 - size[1]/2
frmMain.geometry("%dx%d+%d+%d" % (size + (x, y)))
#ScrollBary in Text
scrollbary = Scrollbar(frmMain, orient = 'vertical')
scrollbary.grid(row = 2, column = 3,sticky = 'NES', columnspan = 2) #sticky is used to contorl the Control's direction in the contained Control
# attach Text Control to scrollbar
Text_result.config(yscrollcommand=scrollbary.set)
scrollbary.config(command=Text_result.yview)
#ScrollBarx in Text
scrollbarx = Scrollbar(frmMain, orient = 'horizontal')
scrollbarx.grid(row = 2, column =3,sticky = 'WSE', columnspan = 2) #sticky is used to contorl the Control's direction in the contained Control
# attach Text Control to scrollbar
Text_result.config(xscrollcommand=scrollbarx.set)
scrollbarx.config(command=Text_result.xview)
KeywordQuery(entry_query.get(), Text_result)#Init
frmMain.mainloop()
<file_sep>/FuncModule/CPlusPlus/UDPTest/MySocket.cpp
// MySocket.cpp : implementation file
//
#include "stdafx.h"
#include "udptest.h"
#include "MySocket.h"
#include "udptestDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// MySocket
MySocket::MySocket()
{
}
MySocket::MySocket(CUdptestDlg* p_hwnd)
{
p_dlgwnd=p_hwnd;
}
MySocket::~MySocket()
{
}
// Do not edit the following lines, which are needed by ClassWizard.
#if 0
BEGIN_MESSAGE_MAP(MySocket, CSocket)
//{{AFX_MSG_MAP(MySocket)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
#endif // 0
/////////////////////////////////////////////////////////////////////////////
// MySocket member functions
void MySocket::OnReceive(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
CSocket::OnReceive(nErrorCode);
p_dlgwnd->OnReceive(this);
}
<file_sep>/FuncModule/CPlusPlus/SelfDevidingNumbers.cpp
/*
@que:A self-dividing number is a number that is divisible by every digit it contains.
For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
Also, a self-dividing number is not allowed to contain the digit zero.
Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible.
Example 1:
Input:
left = 1, right = 22
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
@url:https://leetcode.com/problems/self-dividing-numbers/description/
@author:yangchun,chen
@date:3/27/2018
@pudong,shanghai
*/
class Solution {
public:
bool Devisible(const int &val){
int temp = val;
bool result = true;
while(temp){
//获取余数
int remainder = temp % 10;
if((remainder == 0) ||
(val % remainder != 0)){
result = false;
break;
}
//往右移位
temp /= 10;
}
return result;
}
vector<int> selfDividingNumbers(int left, int right) {
vector<int> arr;
for(int index = left; index <= right; index++){
if(Devisible(index)){
arr.push_back(index);
}
}
return arr;
}
};
<file_sep>/FuncModule/CPlusPlus/cybulk/BulkLoopDlg.h
// BulkLoopDlg.h : header file
//
#if !defined(AFX_BULKLOOPDLG_H__D3E75ECD_0ADD_4838_B4EE_E39E6FC7B4B8__INCLUDED_)
#define AFX_BULKLOOPDLG_H__D3E75ECD_0ADD_4838_B4EE_E39E6FC7B4B8__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "CyAPI.h"
/////////////////////////////////////////////////////////////////////////////
// CBulkLoopDlg dialog
class CBulkLoopDlg : public CDialog
{
// Construction
public:
CBulkLoopDlg(CWnd* pParent = NULL); // standard constructor
CCyUSBDevice *USBDevice;
CCyUSBEndPoint *OutEndpt;
CCyUSBEndPoint *InEndpt;
int DeviceIndex;
CWinThread *XferThread;
int DataFillMethod;
bool bLooping;
//bool RegForUSBEvents(void);
// Dialog Data
//{{AFX_DATA(CBulkLoopDlg)
enum { IDD = IDD_BULKLOOP_DIALOG };
CButton m_DisableTimeoutChkBox;
CButton m_TestBtn;
CButton m_RefreshBtn;
CComboBox m_DeviceListComBox;
CButton m_StartBtn;
CStatic m_StatusLabel;
CComboBox m_FillPatternComBox;
CButton m_StopOnErrorChkBox;
CEdit m_SeedValue;
CStatic m_FailureCount;
CStatic m_SuccessCount;
CEdit m_XferSize;
CComboBox m_InEndptComBox;
CComboBox m_OutEndptComBox;
int m_DataValueRadioBtns;
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CBulkLoopDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
//{{AFX_MSG(CBulkLoopDlg)
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnStartBtn();
afx_msg void OnSelchangeOutCombox();
afx_msg void OnSelchangeInCombox();
afx_msg void OnResetBtn();
afx_msg void OnRefreshBtn();
afx_msg void OnTestBtn();
afx_msg void OnSelchangeDeviceListCombox();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_BULKLOOPDLG_H__D3E75ECD_0ADD_4838_B4EE_E39E6FC7B4B8__INCLUDED_)
<file_sep>/FuncModule/CPlusPlus/BinarySearch/main.cpp
#include <iostream>
#include "BinarySearch.h"
#include "BinaryRecursionSearch.h"
using namespace std;
int main(){
int A[] = {1,2,3,4,5,6};
int index = BinarySearch(A,6,3);
cout << "Binary search index is:" << index << "\n";
index = BinaryRecurSearch(0,5,A,3);
cout << "Binary recursion search index is:" << index << "\n";
return 0;
}
<file_sep>/CodingPartner/PathPack/Path/__init__.py
__author__ = 'JD'
import sys,os
global AbsolutePath
###################Text File Path in FuncModule####################
#C
global Path_FuncModule_C
#CPlusPlus
global Path_FuncModule_CPlusPlus
#CSharp
global Path_FuncModule_CSharp
#HTML_CSS
global Path_FuncModule_HTML_CSS
#Matlab
global Path_FuncModule_Matlab
#Python
global Path_FuncModule_Python
#SQL
global Path_FuncModule_SQL
###################Text File Path in Project##########################
#C
global Path_Project_C
#CPlusPlus
global Path_Project_CPlusPlus
#CSharp
global Path_Project_CSharp
#HTML_CSS
global Path_Project_HTML_CSS
#Matlab
global Path_Project_Matlab
#Python
global Path_Project_Python
#SQL
global Path_Project_SQL
########################### Path List ###############################
global Path_FuncModule
global Path_Project
global Path_FuncModule_txt
global Path_Project_txt
#Three Path Lists
global RootPathList
global FuncModulePathList
global ProjectPathList
def Path_Assig_Value():
###################Text File Path in FuncModule####################
#C
global Path_FuncModule_C
Path_FuncModule_C = AbsolutePath + "FuncModule/C/Record.txt"
#CPlusPlus
global Path_FuncModule_CPlusPlus
Path_FuncModule_CPlusPlus = AbsolutePath+"FuncModule/CPlusPlus/Record.txt"
#CSharp
global Path_FuncModule_CSharp
Path_FuncModule_CSharp = AbsolutePath+"FuncModule/CSharp/Record.txt"
#HTML_CSS
global Path_FuncModule_HTML_CSS
Path_FuncModule_HTML_CSS = AbsolutePath+"FuncModule/HTML_CSS/Record.txt"
#Matlab
global Path_FuncModule_Matlab
Path_FuncModule_Matlab = AbsolutePath+"FuncModule/Matlab/Record.txt"
#Python
global Path_FuncModule_Python
Path_FuncModule_Python = AbsolutePath+"FuncModule/Python/Record.txt"
#SQL
global Path_FuncModule_SQL
Path_FuncModule_SQL = AbsolutePath+"FuncModule/SQL/Record.txt"
###################Text File Path in Project##########################
#C
global Path_Project_C
Path_Project_C = AbsolutePath+"Project/C/Record.txt"
#CPlusPlus
global Path_Project_CPlusPlus
Path_Project_CPlusPlus = AbsolutePath+"Project/CPlusPlus/Record.txt"
#CSharp
global Path_Project_CSharp
Path_Project_CSharp = AbsolutePath+"Project/CSharp/Record.txt"
#HTML_CSS
global Path_Project_HTML_CSS
Path_Project_HTML_CSS = AbsolutePath+"Project/HTML_CSS/Record.txt"
#Matlab
global Path_Project_Matlab
Path_Project_Matlab = AbsolutePath+"Project/Matlab/Record.txt"
#Python
global Path_Project_Python
Path_Project_Python =AbsolutePath+ "Project/Python/Record.txt"
#SQL
global Path_Project_SQL
Path_Project_SQL = AbsolutePath+"Project/SQL/Record.txt"
########################### Path List ###############################
global Path_FuncModule
Path_FuncModule =AbsolutePath+ "FuncModule/"
global Path_Project
Path_Project = AbsolutePath+"Project/"
global Path_FuncModule_txt
Path_FuncModule_txt = AbsolutePath+"FuncModule/Record.txt"
global Path_Project_txt
Path_Project_txt = AbsolutePath+"Project/Record.txt"
#Three Path Lists
global RootPathList
RootPathList = [Path_FuncModule_txt,Path_Project_txt]
global FuncModulePathList
FuncModulePathList = [Path_FuncModule_C,Path_FuncModule_CPlusPlus, Path_FuncModule_CSharp, Path_FuncModule_HTML_CSS, Path_FuncModule_Matlab, Path_FuncModule_Python,Path_FuncModule_SQL]
global ProjectPathList
ProjectPathList = [Path_Project_C,Path_Project_CPlusPlus, Path_Project_CSharp, Path_Project_HTML_CSS, Path_Project_Matlab, Path_Project_Python,Path_Project_SQL]<file_sep>/CodingPartner/FuncPack/txtManage/__init__.py
__author__ = 'JD'
import threading
from PathPack.Path import *
from tkinter import * #when use realted module, we need to import the realted package
from tkinter.messagebox import *
from datetime import *
import shutil #delete directory recursively related
import shutil, errno
import PathPack.Path.__init__
#Add, Delete, Modify and Query the txt file under FuncModule directory and Project directory
###################################### Manage Directory #########################################
#Add
def ManageDirectory_Add(object,Type, Code_Type):
if Type == "":
object.wm_attributes("-topmost", 0)
showwarning("Warning","\'Type\'"+" can't be null")#show a warning MessageBox
object.wm_attributes("-topmost", 1)
return
Type_Dict = {"Function Module": PathPack.Path.__init__.Path_FuncModule,"Project": PathPack.Path.__init__.Path_Project} #Map Type to related directory
Code_Type_Dict = {"C++": "CPlusPlus","Java": "Java","Python": "Python","C#": "CSharp","SQL": "SQL","Html/CSS": "HTML_CSS","C_Lang": "C_Lang","Matlab": "Matlab"} #Map Code Type to related directory
Add_Code_Type_Pairs(Code_Type_Dict, Code_Type)
Type_Dir = ''
if Type in Type_Dict:
Type_Dir = Type_Dict[Type]
else:
Type_Dir = PathPack.Path.__init__.AbsolutePath + Type
#Judge whether Type directory exists
if os.path.exists(Type_Dir):#Type directory exists
#Judge whether Code_Type directory exists further
Code_Type_Dir = ''
temp_Dir = Type_Dict[Type] if Type in Type_Dict else Type
if Code_Type == "":
Code_Type_Dir = temp_Dir
elif Code_Type in Code_Type_Dict:
Code_Type_Dir = temp_Dir + Code_Type_Dict[Code_Type]
else:
Code_Type_Dir = temp_Dir + Code_Type
if os.path.exists(Code_Type_Dir):#Type directory exists
if Code_Type == "":#Code Type directory does not exist
object.wm_attributes("-topmost", 0)
showwarning("Warning","\'"+Type+"\'"+" directory exists")#show a warning MessageBox
object.wm_attributes("-topmost", 1)
else:
object.wm_attributes("-topmost", 0)
showwarning("Warning","\'"+Code_Type_Dict[Code_Type]+"\'"+" directory exists")#show a warning MessageBox
object.wm_attributes("-topmost", 1)
else:#Code Type directory does not exist
object.wm_attributes("-topmost", 0)
Create_Code_Type_Direcotry(Type, Type_Dir, Code_Type_Dict[Code_Type] if (Code_Type in Code_Type_Dict) else Code_Type, Code_Type_Dir)#create Record.txt
showinfo("Success","\'"+ Code_Type +"\'"+" directory was created")
object.wm_attributes("-topmost", 1)
else:#Type directory does not exist
object.wm_attributes("-topmost", 0)
Create_Type_Direcotry(Type, Type_Dir)#create Record.txt
showinfo("Success","\'"+ Type +"\'"+" directory was created")
object.wm_attributes("-topmost", 1)
def Create_Code_Type_Direcotry(Type, Type_Dir, Code_Type, Dir):#create related directory in directory Dir(decided by TypeorCode_Type variable) and Record.txt
os.mkdir(Dir)#create directory
Init_buffer = Type+"-"+Code_Type+"总纲领每添加一个功能模块代码,更新该文档。切记,要维护好本源码功能快速定位功能,需要每次更新完代码后都要实时更新该文本。\n****************************************"+Code_Type+"****************************************************\n标准记录格式:序号-日期:中英文关键字;\n"+"1-"+("%s"%date.today()).replace('-', '')+":Init\n"
with open(os.path.join(Dir, "Record.txt"), 'wt') as Record_file:
Record_file.write(Init_buffer)
Type_Init_Buffer = "\n****************************************"+Code_Type+"****************************************************\n"+"1-"+("%s"%date.today()).replace('-', '')+":Init\n"
with open(os.path.join(Type_Dir, "Record.txt"), 'at+') as Record_file:
Record_file.write(Type_Init_Buffer)
def Create_Type_Direcotry(Type, Dir):#create related directory in directory Dir(decided by TypeorCode_Type variable) and Record.txt
os.mkdir(Dir)#create directory
Init_buffer = Type+"总纲领\n总纲领每次当更新一次源代码的时候除了在其所属文件夹更新ReadMe记录信息外,还需要更新本文档的记录信息,\n这样的话每次查询需要的代码模块的时候就可以按照以下方式快速定位需要寻找的代码模块或者功能:\n=====================1.在本文档用Ctrl+F寻找关键字(单词,中文关键字),定位该功能在哪个语言版本中存在=================================================\n=====================2.根据1的结果到相应的文件夹中的ReadMe文件中用Ctrl+F寻找代码功能模块源码所属文件夹=================================================\n切记,要维护好本源码功能快速定位功能,需要每次更新完代码后都要实时更新该文本。\n"
with open(os.path.join(Dir, "Record.txt"), 'wt') as Record_file:
Record_file.write(Init_buffer)
def Add_Code_Type_Pairs(Dict, Code_Type):
if Code_Type not in Dict:
Dict[Code_Type] = Code_Type
#Delete
def ManageDirectory_Delete(object,Type, Code_Type):
if Type == "":
object.wm_attributes("-topmost", 0)
showwarning("Warning","\'Type\'"+" can't be null")#show a warning MessageBox
object.wm_attributes("-topmost", 1)
return
Type_Dict = {"Function Module": PathPack.Path.__init__.Path_FuncModule,"Project": PathPack.Path.__init__.Path_Project} #Map Type to related directory
Code_Type_Dict = {"C++": "CPlusPlus","Java": "Java","Python": "Python","C#": "CSharp","SQL": "SQL","Html/CSS": "HTML_CSS","C_Lang": "C_Lang","Matlab": "Matlab"} #Map Code Type to related directory
Type_Dir = ''
if Type in Type_Dict:
Type_Dir = Type_Dict[Type]
else:
Type_Dir = PathPack.Path.__init__.AbsolutePath + Type
Add_Code_Type_Pairs(Code_Type_Dict, Code_Type)
#Judge whether Type directory exists
if os.path.exists(Type_Dir):#Type directory exists
#Judge whether Code_Type directory exists further
Code_Type_Dir = ''
Code_Type_Dir = Type_Dir + Code_Type_Dict[Code_Type] if Code_Type in Code_Type_Dict else Type_Dir + Code_Type
if os.path.exists(Code_Type_Dir) and Code_Type != "":#Code Type directory exists
object.wm_attributes("-topmost", 0)
result = askyesno("Caution","Do you really want to delete %s?"%Code_Type)
if result == True:
shutil.rmtree(Code_Type_Dir)#delete directory
Delete_Dir_RenewRecordtxt(Type_Dir, Code_Type)#delete related record in file Record.txt
showinfo("Success","\'"+ Code_Type_Dir +"\'"+" directory was deleted")
object.wm_attributes("-topmost", 1)
else:
object.wm_attributes("-topmost", 1)
elif Code_Type == "":#Code Type directory does not exist
object.wm_attributes("-topmost", 0)
result = askyesno("Caution","Do you really want to delete %s?"%Type)
if result == True:
shutil.rmtree(Type_Dir)
showinfo("Success","\'"+ Type_Dir +"\'"+" directory was deleted")
object.wm_attributes("-topmost", 1)
else:
object.wm_attributes("-topmost", 1)
else:
object.wm_attributes("-topmost", 0)
showwarning("Warning","\'"+Code_Type_Dir+"\'"+" directory does not exist")#show a warning MessageBox
object.wm_attributes("-topmost", 1)
else:#Type directory does not exist
object.wm_attributes("-topmost", 0)
showwarning("Warning","\'"+Type+"\'"+" directory does not exist")#show a warning MessageBox
object.wm_attributes("-topmost", 1)
def Delete_Dir_RenewRecordtxt(Type_Dir, Code_Type):#create related directory in directory Dir(decided by TypeorCode_Type variable) and Record.txt
Code_Type_Dict = {"C++": "CPlusPlus","Java": "Java","Python": "Python","C#": "CSharp","SQL": "SQL","Html/CSS": "HTML_CSS","C_Lang": "C_Lang","Matlab": "Matlab"} #Map Code Type to related directory
Record_txt = Type_Dir + "Record.txt"
fid = open(Record_txt,"r")
lines = fid.readlines()
fid.close()
fid = open(Record_txt,"wt")
#locate if the postion of keyword is between two "*" realted line
endflag = 0#0 means the keyword related record is last record
KeywordPos = float("inf")#represent infinity, no numbers in python larger than this number
CurPos = 0
for line in lines:
Keywordindex = line.find(Code_Type_Dict[Code_Type] if Code_Type in Code_Type_Dict else Code_Type)
CurPos = CurPos + len(line)
Otherindex = line.find('*')
count = 0
count = CntStarCharinLine(line)
if Keywordindex != -1:#keyword line
KeywordPos = Keywordindex + CurPos
elif CurPos + Otherindex > KeywordPos and count >= 20:
endflag = 1
#write the text back to file except content to be deleted
writeflag = 1
CurPos = 0
KeywordPos = float("inf")
for line in lines:
count = 0
CurPos = CurPos + len(line)
count = CntStarCharinLine(line)#decide the deletion end position
if line.find(Code_Type_Dict[Code_Type] if Code_Type in Code_Type_Dict else Code_Type) == -1 and writeflag == 1:#ahead keyword record
fid.write(line)
elif count >= 20 and CurPos + line.find('*') > KeywordPos:#after keyword line
fid.write(line)
writeflag = 1
elif line.find(Code_Type_Dict[Code_Type] if Code_Type in Code_Type_Dict else Code_Type) != -1:#keyword line
if endflag == 1:
writeflag = 0
KeywordPos = CurPos + line.find(Code_Type_Dict[Code_Type] if Code_Type in Code_Type_Dict else Code_Type)
continue
else:
break
fid.close()
def CntStarCharinLine(line):
count = 0
for char in line:
if char == '*':
count += 1
return count
##################################### Manage Record ##########################################
#Add Button
def copytree(src, dst,object, symlinks=False, ignore=None):
# Dir_Name = src.split('/')
# Dir_Name = Dir_Name[-1]
if os.path.isdir(src):
shutil.copytree(src, dst)
else:
shutil.copy2(src, dst)
# object.wm_attributes("-topmost", 0)
showinfo("Success","\'"+ src +"\'"+" directory was copied")
# object.wm_attributes("-topmost", 1)
# dst += "/" + Dir_Name
# if not os.path.exists(dst):
# os.makedirs(dst)
# for item in os.listdir(src):
# s = os.path.join(src, item)
# d = os.path.join(dst, item)
# if os.path.isdir(s):#目录
# copytree(s, d, symlinks, ignore)
# else:#文件
# if (not os.path.exists(d)) or (os.stat(s).st_mtime - os.stat(d).st_mtime > 1):
# shutil.copy2(s, d)
def ManageRecord_Add_RenewRecordtxt(Code_Type, Type_Dir,Code_Type_Dir, Description, Keywords,DirPath, FilePath):
CodeType_RecordPath = Code_Type_Dir + "/Record.txt"
# RecordFileName = ""#used to store as file name in Record.txt
# if os.path.exists(DirPath) and DirPath != "":
# RecordFileName = Code_Type_Dir + "/" + DirPath.split('/')[-1] + "/" + FilePath.split('/')[-1]
fid = open(CodeType_RecordPath,"r")
lines = fid.readlines()
fid.close()
#Renew Record.txt under Code Type directory
#Get last record's index and date
index_data_record = ""
for line in reversed(lines):
if line != '\n':
index_data_record = line
break
index_data_record = index_data_record.split('-')
index = str(int(index_data_record[0]) + 1)
#Renew Record.txt under Type directory
fid = open(CodeType_RecordPath,"at")
record = ""
if os.path.exists(DirPath) and DirPath != "":
record = index + "-" + ("%s"%date.today()).replace('-', '') + ":" + "增加了Directory>" + DirPath.split('/')[-1] + ">" + FilePath.split('/')[-1] +">" + Description + "关键字:" + Keywords
else:
record = index + "-" + ("%s"%date.today()).replace('-', '') + ":" + "增加了File>" +FilePath.split('/')[-1] +">" + Description + "关键字:" + Keywords
record = record+"\n"
fid.write(record)
fid.close()
#Renew Record.txt under Type directory
Code_Type_Dict = {"C++": "CPlusPlus","Java": "Java","Python": "Python","C#": "CSharp","SQL": "SQL","Html/CSS": "HTML_CSS","C_Lang": "C_Lang","Matlab": "Matlab"} #Map Code Type to related directory
Type_Record_txt = Type_Dir + "Record.txt"
#locate if the postion of keyword is between two "*" realted line
fid = open(Type_Record_txt,"r")
lines = fid.readlines()
fid.close()
endflag = 0#0 means the keyword related record is last record
KeywordPos = float("inf")#represent infinity, no numbers in python larger than this number
CurPos = 0
for line in lines:
Keywordindex = line.find(Code_Type_Dict[Code_Type] if Code_Type in Code_Type_Dict else Code_Type)
CurPos = CurPos + len(line)
Otherindex = line.find('*')
count = 0
count = CntStarCharinLine(line)
if Keywordindex != -1:#keyword line
KeywordPos = Keywordindex + CurPos
elif CurPos + Otherindex > KeywordPos and count >= 20:
endflag = 1
fid = open(Type_Record_txt,"at")
if endflag == 0:
fid.write(record+"\n")
fid.close()
return
fid = open(Type_Record_txt,"wt")
#write the text back to file except content to be deleted
writeflag = 0
CurPos = 0
KeywordPos = float("inf")
for line in lines:
count = 0
CurPos = CurPos + len(line)
count = CntStarCharinLine(line)#decide the deletion end position
if line.find(Code_Type_Dict[Code_Type] if Code_Type in Code_Type_Dict else Code_Type) == -1:#except keyword record line
if count >= 20 and CurPos + line.find('*') > KeywordPos and writeflag == 1:#after keyword line
fid.write(record)
fid.write("\n" + line)
writeflag = 0
else:
fid.write(line)
elif line.find(Code_Type_Dict[Code_Type] if Code_Type in Code_Type_Dict else Code_Type) != -1:#keyword line
if endflag == 1:
writeflag = 1
KeywordPos = CurPos + line.find(Code_Type_Dict[Code_Type] if Code_Type in Code_Type_Dict else Code_Type)
fid.write(line)
fid.close()
def ManageRecord_Add(object,Type, Code_Type, Description, Keywords, DirPath, FilePath):
if Type == "" or Code_Type == "" or Description == "" or Keywords == "" or FilePath == "" or not os.path.exists(FilePath):
object.wm_attributes("-topmost", 0)
showerror("Parameter Error", "Please configure parameters correctly!")
object.wm_attributes("-topmost", 1)
return
if ":" in Description:
object.wm_attributes("-topmost", 0)
showwarning("Warning","\'"+"Description" +"\'" + " can't contain colon(:), please write it like" + " \'" + "description1;description2; " +"\'")#show a warning MessageBox
object.wm_attributes("-topmost", 1)
return
if ":" in Keywords:
object.wm_attributes("-topmost", 0)
showwarning("Warning","\'"+"Keywords" +"\'" + " can't contain colon(:), please write it like" + " \'" + "keyword1;keyword2; " +"\'")#show a warning MessageBox
object.wm_attributes("-topmost", 1)
return
#Functions of this function:
#(1)Refer to Type and Code_Type, find the Code Type directory,copy related directory or file and..
#(2) add record to Record.txt under found directory;
#(3)Refer to Type, find the Type directory, add record to Record.txt under the directory.
Type_Dict = {"Function Module": PathPack.Path.__init__.Path_FuncModule,"Project": PathPack.Path.__init__.Path_Project} #Map Type to related directory
Code_Type_Dict = {"C++": "CPlusPlus","Java": "Java","Python": "Python","C#": "CSharp","SQL": "SQL","Html/CSS": "HTML_CSS","C_Lang": "C_Lang","Matlab": "Matlab"} #Map Code Type to related directory
Add_Code_Type_Pairs(Code_Type_Dict, Code_Type)
Type_Dir = ''
if Type in Type_Dict:
Type_Dir = Type_Dict[Type]
else:
Type_Dir = PathPack.Path.__init__.AbsolutePath + Type
Code_Type_Dir = ''
temp_Dir = Type_Dict[Type] if Type in Type_Dict else Type
if Code_Type == "":
Code_Type_Dir = temp_Dir+ "/"
elif Code_Type in Code_Type_Dict:
Code_Type_Dir = temp_Dir + Code_Type_Dict[Code_Type]+ "/"
else:
Code_Type_Dir = temp_Dir + Code_Type+ "/"
#As (1) listed before
if os.path.exists(DirPath) and os.path.exists(FilePath):
#创建根目录
temp_Dir_Name = DirPath.split('/')
temp_Dir_Name = temp_Dir_Name[-1]
temp_Code_Type_Dir = Code_Type_Dir + "/" + temp_Dir_Name
# if not os.path.exists(temp_Code_Type_Dir):
# os.makedirs(temp_Code_Type_Dir)
t = threading.Thread(target=copytree, args=(DirPath, temp_Code_Type_Dir,object))
t.start()
showinfo("Info","Copying...")
# t.join()
# copytree(DirPath, temp_Code_Type_Dir)#文件夹拷贝
#object.wm_attributes("-topmost", 0)
# showinfo("Success","\'"+ DirPath +"\'"+" directory was copied")
# object.wm_attributes("-topmost", 1)
elif ~os.path.exists(DirPath) and os.path.exists(FilePath):
shutil.copy2(FilePath, Code_Type_Dir)
object.wm_attributes("-topmost", 0)
showinfo("Success","\'"+ FilePath +"\'"+" file was copied")
object.wm_attributes("-topmost", 1)
else:
showwarning("Warning","Directory or File path illegal")#show a warning MessageBox
#As (2),(3) listed before
ManageRecord_Add_RenewRecordtxt(Code_Type, Type_Dir, Code_Type_Dir, Description,Keywords, DirPath, FilePath)
#Delete Button
def ManageRecord_Delete(object_frm_Manage_Record,Keyword_Query, object_Combobox_Index, object_entry_Description_Delete, object_entry_Keywords_Delete, object_entry_Dir_Path_Delete, object_entry_File_Path_Delete, index_list, description_list, keywords_list, DirPath_list, FilePath_list, MatchedRecordStr):
#the code here can refer to KeywordQuery, query result can store in parameters and return to calling function
#query the result refer to keyword and store results into index_list to FilePath_list below.
index_list.clear()
description_list.clear()
keywords_list.clear()
DirPath_list.clear()
FilePath_list.clear()
MatchedRecordStr.clear()
KeywordQuery_DeleteRecord(Keyword_Query,index_list, description_list, keywords_list, DirPath_list, FilePath_list, MatchedRecordStr)
#as default, we display the first index on UI
if index_list:
object_Combobox_Index['value'] = ""
object_Combobox_Index['value'] = (index_list)
object_Combobox_Index.set(index_list[0])
if description_list:
object_entry_Description_Delete.delete(0, END)
object_entry_Description_Delete.insert(0, description_list[index_list[0]])
if keywords_list:
object_entry_Keywords_Delete.delete(0, END)
object_entry_Keywords_Delete.insert(0, keywords_list[index_list[0]])
if DirPath_list:
object_entry_Dir_Path_Delete.delete(0, END)
object_entry_Dir_Path_Delete.insert(0, DirPath_list[index_list[0]])
if FilePath_list:
object_entry_File_Path_Delete.delete(0, END)
object_entry_File_Path_Delete.delete(0, END)
object_entry_File_Path_Delete.insert(0, FilePath_list[index_list[0]])
def KeywordQuery_DeleteRecord(keyword, index_list, description_list, keywords_list, DirPath_list, FilePath_list,MatchedRecordStr):
TypeDirList = []
CodeTypeDirList = []
TraveringTypeCodeTypeFiles(TypeDirList,CodeTypeDirList)
rootpathlist = []
for TypeDir in TypeDirList:
rootpathlist.append(PathPack.Path.__init__.AbsolutePath + TypeDir + "/Record.txt")
#Traverse rootpathlist with KeyWord
MatchedRecordStr_temp = []
if len(keyword) == 0:#if keyword is space, program will return
return
#Split Keyword by space
keyword = ' '.join(keyword.split())
keyword = keyword.split(' ')
ResultList = []
QueriedResultCounts = 0
for RootPath in rootpathlist:#Used to read the two root text file
handle = open(RootPath, 'r')#Open File and Read text
#The next three variables is very important!
index = [] #used to store the file position of the "keyword" and paried string Str_Language = []
Str_index = []#the string of where keyword belongs to.
index_Language = {"index_C_Lang": 0,"index_CplusPlus": 0, "index_Csharp": 0, "index_Python": 0, "index_SQL": 0, "index_HTML_CSS": 0, "index_Matlab": 0, "index_Java": 0} #Used to store the current file position of each language index, like "CPlusPlus" and so on.
DirectoryOrFileName = [] #used to store the directory discribed in keyword
Curr_Pos = 0#Current file postion in the text file
for eachLine in handle:#Traverse the text in file and calculate the value of variable "index" and "index_Language"
tempindex = -1
for keyword_item in keyword:
tempindex = eachLine.find(keyword_item)
if tempindex != -1:
continue
else:
break
tempindex1 = tempindex + Curr_Pos
if tempindex != -1:
index.append(tempindex1)#Add the keyword's position in index list
MatchedRecordStr_temp.append(eachLine)
Str_index.append(eachLine)
tempstr = eachLine.split('>')
if len(tempstr) >= 4:
DirectoryOrFileName.append(tempstr[1] + "\\" + tempstr[2]) #The code directory related to keyword
elif len(tempstr) >= 2:
DirectoryOrFileName.append(tempstr[1]) #The code directory related to keyword
else:
DirectoryOrFileName.append("")
count = 0
for i in index:
if RootPath == PathPack.Path.__init__.Path_FuncModule_txt:
for TypeDir in TypeDirList:
for CodeTypeDir in CodeTypeDirList:
Path = PathPack.Path.__init__.AbsolutePath.replace('/', '\\')+ TypeDir + "\\" +CodeTypeDir+ "\\"+ DirectoryOrFileName[count]
if os.path.exists(Path):
ResultList.append(Str_index[count]+"\n PATH: " + Path+"\n")
count = count + 1
else:
for TypeDir in TypeDirList:
for CodeTypeDir in CodeTypeDirList:
Path = PathPack.Path.__init__.AbsolutePath.replace('/', '\\')+ TypeDir + "\\" +CodeTypeDir+ "\\"+ DirectoryOrFileName[count]
if os.path.exists(Path):
ResultList.append(Str_index[count]+"\n PATH: " + Path+ "\n")
count = count + 1
QueriedResultCounts = QueriedResultCounts + count
temp_Count = 0
for querieditems in ResultList: #display the queried result in entry control of GUI
FileName = ""
Description = ""
Splitof_colon = querieditems.split(':')
index_list.append(Splitof_colon[0])
Description = str.replace(Splitof_colon[1],"关键字","",1).split('>')
FileType = str.replace(Description[0],"增加了","",1)
if FileType == "Directory" and len(Description) >= 4:
FileName = Description[2]
Description = Description[3]
elif len(Description) >= 3:
FileName = Description[1]
Description = Description[2]
description_list[Splitof_colon[0]] = Description
Keyword = str.replace(Splitof_colon[2],"PATH","",1)
keywords_list[Splitof_colon[0]] = Keyword
Path = ""
if len(Splitof_colon) >= 5:
Path = Splitof_colon[3] + ":" + Splitof_colon[4]
Path = str.replace(Path, "\n", "",1)
Path = str.replace(Path, " ", "")
FilePath_list[Splitof_colon[0]] = Path
if FileType == "Directory":
if '.' in Path:
Path = str.replace(Path, FileName, "",1)
Path = str.replace(Path, "\n", "",1)
Path = str.replace(Path, " ", "")
Path = Path[::-1].replace("\\","",1)[::-1]
DirPath_list[Splitof_colon[0]] = Path
else:
DirPath_list[Splitof_colon[0]] = "\n"
MatchedRecordStr[Splitof_colon[0]] = MatchedRecordStr_temp[temp_Count]
temp_Count += 1
##################################### Query ##########################################
#First, Query text file just under FuncModule directory and Project directory, and query next layer directory based on result queried in FuncModule and Project directory
def TraveringTypeCodeTypeFiles(TypeDirList, CodeTypeDirList):
# Manage_Dir_GUI.cmbEditComboList_Code_Type = self.Combobox_Code_Type.get()
Dirs = [d for d in os.listdir(PathPack.Path.__init__.AbsolutePath) if os.path.isdir((os.path.join(PathPack.Path.__init__.AbsolutePath,d)))]#list only the directory under given directory
if '.git' in Dirs:
Dirs.remove('.git')
if 'CodingPartner' in Dirs:
Dirs.remove('CodingPartner')
for dir in Dirs:
TypeDirList.append(dir)
# Manage_Dir_GUI.cmbEditComboList_Code_Type = self.Combobox_Code_Type.get()
Type_Dict = {"Function Module": PathPack.Path.__init__.Path_FuncModule,"Project": PathPack.Path.__init__.Path_Project} #Map Type to related directory
cmbEditComboList_Code_Type_Const = {"CPlusPlus": "C++","Java": "Java","Python": "Python","CSharp": "C#","SQL": "SQL","HTML_CSS": "Html/CSS","C_Lang": "C_Lang","Matlab": "Matlab"}
TypeDirMap = {"Function Module":"FuncModule", "Project":"Project"}
Dirs = []
for dir in TypeDirList:
TypeDir = os.path.join(PathPack.Path.__init__.AbsolutePath, TypeDirMap[dir] if dir in TypeDirMap else dir)
Dirs = [d for d in os.listdir(TypeDir) if os.path.isdir(os.path.join(TypeDir,d))]#list only the directory under given directory
for dir in Dirs:
CodeTypeDirList.append(dir)
def KeywordQuery(keyword, Text_result_control):
TypeDirList = []
CodeTypeDirList = []
TraveringTypeCodeTypeFiles(TypeDirList,CodeTypeDirList)
rootpathlist = []
for TypeDir in TypeDirList:
rootpathlist.append(PathPack.Path.__init__.AbsolutePath + TypeDir + "/Record.txt")
#clear the Text
Text_result_control.delete(0.0, END) #based on the package imported at the topmost of this page, namely tkinter
#Traverse rootpathlist with KeyWord
# if len(keyword) == 0:#if keyword is space, program will return
# return
ResultList = []
QueriedResultCounts = 0
#Split Keyword by space
keyword = ' '.join(keyword.split())
keyword = keyword.split(' ')
for RootPath in rootpathlist:#Used to read the two root text file
handle = open(RootPath, 'r')#Open File and Read text
#The next three variables is very important!
index = [] #used to store the file position of the "keyword" and paried string Str_Language = []
Str_index = []#the string of where keyword belongs to.
index_Language = {"index_C_Lang": 0,"index_CplusPlus": 0, "index_Csharp": 0, "index_Python": 0, "index_SQL": 0, "index_HTML_CSS": 0, "index_Matlab": 0, "index_Java": 0} #Used to store the current file position of each language index, like "CPlusPlus" and so on.
DirectoryOrFileName = [] #used to store the directory discribed in keyword
Curr_Pos = 0#Current file postion in the text file
for eachLine in handle:#Traverse the text in file and calculate the value of variable "index" and "index_Language"
tempindex = -1
if len(keyword) == 0:
tempindex = 0;
index.append(tempindex)
continue
for keyword_item in keyword:
tempindex = eachLine.find(keyword_item)
if tempindex != -1:
continue
else:
break
tempindex1 = tempindex + Curr_Pos
if tempindex != -1:
index.append(tempindex1)#Add the keyword's position in index list
Str_index.append(eachLine)
tempstr = eachLine.split('>')
if len(tempstr) >= 4:
DirectoryOrFileName.append(tempstr[1] + "\\" + tempstr[2]) #The code directory related to keyword
elif len(tempstr) >= 2:
DirectoryOrFileName.append(tempstr[1]) #The code directory related to keyword
else:
DirectoryOrFileName.append("")
count = 0
for i in index:
if RootPath == PathPack.Path.__init__.Path_FuncModule_txt:
for TypeDir in TypeDirList:
for CodeTypeDir in CodeTypeDirList:
Path = PathPack.Path.__init__.AbsolutePath.replace('/', '\\')+ TypeDir + "\\" +CodeTypeDir+ "\\"+ DirectoryOrFileName[count]
if os.path.exists(Path):
ResultList.append("\n-******************************************%s**************************************- \nTYPE: "% (QueriedResultCounts+count) + TypeDir +" \nDESCRIPTION: \n"+Str_index[count]+"PATH:\n " + Path+"\n\n")
count = count + 1
else:
for TypeDir in TypeDirList:
for CodeTypeDir in CodeTypeDirList:
Path = PathPack.Path.__init__.AbsolutePath.replace('/', '\\')+ TypeDir + "\\" +CodeTypeDir+ "\\"+ DirectoryOrFileName[count]
if os.path.exists(Path):
ResultList.append("\n-******************************************%s**************************************- \nTYPE: "% (QueriedResultCounts+count) + TypeDir +" \nDESCRIPTION: \n"+Str_index[count]+"PATH:\n " + Path+ "\n\n")
count = count + 1
QueriedResultCounts = QueriedResultCounts + count
# return ResultList#return the queried result.
# print(ResultList)#print the queried result.
count1 = 1.0
for querieditems in ResultList: #display the queried result in entry control of GUI
Text_result_control.insert(count1, querieditems)
count1 = count1 + 7.0
def AddValueInDict(index_list, str, value, CurrPos):
if value != -1:
index_list[str] = value + CurrPos
<file_sep>/Project/CPlusPlus/RFCard_Operate_ReadMissile/RFCard_Operate_ReadMissile/ReflectiveCard.cpp
/**************************************************/
/**************************************************/
/************RFM2g头文件及宏定义******************/
/**************************************************/
/**************************************************/
#if (defined(WIN32))
#include "rfm2g_windows.h"
#endif
#include <stdio.h>
#include <string.h>
#include "rfm2g_api.h"
#include <time.h>
#include "ReflectiveCard.h"
#if (defined(RFM2G_LINUX))
#ifdef CONFIG_DEVFS_FS
#define DEVICE_PREFIX "/dev/rfm2g/"
#else
#define DEVICE_PREFIX "/dev/rfm2g"
#endif
#define PROCFILE "/proc/rfm2g"
#elif defined(RFM2G_VXWORKS)
#define DEVICE_PREFIX "RFM2G_"
#elif defined(SOLARIS)
#define DEVICE_PREFIX "/dev/rfm2g"
#elif defined(WIN32)
#define DEVICE_PREFIX "\\\\.\\rfm2g"
#else
#error Please define DEVICE_PREFIX for your driver
#endif
#define RFCARD_TRANS_MODE_ADDR 0x0010 //反射内存卡主控传输标志信息存储地址
#define START_ADDRESS 0x0000
#define OFFSET_1 0x3000//读取反射内存卡偏移地址
#define OFFSET_2 0x4000//写入反射内存卡偏移地址
/**************************************************/
/**************************************************/
/****************RFM2g头文件及宏定义结束*********/
/**************************************************/
/**************************************************/
enum MainControlMode//主控传输标志信息
{
RF_Query_MissData = 1,//反射内存卡查询模式传输弹道数据
RF_Break_MissData,//反射内存卡中断模式传输弹道数据
UDP,//数据库用到
SYS_Init,//反射内存卡——系统初始化
Reboot,//重启VxWorks系统
PRF_Start,
PRF_Stop,
Last
};
enum MainControlMode static MainCtrolMode = RF_Break_MissData;
#define TIMEOUT 60000 //单位为ms
int RFM_Card_Operate::RFM_Card_Init(rfm2gEventType EventType)//反射内存卡初始化函数,初始化Handle句柄等参数
{
RFM2G_STATUS result;
/* Open the Reflective Memory device */
sprintf(device, "%s%d", DEVICE_PREFIX, numDevice);
result = RFM2gOpen(device, &Handle);
if (result != RFM2G_SUCCESS)
{
printf("ERROR: RFM2gOpen() failed.\n");
printf("Error: %s.\n\n", RFM2gErrorMsg(result));
return(-1);
}
/*获取反射内存卡的型号以及内存大小信息*/
result = RFM2gGetConfig(Handle, &config);
if (result == RFM2G_SUCCESS)
{
printf("\nNode ID is %d\n", config.NodeId);
printf("The total memory size of %s is %d MBytes\n", config.Device, config.MemorySize / 1048576);
printf("The memory offset range is 0x00000000~0x10000000\n");
}
else
{
printf("ERROR: RFM2gGetConfig() failed.\n");
printf("Error: %s.\n\n", RFM2gErrorMsg(result));
return(-1);
}
/*设置大小端,使不能字节反转*/
result_ByteSwap = RFM2gSetPIOByteSwap(Handle, RFM2G_FALSE);
if (result_ByteSwap != RFM2G_SUCCESS)/*设置大小端失败*/
{
printf("ERROR: RFM2gSetPIOByteSwap() failed.\n");
printf("Error: %s.\n\n", RFM2gErrorMsg(result_ByteSwap));
return(-1);
}
result_ByteSwap = RFM2gGetPIOByteSwap(Handle, &byteSwap);
if (result_ByteSwap != RFM2G_SUCCESS)/*获取大小端设置状态失败*/
{
printf("ERROR: RFM2gGetPIOByteSwap() failed.\n");
printf("Error: %s.\n\n", RFM2gErrorMsg(result_ByteSwap));
return(-1);
}
else/*获取大小端设置状态成功*/
{
if (byteSwap == RFM2G_TRUE)
{
printf("The byte swapping of PIO transfers to an RFM2g device is enabled!\n");
}
else
{
printf("The byte swapping of PIO transfers to an RFM2g device is Disabled!\n");
}
}
//写传输模式标志位
int temp = (int)MainCtrolMode;
result = RFM2gWrite(Handle, RFCARD_TRANS_MODE_ADDR, (void *)&temp, sizeof(int));//往地址RFCARD_TRANS_MODE_ADDR写入当前反射内存卡传输模式参数
if (result != RFM2G_SUCCESS)
{
printf("Error: %s\n", RFM2gErrorMsg(result));
RFM2gClose(&Handle);
return(-1);
}
RFM_Card_EnableEvent(EventType);//使能RFM2GEVENT_INTR2中断
}
RFM2G_STATUS RFM_Card_Operate::RFM_Card_EnableEvent(rfm2gEventType EventType)
{
/* Now wait on an interrupt from the other Reflective Memory board */
EventInfo_Receive.Event = EventType; /* We'll wait on this interrupt */
EventInfo_Receive.Timeout = TIMEOUT; /* We'll wait this many milliseconds */
RFM2G_STATUS result = RFM2gEnableEvent(Handle, EventType);//使能接收的中断类型RFM2GEVENT_INTR2
if (result != RFM2G_SUCCESS)
{
printf("Error: %s\n", RFM2gErrorMsg(result));
RFM2gClose(&Handle);
return(result);
}
}
RFM2G_STATUS RFM_Card_Operate::RFM_Card_DisableEvent()
{
//关闭中断
RFM2G_STATUS result = RFM2gDisableEvent(Handle, EventInfo_Receive.Event);
return result;
}
RFM2G_STATUS RFM_Card_Operate::RFM_Write_Missle(struct MissilePosInfo outbuffer, rfm2gEventType EventType)
{
RFM2G_STATUS result = RFM2gWrite(Handle, OFFSET_WRT, (void *)&outbuffer, sizeof(struct MissilePosInfo));
/* Send an interrupt to the other Reflective Memory board */
result = RFM2gSendEvent(Handle, OhterNodeID, EventType, 0);
Sleep(2);//延时极其重要,不然会出错,导致第一次接收的是上一次的最后一个弹道数据
return result;
}
RFM2G_STATUS RFM_Card_Operate::WaitForEvent()
{
RFM2G_STATUS result = RFM2gWaitForEvent(Handle, &EventInfo_Receive);
/* Got the interrupt, see who sent it */
OhterNodeID = EventInfo_Receive.NodeId;
return result;
}
RFM2G_STATUS RFM_Card_Operate::RFM_Read_Missle(struct MissilePosInfo &inbuffer)
{
RFM2G_STATUS result = RFM2gRead(Handle, OFFSET_RD, (void *)&inbuffer, sizeof(struct MissilePosInfo));
return result;
}
RFM_Card_Operate::~RFM_Card_Operate()//反射内存卡初始化函数,初始化Handle句柄等参数
{
//Disable中断
RFM_Card_DisableEvent();
//关闭反射内存卡
RFM2gClose(&Handle);
}
// 判断弹道结构体数据是否相等
int RFM_Card_Operate::StructCMP(struct MissilePosInfo Para1, struct MissilePosInfo Para2)
{
#ifdef DEBUG_MissStruct80Bytes //采用80Bytes的弹道结构体
if (Para1.CurrentTime == Para2.CurrentTime &&
Para1.Position[0] == Para2.Position[0] &&
Para1.Position[1] == Para2.Position[1] &&
Para1.Position[2] == Para2.Position[2] &&
Para1.Velocity[0] == Para2.Velocity[0] &&
Para1.Velocity[1] == Para2.Velocity[1] &&
Para1.Velocity[2] == Para2.Velocity[2] &&
Para1.Acceleration[0] == Para2.Acceleration[0] &&
Para1.Acceleration[1] == Para2.Acceleration[1] &&
Para1.Acceleration[2] == Para2.Acceleration[2] &&
Para1.theta == Para2.theta &&
Para1.psi == Para2.psi &&
Para1.gamma == Para2.gamma &&
Para1.sOmegaX1 == Para2.sOmegaX1 &&
Para1.sOmegaY1 == Para2.sOmegaY1 &&
Para1.sOmegaZ1 == Para2.sOmegaZ1 &&
Para1.sTheta == Para2.sTheta &&
Para1.sAlpha == Para2.sAlpha &&
Para1.sSigma == Para2.sSigma &&
Para1.counter == Para2.counter
)//结构体相等返回1
return 1;
else//结构体不相等返回0
return 0;
#elif defined DEBUG_MissStruct520Bytes //采用520Bytes的弹道结构体
if ((fabs(Para1.CurrentTime - Para2.CurrentTime) < 0.0000001) &&
(fabs(Para1.Position[0] - Para2.Position[0]) < 0.0000001) &&
(fabs(Para1.Position[1] - Para2.Position[1]) < 0.0000001) &&
(fabs(Para1.Position[2] - Para2.Position[2]) < 0.0000001) &&
(fabs(Para1.Velocity[0] - Para2.Velocity[0]) < 0.0000001) &&
(fabs(Para1.Velocity[1] - Para2.Velocity[1]) < 0.0000001) &&
(fabs(Para1.Velocity[2] - Para2.Velocity[2]) < 0.0000001) &&
(fabs(Para1.Acceleration[0] - Para2.Acceleration[0]) < 0.0000001) &&
(fabs(Para1.Acceleration[1] - Para2.Acceleration[1]) < 0.0000001) &&
(fabs(Para1.Acceleration[2] - Para2.Acceleration[2]) < 0.0000001) &&
(fabs(Para1.theta - Para2.theta) < 0.0000001) &&
(fabs(Para1.psi - Para2.psi) < 0.0000001) &&
(fabs(Para1.gamma - Para2.gamma) < 0.0000001) &&
(fabs(Para1.sOmegaX1 - Para2.sOmegaX1) < 0.0000001) &&
(fabs(Para1.sOmegaY1 - Para2.sOmegaY1) < 0.0000001) &&
(fabs(Para1.sOmegaZ1 - Para2.sOmegaZ1) < 0.0000001) &&
(fabs(Para1.sTheta - Para2.sTheta) < 0.0000001) &&
(fabs(Para1.sAlpha - Para2.sAlpha) < 0.0000001) &&
(fabs(Para1.sSigma - Para2.sSigma) < 0.0000001) &&
(fabs(Para1.uiWaveWid - Para2.uiWaveWid) < 0.0000001) &&
(fabs(Para1.uiApcHight - Para2.uiApcHight) < 0.0000001) &&
(memcmp(Para1.Rsvd, Para2.Rsvd, sizeof(short) * (256 - 42)) == 0) &&//比较int数组是否相等
(Para1.usDataFlag == Para2.usDataFlag) &&
(Para1.usDataValid == Para2.usDataValid) &&
(Para1.counter == Para2.counter) &&
(Para1.usSumCheck == Para2.usSumCheck)
)//结构体相等返回1
return 1;
else//结构体不相等返回0
return 0;
#endif
}
<file_sep>/FuncModule/CPlusPlus/ThreadPool/FuncTask.h
#pragma once
#include "task.h"
class CFuncask :
public CTask
{
public:
CFuncask(int id);
~CFuncask(void);
public:
void SetTaskFunc(std::function<BOOL()> func);
virtual void taskProc();
private:
std::function<BOOL()> m_fun;
};
<file_sep>/FuncModule/CPlusPlus/ACMCoder/ACMCoder/main.cpp
#include<iostream>
#include<cmath>
#include <iomanip>
using namespace std;
extern int SortInputString();
extern int TwoPointDis();
int main()
{
SortInputString();
TwoPointDis();
return 0;
}<file_sep>/Project/Python/DeepInsight/que_3.py
import numpy as np
import math
import sys
MAX = 1e10
INIFI_POINT = [MAX,MAX]
r = 0
iPoint = [0]*50
jPoint = [0]*50
#calculate Euclidean distance
def Cal_Dis(point1,point2):
return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)
def IsReachable(ReachablePoints,LeftPoints):
print(ReachablePoints)
print(LeftPoints)
if len(ReachablePoints) == 0:
return 0
for point in ReachablePoints:
if Cal_Dis(point,jPoint) < r:
return 1
temp = ReachablePoints
ReachablePoints = []
#delIndex = []
for i in range(len(temp)):
for j in range(len(LeftPoints)):
print("i,j=%d,%d"%(i,j))
if LeftPoints[j] != INIFI_POINT and Cal_Dis(temp[i],LeftPoints[j]) < r:
if LeftPoints[j] == jPoint:
return 1
else:
ReachablePoints.append(LeftPoints[j])
LeftPoints[j] = INIFI_POINT
#delIndex.append(j)
temp1 = []
for left in LeftPoints:
if left != INIFI_POINT:
temp1.append(left)
LeftPoints = temp1
return IsReachable(ReachablePoints, LeftPoints)
#main
print("Please input points set txt file name(like \"data.txt\"):")
fileName = ""
if sys.version > '3':
fileName = input()
else:
fileName = raw_input()
file = open(fileName)
lines = file.readlines()
Input=[]
for line in lines:
temp = line.replace('\n','').split(',')
Input.append([float(temp[0]),float(temp[1])])
print(Input)
print("Please input r:")
if sys.version > '3':
r = float(input())
else:
r = input()
print ("Please input i(like \"[0,0\"):")
if sys.version > '3':
temp = input()
temp = temp.replace("[","").replace("]","").split(",")
iPoint = [float(temp[0]),float(temp[1])]
else:
iPoint = input()
print ("Please input j(like \"[1,1]\"):")
if sys.version > '3':
temp = input()
temp = temp.replace("[","").replace("]","").split(",")
jPoint = [float(temp[0]),float(temp[1])]
else:
jPoint = input()
Input.append(jPoint)
bReachable = IsReachable([iPoint], Input)
if bReachable == 1:
print("(%d,%d) has at least a path to (%d,%d)!"%(iPoint[0],iPoint[1],jPoint[0],jPoint[1]))
else:
print("ops, no path was found!")
<file_sep>/CodingPartner/Coding_Partner.py
'''
FileName: CodingPartner
Create Time: 2015/08
Modify Time:
Author: <NAME>
Owner: <NAME>
Place: Shanghai Jiao Tong University, Min Hang district.
Reference:
Description: (1)Can based on document ReadMe.txt record, according to the keywords to search the corresponding code path, convenient query and management of files
'''
__author__ = 'JD'
#Main Function
from tkinter import *
import subprocess
import os
import sys,os
from tkinter import * #when use realted module, we need to import the realted package
from tkinter.messagebox import *
from datetime import *
import shutil #delete directory recursively related
import shutil, errno
from tkinter import * #when use realted module, we need to import the realted package
from tkinter.ttk import * #Combobox
from tkinter import filedialog
AbsolutePath = ""
###################Text File Path in FuncModule####################
#C
Path_FuncModule_C= ""
#CPlusPlus
Path_FuncModule_CPlusPlus= ""
#CSharp
Path_FuncModule_CSharp= ""
#HTML_CSS
Path_FuncModule_HTML_CSS= ""
#Matlab
Path_FuncModule_Matlab= ""
#Python
Path_FuncModule_Python= ""
#SQL
Path_FuncModule_SQL= ""
###################Text File Path in Project##########################
#C
Path_Project_C= ""
#CPlusPlus
Path_Project_CPlusPlus= ""
#CSharp
Path_Project_CSharp= ""
#HTML_CSS
Path_Project_HTML_CSS= ""
#Matlab
Path_Project_Matlab= ""
#Python
Path_Project_Python= ""
#SQL
Path_Project_SQL= ""
########################### Path List ###############################
Path_FuncModule= ""
Path_Project= ""
Path_FuncModule_txt= ""
Path_Project_txt= ""
#Three Path Lists
RootPathList= ""
FuncModulePathList= ""
ProjectPathList= ""
ProjectPathList = ""
def Path_Assig_Value():
###################Text File Path in FuncModule####################
#C
global AbsolutePath
temp_AbsolutePath = AbsolutePath
global Path_FuncModule_C
Path_FuncModule_C = temp_AbsolutePath + "FuncModule/C/Record.txt"
#CPlusPlus
global Path_FuncModule_CPlusPlus
Path_FuncModule_CPlusPlus = temp_AbsolutePath+"FuncModule/CPlusPlus/Record.txt"
#CSharp
global Path_FuncModule_CSharp
Path_FuncModule_CSharp = temp_AbsolutePath+"FuncModule/CSharp/Record.txt"
#HTML_CSS
global Path_FuncModule_HTML_CSS
Path_FuncModule_HTML_CSS = temp_AbsolutePath+"FuncModule/HTML_CSS/Record.txt"
#Matlab
global Path_FuncModule_Matlab
Path_FuncModule_Matlab = temp_AbsolutePath+"FuncModule/Matlab/Record.txt"
#Python
global Path_FuncModule_Python
Path_FuncModule_Python = temp_AbsolutePath+"FuncModule/Python/Record.txt"
#SQL
global Path_FuncModule_SQL
Path_FuncModule_SQL = temp_AbsolutePath+"FuncModule/SQL/Record.txt"
###################Text File Path in Project##########################
#C
global Path_Project_C
Path_Project_C = temp_AbsolutePath+"Project/C/Record.txt"
#CPlusPlus
global Path_Project_CPlusPlus
Path_Project_CPlusPlus = temp_AbsolutePath+"Project/CPlusPlus/Record.txt"
#CSharp
global Path_Project_CSharp
Path_Project_CSharp = temp_AbsolutePath+"Project/CSharp/Record.txt"
#HTML_CSS
global Path_Project_HTML_CSS
Path_Project_HTML_CSS = temp_AbsolutePath+"Project/HTML_CSS/Record.txt"
#Matlab
global Path_Project_Matlab
Path_Project_Matlab = temp_AbsolutePath+"Project/Matlab/Record.txt"
#Python
global Path_Project_Python
Path_Project_Python =temp_AbsolutePath+ "Project/Python/Record.txt"
#SQL
global Path_Project_SQL
Path_Project_SQL = temp_AbsolutePath+"Project/SQL/Record.txt"
########################### Path List ###############################
global Path_FuncModule
Path_FuncModule =temp_AbsolutePath+ "FuncModule/"
global Path_Project
Path_Project = temp_AbsolutePath+"Project/"
global Path_FuncModule_txt
Path_FuncModule_txt = temp_AbsolutePath+"FuncModule/Record.txt"
global Path_Project_txt
Path_Project_txt = temp_AbsolutePath+"Project/Record.txt"
#Three Path Lists
global RootPathList
RootPathList = [Path_FuncModule_txt,Path_Project_txt]
global FuncModulePathList
FuncModulePathList = [Path_FuncModule_C,Path_FuncModule_CPlusPlus, Path_FuncModule_CSharp, Path_FuncModule_HTML_CSS, Path_FuncModule_Matlab, Path_FuncModule_Python,Path_FuncModule_SQL]
global ProjectPathList
ProjectPathList = [Path_Project_C,Path_Project_CPlusPlus, Path_Project_CSharp, Path_Project_HTML_CSS, Path_Project_Matlab, Path_Project_Python,Path_Project_SQL]
#Add, Delete, Modify and Query the txt file under FuncModule directory and Project directory
###################################### Manage Directory #########################################
#Add
def ManageDirectory_Add(object,Type, Code_Type):
if Type == "":
object.wm_attributes("-topmost", 0)
showwarning("Warning","\'Type\'"+" can't be null")#show a warning MessageBox
object.wm_attributes("-topmost", 1)
return
Type_Dict = {"Function Module": Path_FuncModule,"Project": Path_Project} #Map Type to related directory
Code_Type_Dict = {"C++": "CPlusPlus","Java": "Java","Python": "Python","C#": "CSharp","SQL": "SQL","Html/CSS": "HTML_CSS","C_Lang": "C_Lang","Matlab": "Matlab"} #Map Code Type to related directory
Add_Code_Type_Pairs(Code_Type_Dict, Code_Type)
Type_Dir = ''
if Type in Type_Dict:
Type_Dir = Type_Dict[Type]
else:
Type_Dir = AbsolutePath + Type
#Judge whether Type directory exists
if os.path.exists(Type_Dir):#Type directory exists
#Judge whether Code_Type directory exists further
Code_Type_Dir = ''
temp_Dir = Type_Dict[Type] if Type in Type_Dict else Type
if Code_Type == "":
Code_Type_Dir = temp_Dir
elif Code_Type in Code_Type_Dict:
Code_Type_Dir = temp_Dir + Code_Type_Dict[Code_Type]
else:
Code_Type_Dir = temp_Dir + Code_Type
if os.path.exists(Code_Type_Dir):#Type directory exists
if Code_Type == "":#Code Type directory does not exist
object.wm_attributes("-topmost", 0)
showwarning("Warning","\'"+Type+"\'"+" directory exists")#show a warning MessageBox
object.wm_attributes("-topmost", 1)
else:
object.wm_attributes("-topmost", 0)
showwarning("Warning","\'"+Code_Type_Dict[Code_Type]+"\'"+" directory exists")#show a warning MessageBox
object.wm_attributes("-topmost", 1)
else:#Code Type directory does not exist
object.wm_attributes("-topmost", 0)
Create_Code_Type_Direcotry(Type, Type_Dir, Code_Type_Dict[Code_Type] if (Code_Type in Code_Type_Dict) else Code_Type, Code_Type_Dir)#create Record.txt
showinfo("Success","\'"+ Code_Type +"\'"+" directory was created")
object.wm_attributes("-topmost", 1)
else:#Type directory does not exist
object.wm_attributes("-topmost", 0)
Create_Type_Direcotry(Type, Type_Dir)#create Record.txt
showinfo("Success","\'"+ Type +"\'"+" directory was created")
object.wm_attributes("-topmost", 1)
def Create_Code_Type_Direcotry(Type, Type_Dir, Code_Type, Dir):#create related directory in directory Dir(decided by TypeorCode_Type variable) and Record.txt
os.mkdir(Dir)#create directory
Init_buffer = Type+"-"+Code_Type+"总纲领每添加一个功能模块代码,更新该文档。切记,要维护好本源码功能快速定位功能,需要每次更新完代码后都要实时更新该文本。\n****************************************"+Code_Type+"****************************************************\n标准记录格式:序号-日期:中英文关键字;\n"+"1-"+("%s"%date.today()).replace('-', '')+":Init\n"
with open(os.path.join(Dir, "Record.txt"), 'wt') as Record_file:
Record_file.write(Init_buffer)
Type_Init_Buffer = "\n****************************************"+Code_Type+"****************************************************\n"+"1-"+("%s"%date.today()).replace('-', '')+":Init\n"
with open(os.path.join(Type_Dir, "Record.txt"), 'at+') as Record_file:
Record_file.write(Type_Init_Buffer)
def Create_Type_Direcotry(Type, Dir):#create related directory in directory Dir(decided by TypeorCode_Type variable) and Record.txt
os.mkdir(Dir)#create directory
Init_buffer = Type+"总纲领\n总纲领每次当更新一次源代码的时候除了在其所属文件夹更新ReadMe记录信息外,还需要更新本文档的记录信息,\n这样的话每次查询需要的代码模块的时候就可以按照以下方式快速定位需要寻找的代码模块或者功能:\n=====================1.在本文档用Ctrl+F寻找关键字(单词,中文关键字),定位该功能在哪个语言版本中存在=================================================\n=====================2.根据1的结果到相应的文件夹中的ReadMe文件中用Ctrl+F寻找代码功能模块源码所属文件夹=================================================\n切记,要维护好本源码功能快速定位功能,需要每次更新完代码后都要实时更新该文本。\n"
with open(os.path.join(Dir, "Record.txt"), 'wt') as Record_file:
Record_file.write(Init_buffer)
def Add_Code_Type_Pairs(Dict, Code_Type):
if Code_Type not in Dict:
Dict[Code_Type] = Code_Type
#Delete
def ManageDirectory_Delete(object,Type, Code_Type):
if Type == "":
object.wm_attributes("-topmost", 0)
showwarning("Warning","\'Type\'"+" can't be null")#show a warning MessageBox
object.wm_attributes("-topmost", 1)
return
Type_Dict = {"Function Module": Path_FuncModule,"Project": Path_Project} #Map Type to related directory
Code_Type_Dict = {"C++": "CPlusPlus","Java": "Java","Python": "Python","C#": "CSharp","SQL": "SQL","Html/CSS": "HTML_CSS","C_Lang": "C_Lang","Matlab": "Matlab"} #Map Code Type to related directory
Type_Dir = ''
if Type in Type_Dict:
Type_Dir = Type_Dict[Type]
else:
global AbsolutePath
Type_Dir = AbsolutePath + Type
Add_Code_Type_Pairs(Code_Type_Dict, Code_Type)
#Judge whether Type directory exists
if os.path.exists(Type_Dir):#Type directory exists
#Judge whether Code_Type directory exists further
Code_Type_Dir = ''
Code_Type_Dir = Type_Dir + Code_Type_Dict[Code_Type] if Code_Type in Code_Type_Dict else Type_Dir + Code_Type
if os.path.exists(Code_Type_Dir) and Code_Type != "":#Code Type directory exists
object.wm_attributes("-topmost", 0)
result = askyesno("Caution","Do you really want to delete %s?"%Code_Type)
if result == True:
shutil.rmtree(Code_Type_Dir)#delete directory
Delete_Dir_RenewRecordtxt(Type_Dir, Code_Type)#delete related record in file Record.txt
showinfo("Success","\'"+ Code_Type_Dir +"\'"+" directory was deleted")
object.wm_attributes("-topmost", 1)
else:
object.wm_attributes("-topmost", 1)
elif Code_Type == "":#Code Type directory does not exist
object.wm_attributes("-topmost", 0)
result = askyesno("Caution","Do you really want to delete %s?"%Type)
if result == True:
shutil.rmtree(Type_Dir)
showinfo("Success","\'"+ Type_Dir +"\'"+" directory was deleted")
object.wm_attributes("-topmost", 1)
else:
object.wm_attributes("-topmost", 1)
else:
object.wm_attributes("-topmost", 0)
showwarning("Warning","\'"+Code_Type_Dir+"\'"+" directory does not exist")#show a warning MessageBox
object.wm_attributes("-topmost", 1)
else:#Type directory does not exist
object.wm_attributes("-topmost", 0)
showwarning("Warning","\'"+Type+"\'"+" directory does not exist")#show a warning MessageBox
object.wm_attributes("-topmost", 1)
def Delete_Dir_RenewRecordtxt(Type_Dir, Code_Type):#create related directory in directory Dir(decided by TypeorCode_Type variable) and Record.txt
Code_Type_Dict = {"C++": "CPlusPlus","Java": "Java","Python": "Python","C#": "CSharp","SQL": "SQL","Html/CSS": "HTML_CSS","C_Lang": "C_Lang","Matlab": "Matlab"} #Map Code Type to related directory
Record_txt = Type_Dir + "Record.txt"
fid = open(Record_txt,"r")
lines = fid.readlines()
fid.close()
fid = open(Record_txt,"wt")
#locate if the postion of keyword is between two "*" realted line
endflag = 0#0 means the keyword related record is last record
KeywordPos = float("inf")#represent infinity, no numbers in python larger than this number
CurPos = 0
for line in lines:
Keywordindex = line.find(Code_Type_Dict[Code_Type] if Code_Type in Code_Type_Dict else Code_Type)
CurPos = CurPos + len(line)
Otherindex = line.find('*')
count = 0
count = CntStarCharinLine(line)
if Keywordindex != -1:#keyword line
KeywordPos = Keywordindex + CurPos
elif CurPos + Otherindex > KeywordPos and count >= 20:
endflag = 1
#write the text back to file except content to be deleted
writeflag = 1
CurPos = 0
KeywordPos = float("inf")
for line in lines:
count = 0
CurPos = CurPos + len(line)
count = CntStarCharinLine(line)#decide the deletion end position
if line.find(Code_Type_Dict[Code_Type] if Code_Type in Code_Type_Dict else Code_Type) == -1 and writeflag == 1:#ahead keyword record
fid.write(line)
elif count >= 20 and CurPos + line.find('*') > KeywordPos:#after keyword line
fid.write(line)
writeflag = 1
elif line.find(Code_Type_Dict[Code_Type] if Code_Type in Code_Type_Dict else Code_Type) != -1:#keyword line
if endflag == 1:
writeflag = 0
KeywordPos = CurPos + line.find(Code_Type_Dict[Code_Type] if Code_Type in Code_Type_Dict else Code_Type)
continue
else:
break
fid.close()
def CntStarCharinLine(line):
count = 0
for char in line:
if char == '*':
count += 1
return count
##################################### Manage Record ##########################################
#Add Button
def copytree(src, dst, symlinks=False, ignore=None):
Dir_Name = src.split('/')
Dir_Name = Dir_Name[-1]
dst += "/" + Dir_Name
if not os.path.exists(dst):
os.makedirs(dst)
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.isdir(s):
copytree(s, d, symlinks, ignore)
else:
if not os.path.exists(d) or os.stat(s).st_mtime - os.stat(d).st_mtime > 1:
shutil.copy2(s, d)
def ManageRecord_Add_RenewRecordtxt(Code_Type, Type_Dir,Code_Type_Dir, Description, Keywords,DirPath, FilePath):
CodeType_RecordPath = Code_Type_Dir + "/Record.txt"
# RecordFileName = ""#used to store as file name in Record.txt
# if os.path.exists(DirPath) and DirPath != "":
# RecordFileName = Code_Type_Dir + "/" + DirPath.split('/')[-1] + "/" + FilePath.split('/')[-1]
fid = open(CodeType_RecordPath,"r")
lines = fid.readlines()
fid.close()
#Renew Record.txt under Code Type directory
#Get last record's index and date
index_data_record = ""
for line in reversed(lines):
if line != '\n':
index_data_record = line
break
index_data_record = index_data_record.split('-')
index = str(int(index_data_record[0]) + 1)
#Renew Record.txt under Type directory
fid = open(CodeType_RecordPath,"at")
record = ""
if os.path.exists(DirPath) and DirPath != "":
record = index + "-" + ("%s"%date.today()).replace('-', '') + ":" + "增加了Directory>" + DirPath.split('/')[-1] + ">" + FilePath.split('/')[-1] +">" + Description + "关键字:" + Keywords
else:
record = index + "-" + ("%s"%date.today()).replace('-', '') + ":" + "增加了File>" +FilePath.split('/')[-1] +">" + Description + "关键字:" + Keywords
record = record+"\n"
fid.write(record)
fid.close()
#Renew Record.txt under Type directory
Code_Type_Dict = {"C++": "CPlusPlus","Java": "Java","Python": "Python","C#": "CSharp","SQL": "SQL","Html/CSS": "HTML_CSS","C_Lang": "C_Lang","Matlab": "Matlab"} #Map Code Type to related directory
Type_Record_txt = Type_Dir + "Record.txt"
#locate if the postion of keyword is between two "*" realted line
fid = open(Type_Record_txt,"r")
lines = fid.readlines()
fid.close()
endflag = 0#0 means the keyword related record is last record
KeywordPos = float("inf")#represent infinity, no numbers in python larger than this number
CurPos = 0
for line in lines:
Keywordindex = line.find(Code_Type_Dict[Code_Type] if Code_Type in Code_Type_Dict else Code_Type)
CurPos = CurPos + len(line)
Otherindex = line.find('*')
count = 0
count = CntStarCharinLine(line)
if Keywordindex != -1:#keyword line
KeywordPos = Keywordindex + CurPos
elif CurPos + Otherindex > KeywordPos and count >= 20:
endflag = 1
fid = open(Type_Record_txt,"at")
if endflag == 0:
fid.write(record+"\n")
fid.close()
return
fid = open(Type_Record_txt,"wt")
#write the text back to file except content to be deleted
writeflag = 0
CurPos = 0
KeywordPos = float("inf")
for line in lines:
count = 0
CurPos = CurPos + len(line)
count = CntStarCharinLine(line)#decide the deletion end position
if line.find(Code_Type_Dict[Code_Type] if Code_Type in Code_Type_Dict else Code_Type) == -1:#except keyword record line
if count >= 20 and CurPos + line.find('*') > KeywordPos and writeflag == 1:#after keyword line
fid.write(record)
fid.write("\n" + line)
writeflag = 0
else:
fid.write(line)
elif line.find(Code_Type_Dict[Code_Type] if Code_Type in Code_Type_Dict else Code_Type) != -1:#keyword line
if endflag == 1:
writeflag = 1
KeywordPos = CurPos + line.find(Code_Type_Dict[Code_Type] if Code_Type in Code_Type_Dict else Code_Type)
fid.write(line)
fid.close()
def ManageRecord_Add(object,Type, Code_Type, Description, Keywords, DirPath, FilePath):
if Type == "" or Code_Type == "" or Description == "" or Keywords == "" or FilePath == "" or not os.path.exists(FilePath):
object.wm_attributes("-topmost", 0)
showerror("Parameter Error", "Please configure parameters correctly!")
object.wm_attributes("-topmost", 1)
return
if ":" in Description:
object.wm_attributes("-topmost", 0)
showwarning("Warning","\'"+"Description" +"\'" + " can't contain colon(:), please write it like" + " \'" + "description1;description2; " +"\'")#show a warning MessageBox
object.wm_attributes("-topmost", 1)
return
if ":" in Keywords:
object.wm_attributes("-topmost", 0)
showwarning("Warning","\'"+"Keywords" +"\'" + " can't contain colon(:), please write it like" + " \'" + "keyword1;keyword2; " +"\'")#show a warning MessageBox
object.wm_attributes("-topmost", 1)
return
#Functions of this function:
#(1)Refer to Type and Code_Type, find the Code Type directory,copy related directory or file and..
#(2) add record to Record.txt under found directory;
#(3)Refer to Type, find the Type directory, add record to Record.txt under the directory.
Type_Dict = {"Function Module": Path_FuncModule,"Project": Path_Project} #Map Type to related directory
Code_Type_Dict = {"C++": "CPlusPlus","Java": "Java","Python": "Python","C#": "CSharp","SQL": "SQL","Html/CSS": "HTML_CSS","C_Lang": "C_Lang","Matlab": "Matlab"} #Map Code Type to related directory
Add_Code_Type_Pairs(Code_Type_Dict, Code_Type)
Type_Dir = ''
if Type in Type_Dict:
Type_Dir = Type_Dict[Type]
else:
global AbsolutePath
Type_Dir = AbsolutePath + Type
Code_Type_Dir = ''
temp_Dir = Type_Dict[Type] if Type in Type_Dict else Type
if Code_Type == "":
Code_Type_Dir = temp_Dir+ "/"
elif Code_Type in Code_Type_Dict:
Code_Type_Dir = temp_Dir + Code_Type_Dict[Code_Type]+ "/"
else:
Code_Type_Dir = temp_Dir + Code_Type+ "/"
#As (1) listed before
if os.path.exists(DirPath) and os.path.exists(FilePath):
copytree(DirPath, Code_Type_Dir)
object.wm_attributes("-topmost", 0)
showinfo("Success","\'"+ DirPath +"\'"+" directory was copied")
object.wm_attributes("-topmost", 1)
elif ~os.path.exists(DirPath) and os.path.exists(FilePath):
shutil.copy2(FilePath, Code_Type_Dir)
object.wm_attributes("-topmost", 0)
showinfo("Success","\'"+ FilePath +"\'"+" file was copied")
object.wm_attributes("-topmost", 1)
else:
showwarning("Warning","Directory or File path illegal")#show a warning MessageBox
#As (2),(3) listed before
ManageRecord_Add_RenewRecordtxt(Code_Type, Type_Dir, Code_Type_Dir, Description,Keywords, DirPath, FilePath)
#Delete Button
def ManageRecord_Delete(object_frm_Manage_Record,Keyword_Query, object_Combobox_Index, object_entry_Description_Delete, object_entry_Keywords_Delete, object_entry_Dir_Path_Delete, object_entry_File_Path_Delete, index_list, description_list, keywords_list, DirPath_list, FilePath_list, MatchedRecordStr):
#the code here can refer to KeywordQuery, query result can store in parameters and return to calling function
#query the result refer to keyword and store results into index_list to FilePath_list below.
index_list.clear()
description_list.clear()
keywords_list.clear()
DirPath_list.clear()
FilePath_list.clear()
MatchedRecordStr.clear()
KeywordQuery_DeleteRecord(Keyword_Query,index_list, description_list, keywords_list, DirPath_list, FilePath_list, MatchedRecordStr)
#as default, we display the first index on UI
if index_list:
object_Combobox_Index['value'] = ""
object_Combobox_Index['value'] = (index_list)
object_Combobox_Index.set(index_list[0])
if description_list:
object_entry_Description_Delete.delete(0, END)
object_entry_Description_Delete.insert(0, description_list[index_list[0]])
if keywords_list:
object_entry_Keywords_Delete.delete(0, END)
object_entry_Keywords_Delete.insert(0, keywords_list[index_list[0]])
if DirPath_list:
object_entry_Dir_Path_Delete.delete(0, END)
object_entry_Dir_Path_Delete.insert(0, DirPath_list[index_list[0]])
if FilePath_list:
object_entry_File_Path_Delete.delete(0, END)
object_entry_File_Path_Delete.delete(0, END)
object_entry_File_Path_Delete.insert(0, FilePath_list[index_list[0]])
def KeywordQuery_DeleteRecord(keyword, index_list, description_list, keywords_list, DirPath_list, FilePath_list,MatchedRecordStr):
global AbsolutePath
TypeDirList = []
CodeTypeDirList = []
TraveringTypeCodeTypeFiles(TypeDirList,CodeTypeDirList)
rootpathlist = []
for TypeDir in TypeDirList:
rootpathlist.append(AbsolutePath + TypeDir + "/Record.txt")
#Traverse rootpathlist with KeyWord
MatchedRecordStr_temp = []
if len(keyword) == 0:#if keyword is space, program will return
return
#Split Keyword by space
keyword = ' '.join(keyword.split())
keyword = keyword.split(' ')
ResultList = []
QueriedResultCounts = 0
for RootPath in rootpathlist:#Used to read the two root text file
handle = open(RootPath, 'r')#Open File and Read text
#The next three variables is very important!
index = [] #used to store the file position of the "keyword" and paried string Str_Language = []
Str_index = []#the string of where keyword belongs to.
index_Language = {"index_C_Lang": 0,"index_CplusPlus": 0, "index_Csharp": 0, "index_Python": 0, "index_SQL": 0, "index_HTML_CSS": 0, "index_Matlab": 0, "index_Java": 0} #Used to store the current file position of each language index, like "CPlusPlus" and so on.
DirectoryOrFileName = [] #used to store the directory discribed in keyword
Curr_Pos = 0#Current file postion in the text file
for eachLine in handle:#Traverse the text in file and calculate the value of variable "index" and "index_Language"
tempindex = -1
for keyword_item in keyword:
tempindex = eachLine.find(keyword_item)
if tempindex != -1:
continue
else:
break
tempindex1 = tempindex + Curr_Pos
if tempindex != -1:
index.append(tempindex1)#Add the keyword's position in index list
MatchedRecordStr_temp.append(eachLine)
Str_index.append(eachLine)
tempstr = eachLine.split('>')
if len(tempstr) >= 4:
DirectoryOrFileName.append(tempstr[1] + "\\" + tempstr[2]) #The code directory related to keyword
elif len(tempstr) >= 2:
DirectoryOrFileName.append(tempstr[1]) #The code directory related to keyword
else:
DirectoryOrFileName.append("")
count = 0
for i in index:
if RootPath == Path_FuncModule_txt:
for TypeDir in TypeDirList:
for CodeTypeDir in CodeTypeDirList:
Path = AbsolutePath.replace('/', '\\')+ TypeDir + "\\" +CodeTypeDir+ "\\"+ DirectoryOrFileName[count]
if os.path.exists(Path):
ResultList.append(Str_index[count]+"\n PATH: " + Path+"\n")
count = count + 1
else:
for TypeDir in TypeDirList:
for CodeTypeDir in CodeTypeDirList:
Path = AbsolutePath.replace('/', '\\')+ TypeDir + "\\" +CodeTypeDir+ "\\"+ DirectoryOrFileName[count]
if os.path.exists(Path):
ResultList.append(Str_index[count]+"\n PATH: " + Path+ "\n")
count = count + 1
QueriedResultCounts = QueriedResultCounts + count
temp_Count = 0
for querieditems in ResultList: #display the queried result in entry control of GUI
FileName = ""
Description = ""
Splitof_colon = querieditems.split(':')
index_list.append(Splitof_colon[0])
Description = str.replace(Splitof_colon[1],"关键字","",1).split('>')
FileType = str.replace(Description[0],"增加了","",1)
if FileType == "Directory" and len(Description) >= 4:
FileName = Description[2]
Description = Description[3]
elif len(Description) >= 3:
FileName = Description[1]
Description = Description[2]
description_list[Splitof_colon[0]] = Description
Keyword = str.replace(Splitof_colon[2],"PATH","",1)
keywords_list[Splitof_colon[0]] = Keyword
Path = ""
if len(Splitof_colon) >= 5:
Path = Splitof_colon[3] + ":" + Splitof_colon[4]
Path = str.replace(Path, "\n", "",1)
Path = str.replace(Path, " ", "")
FilePath_list[Splitof_colon[0]] = Path
if FileType == "Directory":
if '.' in Path:
Path = str.replace(Path, FileName, "",1)
Path = str.replace(Path, "\n", "",1)
Path = str.replace(Path, " ", "")
Path = Path[::-1].replace("\\","",1)[::-1]
DirPath_list[Splitof_colon[0]] = Path
else:
DirPath_list[Splitof_colon[0]] = "\n"
MatchedRecordStr[Splitof_colon[0]] = MatchedRecordStr_temp[temp_Count]
temp_Count += 1
##################################### Query ##########################################
#First, Query text file just under FuncModule directory and Project directory, and query next layer directory based on result queried in FuncModule and Project directory
def TraveringTypeCodeTypeFiles(TypeDirList, CodeTypeDirList):
# Manage_Dir_GUI.cmbEditComboList_Code_Type = self.Combobox_Code_Type.get()
global AbsolutePath
Dirs = [d for d in os.listdir(AbsolutePath) if os.path.isdir((os.path.join(AbsolutePath,d)))]#list only the directory under given directory
if '.git' in Dirs:
Dirs.remove('.git')
if 'CodingPartner' in Dirs:
Dirs.remove('CodingPartner')
for dir in Dirs:
TypeDirList.append(dir)
# Manage_Dir_GUI.cmbEditComboList_Code_Type = self.Combobox_Code_Type.get()
Type_Dict = {"Function Module": Path_FuncModule,"Project": Path_Project} #Map Type to related directory
cmbEditComboList_Code_Type_Const = {"CPlusPlus": "C++","Java": "Java","Python": "Python","CSharp": "C#","SQL": "SQL","HTML_CSS": "Html/CSS","C_Lang": "C_Lang","Matlab": "Matlab"}
TypeDirMap = {"Function Module":"FuncModule", "Project":"Project"}
Dirs = []
for dir in TypeDirList:
TypeDir = os.path.join(AbsolutePath, TypeDirMap[dir] if dir in TypeDirMap else dir)
Dirs = [d for d in os.listdir(TypeDir) if os.path.isdir(os.path.join(TypeDir,d))]#list only the directory under given directory
for dir in Dirs:
CodeTypeDirList.append(dir)
def KeywordQuery(keyword, Text_result_control):
global AbsolutePath
TypeDirList = []
CodeTypeDirList = []
TraveringTypeCodeTypeFiles(TypeDirList,CodeTypeDirList)
rootpathlist = []
for TypeDir in TypeDirList:
rootpathlist.append(AbsolutePath + TypeDir + "/Record.txt")
#clear the Text
Text_result_control.delete(0.0, END) #based on the package imported at the topmost of this page, namely tkinter
#Traverse rootpathlist with KeyWord
if len(keyword) == 0:#if keyword is space, program will return
return
#Split Keyword by space
keyword = ' '.join(keyword.split())
keyword = keyword.split(' ')
ResultList = []
QueriedResultCounts = 0
for RootPath in rootpathlist:#Used to read the two root text file
handle = open(RootPath, 'r')#Open File and Read text
#The next three variables is very important!
index = [] #used to store the file position of the "keyword" and paried string Str_Language = []
Str_index = []#the string of where keyword belongs to.
index_Language = {"index_C_Lang": 0,"index_CplusPlus": 0, "index_Csharp": 0, "index_Python": 0, "index_SQL": 0, "index_HTML_CSS": 0, "index_Matlab": 0, "index_Java": 0} #Used to store the current file position of each language index, like "CPlusPlus" and so on.
DirectoryOrFileName = [] #used to store the directory discribed in keyword
Curr_Pos = 0#Current file postion in the text file
for eachLine in handle:#Traverse the text in file and calculate the value of variable "index" and "index_Language"
tempindex = -1
for keyword_item in keyword:
tempindex = eachLine.find(keyword_item)
if tempindex != -1:
continue
else:
break
tempindex1 = tempindex + Curr_Pos
if tempindex != -1:
index.append(tempindex1)#Add the keyword's position in index list
Str_index.append(eachLine)
tempstr = eachLine.split('>')
if len(tempstr) >= 4:
DirectoryOrFileName.append(tempstr[1] + "\\" + tempstr[2]) #The code directory related to keyword
elif len(tempstr) >= 2:
DirectoryOrFileName.append(tempstr[1]) #The code directory related to keyword
else:
DirectoryOrFileName.append("")
count = 0
for i in index:
if RootPath == Path_FuncModule_txt:
for TypeDir in TypeDirList:
for CodeTypeDir in CodeTypeDirList:
Path = AbsolutePath.replace('/', '\\')+ TypeDir + "\\" +CodeTypeDir+ "\\"+ DirectoryOrFileName[count]
if os.path.exists(Path):
ResultList.append("\n-******************************************%s**************************************- \nTYPE: "% (QueriedResultCounts+count) + TypeDir +" \nDESCRIPTION: \n"+Str_index[count]+"PATH:\n " + Path+"\n\n")
count = count + 1
else:
for TypeDir in TypeDirList:
for CodeTypeDir in CodeTypeDirList:
Path = AbsolutePath.replace('/', '\\')+ TypeDir + "\\" +CodeTypeDir+ "\\"+ DirectoryOrFileName[count]
if os.path.exists(Path):
ResultList.append("\n-******************************************%s**************************************- \nTYPE: "% (QueriedResultCounts+count) + TypeDir +" \nDESCRIPTION: \n"+Str_index[count]+"PATH:\n " + Path+ "\n\n")
count = count + 1
QueriedResultCounts = QueriedResultCounts + count
# return ResultList#return the queried result.
# print(ResultList)#print the queried result.
count1 = 1.0
for querieditems in ResultList: #display the queried result in entry control of GUI
Text_result_control.insert(count1, querieditems)
count1 = count1 + 7.0
def AddValueInDict(index_list, str, value, CurrPos):
if value != -1:
index_list[str] = value + CurrPos
#Main Frame Form
#Manage Record GUI
def Call_Manage_Record_GUI(object):
Manage_Record_GUI_1 = Manage_Record_GUI(object)
class Manage_Record_GUI:
#using Type, Code_Type to find the Record.txt file and locate the position to add record
cmbEditComboList_Code_Type = []
index_list = []
description_list = {}
keywords_list = {}
DirPath_list = {}
FilePath_list = {}
MatchedRecordStr = {}
def __init__(self, object):
self.object = object
self.frm_Manage_Record = Toplevel(self.object)
self.frm_Manage_Record.attributes("-toolwindow", 1)
self.frm_Manage_Record.wm_attributes("-topmost", 1)
self.object.wm_attributes("-disabled", 1)#Disable parent window
self.frm_Manage_Record.title("Manage Record")
self.frm_Manage_Record.resizable(False,False)
self.Init()
#Add Related UI
#Type
def TraveringTypeFiles(self,event):
self.Combobox_Type.delete(0,END)
# Manage_Dir_GUI.cmbEditComboList_Code_Type = self.Combobox_Code_Type.get()
global AbsolutePath
Dirs = [d for d in os.listdir(AbsolutePath) if os.path.isdir((os.path.join(AbsolutePath,d)))]#list only the directory under given directory
if '.git' in Dirs:
Dirs.remove('.git')
if 'CodingPartner' in Dirs:
Dirs.remove('CodingPartner')
if 'FuncModule' in Dirs:
Dirs.remove('FuncModule')
Dirs.append('Function Module')
self.Combobox_Type['value'] = (Dirs)
def TraveringCodeTypeFiles(self,event):
self.Combobox_Code_Type.delete(0,END)
Type = self.Combobox_Type.get()
# Manage_Dir_GUI.cmbEditComboList_Code_Type = self.Combobox_Code_Type.get()
Type_Dict = {"Function Module": Path_FuncModule,"Project": Path_Project} #Map Type to related directory
cmbEditComboList_Code_Type_Const = {"CPlusPlus": "C++","Java": "Java","Python": "Python","CSharp": "C#","SQL": "SQL","HTML_CSS": "Html/CSS","C_Lang": "C_Lang","Matlab": "Matlab"}
Dirs = []
if Type != '':
if os.path.exists(Type_Dict[Type]):
Dirs = [d for d in os.listdir(Type_Dict[Type]) if os.path.isdir(os.path.join(Type_Dict[Type],d))]#list only the directory under given directory
self.Combobox_Code_Type['value'] = (Dirs)
def EnableButton(self):
self.object.wm_attributes("-disabled", 0)#Enable parent window
self.frm_Manage_Record.destroy()
def Init(self):
self.label_Type = Label(self.frm_Manage_Record,anchor = "nw",text="Type") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Type.grid(row=0, column = 0, columnspan = 2)
cmbEditComboList_Type = ['Function Module','Project',]
self.Combobox_Type = Combobox(self.frm_Manage_Record, values = cmbEditComboList_Type, state = 'readonly') #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.Combobox_Type.grid(row=0, column = 2, columnspan = 2)
self.Combobox_Type.bind('<Button-1>', self.TraveringTypeFiles)#<ComboboxSelected>
#Code Type
self.label_Code_Type = Label(self.frm_Manage_Record,anchor = "nw",text="Code Type") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Code_Type.grid(row=0, column = 6, columnspan = 2)
#cmbEditComboList_Code_Type = ['C++','Java','Python','C#','SQL', 'Html/CSS','C', 'Matlab']
self.Combobox_Code_Type = Combobox(self.frm_Manage_Record, state = 'readonly')
self.Combobox_Code_Type.grid(row=0, column = 10, columnspan = 4)
self.Combobox_Code_Type.bind('<Button-1>', self.TraveringCodeTypeFiles)#<ComboboxSelected>
#Description
self.label_Description = Label(self.frm_Manage_Record,anchor = "nw",text="Description") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Description.grid(row=0, column = 14, columnspan = 2)
self.entry_Description = Entry(self.frm_Manage_Record)
self.entry_Description.grid(row=0, column=16, columnspan = 4)
#Keywords
self.label_Keywords = Label(self.frm_Manage_Record,anchor = "nw",text="Keywords") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Keywords.grid(row=0, column = 20, columnspan = 2)
self.entry_Keywords = Entry(self.frm_Manage_Record)
self.entry_Keywords.grid(row=0, column=22, columnspan = 4)
#Directory Path
DirecotryPath = ''
self.button_Dir_Path = Button(self.frm_Manage_Record, text = "Directory", command = lambda:OpenDir(DirecotryPath,self.entry_Dir_Path, self.Combobox_Type.get(), self.frm_Manage_Record))#Button used to add record in Record.txt
self.button_Dir_Path.grid(row=0, column=26, columnspan = 2)
self.entry_Dir_Path = Entry(self.frm_Manage_Record)
self.entry_Dir_Path.grid(row=0, column=28, columnspan = 4)
#File Path
FilePath = ''
self.button_File_Path = Button(self.frm_Manage_Record, text = "File", command = lambda:OpenFile(FilePath,self.entry_File_Path, self.Combobox_Type.get(), self.frm_Manage_Record))#Button used to add record in Record.txt
self.button_File_Path.grid(row=0, column=32, columnspan = 2)
self.entry_File_Path = Entry(self.frm_Manage_Record)
self.entry_File_Path.grid(row=0, column=34, columnspan = 4)
#Add
self.button_Add = Button(self.frm_Manage_Record, text = "Add", command = lambda:ManageRecord_Add(self.frm_Manage_Record,self.Combobox_Type.get(), self.Combobox_Code_Type.get(), self.entry_Description.get(), self.entry_Keywords.get(), self.entry_Dir_Path.get(), self.entry_File_Path.get()))#Button used to add record in Record.txt , command = lambda:OpenFile(FilePath,entry_Path, Combobox_Type.get())
self.button_Add.grid(row=0, column=38, columnspan = 2)
#Delete Related UI
#Keyword_Query
self.label_Keyword_Query = Label(self.frm_Manage_Record,anchor = "nw",text="Keyword") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Keyword_Query.grid(row=1, column = 0, columnspan = 2)
self.entry_Keyword_Query = Entry(self.frm_Manage_Record)
self.entry_Keyword_Query.grid(row=1, column = 2, columnspan = 4)
#Index
self.label_Index = Label(self.frm_Manage_Record,anchor = "nw",text="Index") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Index.grid(row=1, column = 6, columnspan = 2)
self.Combobox_Index = Combobox(self.frm_Manage_Record, state = 'readonly')
self.Combobox_Index.grid(row=1, column = 10, columnspan = 4)
self.Combobox_Index.bind("<<ComboboxSelected>>", self.RenewManageRecord_Delete_UI)#<ComboboxSelected>
#Description
self.label_Description_Delete = Label(self.frm_Manage_Record,anchor = "nw",text="Description") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Description_Delete.grid(row=1, column = 14, columnspan = 2)
self.entry_Description_Delete = Entry(self.frm_Manage_Record)
self.entry_Description_Delete.grid(row=1, column=16, columnspan = 4)
#Keywords
self.label_Keywords_Delete = Label(self.frm_Manage_Record,anchor = "nw",text="Keywords") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Keywords_Delete.grid(row=1, column = 20, columnspan = 2)
self.entry_Keywords_Delete = Entry(self.frm_Manage_Record)
self.entry_Keywords_Delete.grid(row=1, column=22, columnspan = 4)
#Directory Path
self.label_Dir_Path = Label(self.frm_Manage_Record,anchor = "nw",text="Directory") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Dir_Path.grid(row=1, column = 26, columnspan = 2)
self.entry_Dir_Path_Delete = Entry(self.frm_Manage_Record)
self.entry_Dir_Path_Delete.grid(row=1, column=28, columnspan = 4)
#File Path
self.label_File_Path = Label(self.frm_Manage_Record,anchor = "nw",text="File") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_File_Path.grid(row=1, column = 32, columnspan = 2)
self.entry_File_Path_Delete = Entry(self.frm_Manage_Record)
self.entry_File_Path_Delete.grid(row=1, column=34, columnspan = 4)
#Delete
self.button_Delete = Button(self.frm_Manage_Record, text = "Delete", command = lambda:ManageRecord_Delete_Button(self.frm_Manage_Record, self.Combobox_Index.get(), Manage_Record_GUI.MatchedRecordStr, self.entry_Dir_Path_Delete.get(), self.entry_File_Path_Delete.get()))#Button used to delete record in Record.txt
self.button_Delete.grid(row=1, column=38, columnspan = 2)
self.entry_Keyword_Query.bind('<KeyRelease>', self.ManageRecord_Delete_callback)
#make the current main window lay in the middle of screen
self.frm_Manage_Record.update_idletasks()
w = self.frm_Manage_Record.winfo_screenwidth()
h = self.frm_Manage_Record.winfo_screenheight()
size = tuple(int(_) for _ in self.frm_Manage_Record.geometry().split('+')[0].split('x'))
x = w/2 - size[0]/2
y = h/2 - size[1]/2
self.frm_Manage_Record.geometry("%dx%d+%d+%d" % (size + (x, y)))
self.frm_Manage_Record.protocol ("WM_DELETE_WINDOW", self.EnableButton)
def RenewManageRecord_Delete_UI(self, event):
selected_index = self.Combobox_Index.get()
self.entry_Description_Delete.delete(0, END)
self.entry_Description_Delete.insert(0, Manage_Record_GUI.description_list[selected_index])
self.entry_Keywords_Delete.delete(0, END)
self.entry_Keywords_Delete.insert(0, Manage_Record_GUI.keywords_list[selected_index])
self.entry_Dir_Path_Delete.delete(0, END)
self.entry_Dir_Path_Delete.insert(0, Manage_Record_GUI.DirPath_list[selected_index])
self.entry_File_Path_Delete.delete(0, END)
self.entry_File_Path_Delete.insert(0, Manage_Record_GUI.FilePath_list[selected_index])
def ManageRecord_Delete_callback(self,event):
ManageRecord_Delete(self.frm_Manage_Record,self.entry_Keyword_Query.get(), self.Combobox_Index, self.entry_Description_Delete, self.entry_Keywords_Delete, self.entry_Dir_Path_Delete, self.entry_File_Path_Delete, Manage_Record_GUI.index_list, Manage_Record_GUI.description_list, Manage_Record_GUI.keywords_list,Manage_Record_GUI.DirPath_list, Manage_Record_GUI.FilePath_list,Manage_Record_GUI.MatchedRecordStr)
def ManageRecord_Delete_Button(object, index,RecordStrMap,Dir_Path, File_Path):
if index == "" or RecordStrMap == "" or File_Path == "":
object.wm_attributes("-topmost", 0)
showerror("Parameter Error", "Please configure the parameter correctly!")
object.wm_attributes("-topmost", 1)
return
RecordStr = RecordStrMap[index]
#delete file or directory and renew record in Record.txt
if os.path.isdir(Dir_Path) and Dir_Path != "":
object.wm_attributes("-topmost", 0)
result = askyesno("Caution","Do you really want to delete %s?"%Dir_Path)
if result == True:
shutil.rmtree(Dir_Path)#delete directory
Delete_Record_RenewRecordtxt(Dir_Path,RecordStr)#delete related record in file Record.txt
showinfo("Success","\'"+ Dir_Path +"\'"+" directory was deleted")
object.wm_attributes("-topmost", 1)
else:
object.wm_attributes("-topmost", 0)
result = askyesno("Caution","Do you really want to delete %s?"%File_Path)
if result == True:
os.remove(File_Path)#delete file
Delete_Record_RenewRecordtxt(File_Path,RecordStr)#delete related record in file Record.txt
showinfo("Success","\'"+ File_Path +"\'"+" file was deleted")
object.wm_attributes("-topmost", 1)
def Delete_Record_RenewRecordtxt(Path,RecordStr):
Path_CodeTypeRecordPath = str.replace(Path, Path.split('\\')[-2] if Path.split('\\')[-1] == '' else Path.split('\\')[-1], "",1)
Path_TypeRecordPath = str.replace(Path_CodeTypeRecordPath, Path_CodeTypeRecordPath.split('\\')[-2] if Path_CodeTypeRecordPath.split('\\')[-1] == '' else Path_CodeTypeRecordPath.split('\\')[-1], "",1)
CodeType_Recordtxt = Path_CodeTypeRecordPath + "\\Record.txt"
Type_Recordtxt = Path_TypeRecordPath + "\\Record.txt"
fid = open(CodeType_Recordtxt,"r")
lines = fid.readlines()
fid.close()
fid = open(CodeType_Recordtxt,"wt")
for line in lines:
if line == RecordStr:
continue
else:
fid.write(line)
fid.close()
fid = open(Type_Recordtxt,"r")
lines = fid.readlines()
fid.close()
fid = open(Type_Recordtxt,"wt")
for line in lines:
if line == RecordStr:
continue
else:
fid.write(line)
fid.close()
#Manage Directory GUI
def Call_Manage_Dir_GUI(object):
Manage_Dir_GUI_1 = Manage_Dir_GUI(object)
class Manage_Dir_GUI:
#using Type, Code_Type to find the Record.txt file and locate the position to add record
cmbEditComboList_Code_Type = []
def __init__(self, object):
self.object = object
self.frm_Manage_Dir = Toplevel(self.object)
self.frm_Manage_Dir.attributes("-toolwindow", 1)
self.frm_Manage_Dir.wm_attributes("-topmost", 1)
self.object.wm_attributes("-disabled", 1)#Disable parent window
self.frm_Manage_Dir.title("Manage Directory")
self.frm_Manage_Dir.resizable(False,False)
self.Init()
def TraveringCodeTypeFiles(self,event):
self.Combobox_Code_Type['value'] = ("")
Type = self.Combobox_Type.get()
# Manage_Dir_GUI.cmbEditComboList_Code_Type = self.Combobox_Code_Type.get()
Type_Dict = {"Function Module": Path_FuncModule,"Project": Path_Project} #Map Type to related directory
cmbEditComboList_Code_Type_Const = {"CPlusPlus": "C++","Java": "Java","Python": "Python","CSharp": "C#","SQL": "SQL","HTML_CSS": "Html/CSS","C_Lang": "C_Lang","Matlab": "Matlab"}
if Type in Type_Dict:
if Type != "" and os.path.exists(Type_Dict[Type]):
Dirs = [d for d in os.listdir(Type_Dict[Type]) if os.path.isdir(os.path.join(Type_Dict[Type],d))]#list only the directory under given directory
else:
global AbsolutePath
Dirs = [d for d in os.listdir(AbsolutePath + "\\" + Type) if os.path.isdir(os.path.join(AbsolutePath + "\\" + Type,d))]#list only the directory under given directory
self.Combobox_Code_Type['value'] = (Dirs)
def TraveringTypeFiles(self,event):
self.Combobox_Type['value'] = ("")
# Manage_Dir_GUI.cmbEditComboList_Code_Type = self.Combobox_Code_Type.get()
global AbsolutePath
Dirs = [d for d in os.listdir(AbsolutePath) if os.path.isdir((os.path.join(AbsolutePath,d)))]#list only the directory under given directory
if '.git' in Dirs:
Dirs.remove('.git')
if 'CodingPartner' in Dirs:
Dirs.remove('CodingPartner')
if 'FuncModule' in Dirs:
Dirs.remove('FuncModule')
Dirs.append('Function Module')
self.Combobox_Type['value'] = (Dirs)
def EnableButton(self):#when current windows closes, the parent window will be enable.
self.object.wm_attributes("-disabled", 0)#Enable parent window
self.frm_Manage_Dir.destroy()#Destory current window
def Init(self):
#GUI Related
#Type
self.label_Type = Label(self.frm_Manage_Dir,anchor = "nw",text="Type") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Type.grid(row=0, column = 0, columnspan = 2, rowspan = 3)
cmbEditComboList_Type = ['Function Module','Project',]
self.Combobox_Type = Combobox(self.frm_Manage_Dir, values = cmbEditComboList_Type) #anchor:must be n, ne, e, se, s, sw, w, nw, or center , state = 'readonly'
self.Combobox_Type.grid(row=0, column = 2, columnspan = 10, rowspan = 3)
self.Combobox_Type.bind('<Button-1>', self.TraveringTypeFiles)#<ComboboxSelected>
#Code Type
self.label_Code_Type = Label(self.frm_Manage_Dir,anchor = "nw",text="Code Type") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Code_Type.grid(row=0, column = 12, columnspan = 2, rowspan = 3)
self.Combobox_Code_Type = Combobox(self.frm_Manage_Dir, values = Manage_Dir_GUI.cmbEditComboList_Code_Type)
self.Combobox_Code_Type.grid(row=0, column = 14, columnspan = 4, rowspan = 3)
self.Combobox_Code_Type.bind('<Button-1>', self.TraveringCodeTypeFiles)#<ComboboxSelected>
#Add
self.button_Add = Button(self.frm_Manage_Dir, text = "Add" , command = lambda:ManageDirectory_Add(self.frm_Manage_Dir,self.Combobox_Type.get(), self.Combobox_Code_Type.get()))#Button used to add Direcotory
self.button_Add.grid(row=4, column=9, columnspan = 2)
self.button_Delete = Button(self.frm_Manage_Dir, text = "Delete" , command = lambda:ManageDirectory_Delete(self.frm_Manage_Dir,self.Combobox_Type.get(), self.Combobox_Code_Type.get()))#Button used to add record in Record.txt , command = lambda:OpenFile(FilePath,entry_Path, Combobox_Type.get())
self.button_Delete.grid(row=4, column=14, columnspan = 2)
#Delete
#make the current main window lay in the middle of screen
self.frm_Manage_Dir.update_idletasks()
w = self.frm_Manage_Dir.winfo_screenwidth()
h = self.frm_Manage_Dir.winfo_screenheight()
size = tuple(int(_) for _ in self.frm_Manage_Dir.geometry().split('+')[0].split('x'))
x = w/2 - size[0]/2
y = h/2 - size[1]/2
self.frm_Manage_Dir.geometry("%dx%d+%d+%d" % (size + (x, y)))
self.frm_Manage_Dir.protocol ("WM_DELETE_WINDOW", self.EnableButton)
def OpenDir(Path,object, Type, Window_Name):#Get Directory
Window_Name.wm_attributes("-topmost", 0)
Path = ''#askopenfilename
Path = filedialog.askdirectory()
object.delete(0, END)
object.insert(1, Path)
Window_Name.wm_attributes("-topmost", 1)
def OpenFile(Path,object, Type, Window_Name):#Get File Directory
Window_Name.wm_attributes("-topmost", 0)
Path = ''#askopenfilename
Path = filedialog.askopenfilename()
object.delete(0, END)
object.insert(1, Path)
Window_Name.wm_attributes("-topmost", 1)
def SetDefaultWorkingFile(entry_query):#Get File Directory
Path = filedialog.askdirectory()
if os.path.exists(Path) and Path != "":
entry_query.insert(0, Path)
class SetDefaultPath:
#Flow:
#(1)First: Judge whether there under the
def __init__(self):
self.DefaultPath = "C:\\Users\\Public\\Coding Partner\\DefaultPath.txt"
self.DefaultDir = "C:\\Users\\Public\\Coding Partner"
self.Init()
def SetDefaultWorkingFile_OK(self):
Path = self.entry_PATH.get()
global AbsolutePath
if Path != "":
if os.path.exists(Path):
if self.Combobox_Dir.get() == "Existed":
os.mkdir(self.DefaultDir)
DefaultPath = self.DefaultDir + "\\DefaultPath.txt"
fid = open(DefaultPath, "wt")
Path = Path+"/"
fid.write(Path)#This str should get from UI set
fid.close()
AbsolutePath = Path
Path_Assig_Value()
self.PathSetUI.destroy()
elif self.Combobox_Dir.get() == "New":
os.mkdir(self.DefaultDir)
DefaultPath = self.DefaultDir + "\\DefaultPath.txt"
fid = open(DefaultPath, "wt")
if not os.path.exists(Path + "/Coding_Partner"):
os.mkdir(Path + "/Coding_Partner")
Path = Path + "/Coding_Partner/"
fid.write(Path)#This str should get from UI set
fid.close()
AbsolutePath = Path
Path_Assig_Value()
self.PathSetUI.destroy()
def CancelButtonFunc(self):
self.PathSetUI.destroy()
sys.exit()
def Init(self):
if not os.path.exists(self.DefaultPath):
#result = askyesno("Attention","Do You Want Create A New Working Directory?")
#if result == YES:
self.PathSetUI = Tk()
self.PathSetUI.title("Select Working Directory")
self.PathSetUI.resizable(False,False)
self.PathSetUI.protocol ("WM_DELETE_WINDOW", self.CancelButtonFunc)
self.label_DirSelect = Label(self.PathSetUI,anchor = "nw",text="Directory Type")
self.label_DirSelect.grid(row=0, column=0,sticky=W, columnspan = 2)
cmbEditComboList_Dir = ["New", "Existed"]
self.Combobox_Dir = Combobox(self.PathSetUI, values = cmbEditComboList_Dir, state = 'readonly') #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.Combobox_Dir.set("Existed");
self.Combobox_Dir.grid(row=0, column = 2, columnspan = 2)
self.label_PATH = Label(self.PathSetUI,anchor = "nw",text="PATH") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_PATH.grid(row=0, column=4,sticky=W, columnspan = 3)
self.entry_PATH = Entry(self.PathSetUI,width = 60)
self.entry_PATH.grid(row=0, column=7, columnspan = 6)
self.button_SetPath = Button(self.PathSetUI, text = "Open", command = lambda:SetDefaultWorkingFile( self.entry_PATH))#tied the entry to the button, when the button is being clicked, function KeywordQuery will be called.
self.button_SetPath.grid(row=0, column=13)
self.button_ok = Button(self.PathSetUI, text = " OK ", command = self.SetDefaultWorkingFile_OK)#tied the entry to the button, when the button is being clicked, function KeywordQuery will be called.
self.button_ok.grid(row=1, column=4, columnspan = 4)
self.button_cacel = Button(self.PathSetUI, text = "CACEL", command = self.CancelButtonFunc)#tied the entry to the button, when the button is being clicked, function KeywordQuery will be called.
self.button_cacel.grid(row=1, column=8, columnspan = 4)
#make the current main window lay in the middle of screen
self.PathSetUI.update_idletasks()
w = self.PathSetUI.winfo_screenwidth()
h = self.PathSetUI.winfo_screenheight()
size = tuple(int(_) for _ in self.PathSetUI.geometry().split('+')[0].split('x'))
x = w/2 - size[0]/2
y = h/2 - size[1]/2
self.PathSetUI.geometry("%dx%d+%d+%d" % (size + (x, y)))
self.PathSetUI.mainloop()
else:
fid = open(self.DefaultPath, "r")
line = fid.readline()
fid.close()
global AbsolutePath
AbsolutePath = line
Path_Assig_Value()
class MainWindow:
#Set a new default Directory or select existed directory
QuriedResultList = [] #Queried result will be in this list variable
#Later the GUI related code will be packaging and be putted in Main_UI directory
#GUI Related
############################################Query GUI Related###############################################################
#input gui entry contorl
if __name__ == "__main__":
WindowsCodingPartnerPath = SetDefaultPath()
frmMain = Tk()
frmMain.title("Coding Partner")
frmMain.resizable(False,False)
label_query = Label(frmMain,anchor = "nw",text="Enter Keyword") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
label_query.grid(row=0, sticky=W, columnspan = 3)
entry_query = Entry(frmMain, width = 95)
entry_query.grid(row=0, column=3, columnspan = 2)
button_query = Button(frmMain, text = "Query", width = 6, command = lambda:KeywordQuery(entry_query.get(),Text_result))#tied the entry to the button, when the button is being clicked, function KeywordQuery will be called.
button_query.grid(row=0, column=5, columnspan = 2)
#output gui entry contol
label_result = Label(frmMain,anchor = "s",text="Queried Results") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
label_result.grid(row=2, column=0, sticky=W)
Text_result = Text(frmMain, width = 95, height = 15)
Text_result.grid(row=2, column=3, columnspan = 2)
#Bind the ENTER key to Entry to execute KeywordQuery function
# create a popup menu
def ShowInExplorer():
selectedPath = Text_result.get('sel.first', 'sel.last')
#judge whether the path exists
if os.path.exists(selectedPath):
if os.path.isdir(selectedPath):
subprocess.Popen(r'explorer /select,"{0}"'.format(selectedPath))
else:
showwarning("Warning","\'"+selectedPath+"\'"+" do not exist")#show a warning MessageBox
def OpenwithIDE():
selectedPath = Text_result.get('sel.first', 'sel.last')
#judge whether the path exists
if os.path.exists(selectedPath):
if os.path.isfile(selectedPath):
os.startfile(selectedPath)
else:
showwarning("Warning","\'"+selectedPath+"\'"+" do not exist")#show a warning MessageBox
menu = Menu(frmMain, tearoff=0)
menu.add_command(label="show in windows explorer", command=ShowInExplorer)
menu.add_command(label="open with related IDE", command=OpenwithIDE)
def Text_result_callback(event):
menu.post(event.x_root, event.y_root)
Text_result.bind('<Button-3>', Text_result_callback)
#Bind the ENTER key to Entry to execute KeywordQuery function
def callback(event):
KeywordQuery(entry_query.get(), Text_result)
entry_query.bind('<KeyRelease>', callback)
############################################Add Record GUI Related######################################################
button_Manage_Record = Button(frmMain, text="Manage Record", command= lambda:Call_Manage_Record_GUI(frmMain))
button_Manage_Record.grid(row=4, column=3, rowspan = 2)
button_Manage_Dir = Button(frmMain, text = "Manage Directory", command = lambda:Call_Manage_Dir_GUI(frmMain))#Button used to add record in Record.txt
button_Manage_Dir.grid(row=4, column=4, rowspan = 2)
######################################################End###############################################################
#make the current main window lay in the middle of screen
frmMain.update_idletasks()
w = frmMain.winfo_screenwidth()
h = frmMain.winfo_screenheight()
size = tuple(int(_) for _ in frmMain.geometry().split('+')[0].split('x'))
x = w/2 - size[0]/2
y = h/2 - size[1]/2
frmMain.geometry("%dx%d+%d+%d" % (size + (x, y)))
#ScrollBary in Text
scrollbary = Scrollbar(frmMain, orient = 'vertical')
scrollbary.grid(row = 2, column = 3,sticky = 'NES', columnspan = 2) #sticky is used to contorl the Control's direction in the contained Control
# attach Text Control to scrollbar
Text_result.config(yscrollcommand=scrollbary.set)
scrollbary.config(command=Text_result.yview)
#ScrollBarx in Text
scrollbarx = Scrollbar(frmMain, orient = 'horizontal')
scrollbarx.grid(row = 2, column =3,sticky = 'WSE', columnspan = 2) #sticky is used to contorl the Control's direction in the contained Control
# attach Text Control to scrollbar
Text_result.config(xscrollcommand=scrollbarx.set)
scrollbarx.config(command=Text_result.xview)
frmMain.mainloop()
<file_sep>/FuncModule/CPlusPlus/SumofTwoIntegers.cpp
/*
@ques:Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3.
@url:https://leetcode.com/problems/sum-of-two-integers/description/
@author:shujie,wang
@date:3/25/2018
@pudong district,shanghai
*/
class Solution {
public:
int getSum(int a, int b) {
//异或后,再加上相与的结果左移作为进位,循环往复
while(a&b){
int temp = a;
a = (temp & b)<<1;
b = temp ^ b;
}
return a|b;
}
};
<file_sep>/FuncModule/CPlusPlus/ArraySubSet.cpp
/*
@ques:输出数组的的所有子集
@author:yangchun,chen
@date:3/29/2018
@iqiyi,shanghai
*/
#include<cstdio>
int a[10];
void print_subset(int n,int *b,int cur) //确定第cur位选或者不选
{
if (cur==n) //如果确定好了n位,打印结果
{
printf("{ ");
for (int i=0;i<n;i++)
if (b[i]) printf("%d ",a[i]);
printf("}\n");
}
else
{
b[cur]=1; //这一位选
printf("cur:%d-1\n",cur);
print_subset(n,b,cur+1); //递归下一位
b[cur]=0; //这一位不选
printf("cur:%d-0\n",cur);
print_subset(n,b,cur+1); //递归下一位
}
}
int main()
{
int n;
int b[10]={};
scanf("%d",&n);
for (int i=0;i<n;i++) a[i]=i;
print_subset(n,b,0);
return 0;
}
<file_sep>/FuncModule/CPlusPlus/InputAStringLine/main.cpp
/*
FileName: BinaryTree.cpp
Create Time: 2015/09/16
Modify Time:
Author: <NAME>
Owner: <NAME>
Place: 上海交通大学闵行校区微电子楼301室
Reference:
Description: (1)主要测试在控制台应用程序中如何输入一整行的字符串数据,这个在微软实习生招聘以及华为正式招聘机考的时候都出问题,切记,血的教训;
(2)将输入的字符串的首字母变为大写,如果本来就是大写或者是数字,就保持不变。
*/
//#define METHOD1
//#define METHOD2
#define METHOD3
#if defined METHOD1
#include<stdio.h>
#include<string.h>
void ToB(char* Input)
{
int len = strlen(Input) + 1;
char *temp = " ";
for(int i = 0; i < len; i++)
{
if(i == 0)
{
Input[i] = Input[i] - 32;
}
else if(Input[i-1] == ' ' && (Input[i] >= 'a' && Input[i] <= 'z'))
{
Input[i] = Input[i] - 32;
}
else
{
Input[i] = Input[i];
}
}
}
int main()
{
char Input[100] = {0};
char Output[1000] = {0};
gets(Input);
ToB(Input);
printf("%s ", Input);
return 0;
}
#elif defined METHOD2
#include<iostream>
#include<string>
using namespace std;
void ToB(string &Input)
{
int len = Input.size();
for(int i = 0; i < len; i++)
{
if(i == 0)
{
Input[i] = Input[i] - 32;
}
else if(Input[i-1] == ' ' && (Input[i] >= 'a' && Input[i] <= 'z'))
{
Input[i] = Input[i] - 32;
}
else
{
Input[i] = Input[i];
}
}
}
int main()
{
string Input;
getline(cin,Input);
ToB(Input);
cout << Input << endl;
return 0;
}
#elif defined METHOD3
#include<iostream>
#include<string>
using namespace std;
void ToB(char *Input)
{
int len = strlen(Input);
for(int i = 0; i < len; i++)
{
if(i == 0)
{
Input[i] = Input[i] - 32;
}
else if(Input[i-1] == ' ' && (Input[i] >= 'a' && Input[i] <= 'z'))
{
Input[i] = Input[i] - 32;
}
else
{
Input[i] = Input[i];
}
}
}
int main()
{
char Input[1000];
cin.getline(Input, 1000);
ToB(Input);
cout << Input << endl;
return 0;
}
#endif<file_sep>/CodingPartner/FuncPack/FuncModule_Manage/__init__.py
__author__ = 'JD'
#Add, Delete, Modify and Query code under the FuncModule directory
<file_sep>/FuncModule/CPlusPlus/Course_CPlusPlus_Week2.cpp
/*
FileName: Course_CPlusPlus_Week2.cpp
Create Time: 2015/10/09
Modify Time:
Author: <NAME>
Owner: <NAME>
Place: 上海交通大学闵行校区微电子楼301室
Reference: https://www.coursera.org/learn/cpp-chengxu-sheji/programming/CpvBs/bian-cheng-zuo-ye-c-chu-tan
Description: (1)简单的学生信息处理程序;(2)如何正确的使用geline函数读取以某个分隔符分开的不同类型的一行数据;
*/
/*
简单的学生信息处理程序实现
来源: POJ (Coursera声明:在POJ上完成的习题将不会计入Coursera的最后成绩。)
注意: 总时间限制: 1000ms 内存限制: 65536kB
描述
在一个学生信息处理程序中,要求实现一个代表学生的类,并且所有成员变量都应该是私有的。
(注:评测系统无法自动判断变量是否私有。我们会在结束之后统一对作业进行检查,请同学们严格按照题目要求完成,否则可能会影响作业成绩。)
输入
姓名,年龄,学号,第一学年平均成绩,第二学年平均成绩,第三学年平均成绩,第四学年平均成绩。
其中姓名、学号为字符串,不含空格和逗号;年龄为正整数;成绩为非负整数。
各部分内容之间均用单个英文逗号","隔开,无多余空格。
输出
一行,按顺序输出:姓名,年龄,学号,四年平均成绩(向下取整)。
各部分内容之间均用单个英文逗号","隔开,无多余空格。
样例输入
Tom,18,7817,80,80,90,70
样例输出
Tom,18,7817,80
*/
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
class student
{
private:
char Name[20];
char StudentID[20];
unsigned int Age;
unsigned int Score[4];
public:
student(const char *name, const char *studentid, unsigned int age, unsigned int *score) :Age(age)
{
strcpy_s(Name, name);
strcpy_s(StudentID, studentid);
memcpy(Score, score, 4 * sizeof(unsigned int));
}
void Print()
{
cout << Name << "," << Age << "," << StudentID << "," << (int)((Score[0] + Score[1] + Score[2] + Score[3]) / 4) << endl;
}
};
int main()
{
char Name[20];
char StudentID[20];
unsigned int Age;
unsigned int Score[4];
string str;
getline(cin, str, ',');//这里的getline使用一个循环读取str并依此赋值给一个string数组也是可以的,尤其在输入数据量比较大的情况下
strcpy_s(Name, str.c_str());//不能使用Name(Name为指针变量) = str.c_str();因为这样是指针赋值,下次str的值改变后会影响已经赋值过的变量
getline(cin, str, ',');
Age = atoi(str.c_str());
getline(cin, str, ',');
strcpy_s(StudentID, str.c_str());
getline(cin, str, ',');
Score[0] = atoi(str.c_str());
getline(cin, str, ',');
Score[1] = atoi(str.c_str());
getline(cin, str, ',');
Score[2] = atoi(str.c_str());
getline(cin, str);//因为最后一个没有的分隔符是回车符,所以这里使用默认的即可
Score[3] = atoi(str.c_str());
student Tim(Name, StudentID, Age, Score);
Tim.Print();
return 0;
}<file_sep>/FuncModule/CPlusPlus/MaximumSubarray.cpp
/*
*@ques:Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
@url:https://leetcode.com/problems/maximum-subarray/description/
@author:yangchun,chen
@date:4/1/2018
* */
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int maxSubArray(vector<int>& nums) {
vector <int> dp = nums;
//将最大值和动态规划数组先赋值为第一位
int max = nums[0];
dp[0] = nums[0];
//遍历数组,将数组当前位置的值与动态规划数组前一位相加,如果前一位值大于0,就相加再存到当前位置,否则只保留当前位置的值,在遍历过程中每次与max值比较
for(int i = 1; i < nums.size(); i++){
dp[i] = nums[i] + (dp[i-1] > 0 ? dp[i-1] : 0);
max = std::max(max,dp[i]);
}
return max;
}
};
int main(){
int arr[2] = {-1,-2};
vector<int> vec(arr,arr+2);
Solution s;
int result = s.maxSubArray(vec);
cout << result << endl;
return 1;
}
<file_sep>/FuncModule/CPlusPlus/LevelTraverseOfBT/LevelTraverseOfBT/main.cpp
//Ref: 《编程之美》——分层遍历二叉树
//Author: <NAME>
//Data: 2015/8/30
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
/*使用层次遍历法遍历该二叉树
| 1 |
- -
- -
| 2 | | 3 |
- - -
- - -
| 4 | | 5 | | 6 |
*/
struct Node
{
int data;
Node* lChild;
Node* rChild;
};
//层次遍历法递归代码,所有遍历都需要从根结点开始,效率比较低
int PrintNodeAtLevel(Node *root, int level)
{
if(!root || level < 0)
{
return 0;
}
else if(level == 0 )//输出该层的节点信息
{
cout << root->data << " ";
return 1;
}
return PrintNodeAtLevel(root -> lChild, level - 1) + PrintNodeAtLevel(root -> rChild, level - 1);//分层遍历,层次遍历的关键,@从左子树到右子树输出
//return PrintNodeAtLevel(root -> rChild, level - 1) + PrintNodeAtLevel(root -> lChild, level - 1);//分层遍历,层次遍历的关键,@从右子树到左子树输出
}
//按层次遍历二叉树
//root:二叉树根节点
//不需要从根节点重复遍历,效率比较高
void PrintNodeByLevel(Node* root)
{
if(root == NULL)
return ;
vector<Node*> vec;
vec.push_back(root);
int cur = 0;
int last = 1;
while(cur < vec.size())//整个BT的Level层循环
{
last = vec.size();
while(cur < last)//当前Level层的各个节点循环
{
cout << vec[cur]->data << " ";
if(vec[cur]->lChild)
vec.push_back(vec[cur]->lChild);
if(vec[cur]->rChild)
vec.push_back(vec[cur]->rChild);
cur++;
}
cout << endl;//输出一行后换行
}
}
void PrintByReverseLevel(Node *root)//从下往上访问二叉树,待消化
{
vector<Node *> q;
stack<int> q2; //记录当前节点的层次
Node *p;
q.push_back(root);
q2.push(0);
int cur=0;
int last=1;
while(cur<q.size())
{
int level=q2.top();
last=q.size();
while(cur<last)
{
p=q[cur];
if(p->rChild)
{
q.push_back(p->rChild);
q2.push(level+1);
}
if(p->lChild)
{
q.push_back(p->lChild);
q2.push(level+1);
}
cur++;
}
}
while(!q2.empty())
{
cout << q[--cur]->data;
int temp=q2.top();
q2.pop();
if(q2.empty() || temp!=q2.top())
cout << endl;
}
}
int main()
{
//Init BT(Binary Tree)
Node node1,node2,node3,node4,node5,node6;
node4.data=4;
node4.lChild=NULL;
node4.rChild=NULL;
node5.data=5;
node5.lChild=NULL;
node5.rChild=NULL;
node2.data=2;
node2.lChild=&node4;
node2.rChild=&node5;
node6.data=6;
node6.lChild=NULL;
node6.rChild=NULL;
node3.data=3;
node3.lChild=NULL;
node3.rChild=&node6;
node1.data=1;
node1.lChild=&node2;
node1.rChild=&node3;
cout << "*******方法1********" <<endl;
////层次遍历所有层,@知道树的深度
//for(int i = 0; i < 3; i++)
//{
// int Num = PrintNodeAtLevel(&node1,i);
// cout << "Num:" << Num <<endl;
//}
//层次遍历所有层,@不知道树的深度
for(int i = 0; ; i++)
{
if(!PrintNodeAtLevel(&node1,i))//效率较低,因为每层都需要从根节点开始遍历
break;
cout << endl;
}
cout << "*******方法2********" <<endl;
PrintNodeByLevel(&node1);//效率比较高,利用了队列概念,每层遍历时只需要上一层的信息即可
cout << "*******方法1:从下往上********" <<endl;
PrintByReverseLevel(&node1);//效率比较高,利用了队列概念,每层遍历时只需要上一层的信息即可
getchar();
return 0;
}<file_sep>/Project/Python/DeepInsight/que_2.py
import sys
#example
print("Please input points set txt file name(like \"data.txt\"):")
fileName = ""
if sys.version > '3':
fileName = input()
else:
fileName = raw_input()
file = open(fileName)
lines = file.readlines()
Input=[]
for line in lines:
temp = line.replace('\n','').split(',')
Input.append([float(temp[0]),float(temp[1])])
print(Input)
print("Please inpute [Xmin,Xmax](like \"[0,0]\"):")
X = input()
print("Please inpute [Ymin,Ymax](like \"[1,1]\"):")
Y = input()
nPoints = 0
for nIndex in range(len(Input)):
if Input[nIndex][0] >= X[0] and Input[nIndex][0] <= X[1] and Input[nIndex][1] >= Y[0] and Input[nIndex][1] <= Y[1]:
nPoints += 1
print("The number of points inclued in the rectangel [Xmin,Xmax]x[Ymin,Ymax] is:%d"%nPoints)
<file_sep>/FuncModule/CPlusPlus/Arrange.cpp
/*
FileName: Arrange.cpp
Create Time: 2015/09/05
Modify Time:
Author: <NAME>
Owner: <NAME>
Place: 上海交通大学闵行校区微电子楼301室
Reference:
Description: (1)计算没有相同值排在相邻位置的排列种类;
*/
/*
通常我们希望检查n个不同元素的所有排列方式来确定一个最佳的排序。比如a,b,c的排列方式有abc,acb,bac,bca,cab,cba六种。
由于采用非递归的c++函数来输出排列方式很困难,所以采用递归是一种比较不错的方法。
其核心是:将每个元素放到n个元素组成的队列最前方,然后对剩余元素进行全排列,依次递归下去。
比如:
a b c
首先将a放到最前方(跟第一个元素交换),然后排列b c,然后将a放回本来位置
结果 a b c; a c b
其次将b放到最前方(跟第一个元素交换),然后排列a c,然后将b放回
结果 b a c; b c a
。。。
如果是4个元素,就将元素依次放到第一个元素的位置,后面的排序类似前面的3元素排序。
*/
int COUNT = 0;//在调用perm函数的地方需要将COUNT初始化为零
void SWAP(int *a,int *b) //交换数据
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
bool check(int *list, int n){//排除排列中存在值相同的排在相邻位置的情况
for(int i =0; i < n-1 ; i++){
if(abs(list[i] - list[i+1]) % 13 == 0){
return false;
}
}
return true;
}
int perm(int *list, int i, int n)//递归实现全排列
{
int j/*无用,temp*/;
if(i == n /*&& check(list, n)*/)//必须没有相邻的数值相同的才算数
{
for(j = 0; j < n; j++)
{
cout<<list[j];
cout<<" ";
}
COUNT++;
cout<<endl; //加
}
else
{
for(j = i; j < n; j++)
{
SWAP(list+i,list+j); //SWAP(list+i,list+j,temp);
perm(list,i+1,n);
SWAP(list+i,list+j); //SWAP(list+i,list+j,temp);
}
}
return COUNT;
}<file_sep>/Project/CPlusPlus/RFCard_Operate_ReadMissile/RFCard_Operate_ReadMissile/RFCard_Operate_ReadMissile.cpp
// VisualSimulation_RFcardMissleRecv.cpp: 主项目文件。
#include "stdafx.h"
#include "ReflectiveCard.h"
using namespace System;
int main(array<System::String ^> ^args)
{
/*********************反射内存卡读弹道数据使用示例*********************/
//反射内存卡读写数据变量
RFM_Card_Operate RFCardMissOperate(1, 4);//其中1为Device ID——即本地反射内存卡的设备ID,4为接收方Node ID
int result_RFM_CardInit = RFCardMissOperate.RFM_Card_Init(RFM2GEVENT_INTR1);//RFM2GEVENT_INTR1是本地反射内存卡接收中断类型
if (result_RFM_CardInit == -1)
{
printf("反射内存卡初始化错误!\n");
return -1;
}
struct MissilePosInfo inbuffer;
memset(&inbuffer, 0, sizeof(struct MissilePosInfo));
//循环开始
//生成弹道数据并赋值给outbuffer
//...
//写反射内存卡
//将弹道数据写入反射内存卡
RFM2G_STATUS result_Event = RFCardMissOperate.WaitForEvent();
if (result_Event != RFM2G_SUCCESS)
{
return(-1);
}
else
{
RFM2G_STATUS result_Read = RFCardMissOperate.RFM_Read_Missle(inbuffer);
if (result_Read != RFM2G_SUCCESS)
{
return(-1);
}
else
{
RFM2G_STATUS result_Write = RFCardMissOperate.RFM_Write_Missle(inbuffer, RFM2GEVENT_INTR2);//RFM2GEVENT_INTR2是远端反射内存卡接收中断类型
if (result_Write != RFM2G_SUCCESS)
{
return(-1);
}
}
}
//...
//循环结束
/**************************************************************/
return 0;
}
<file_sep>/FuncModule/CPlusPlus/ListSorting/ListSorting/BubbleSorting.h
/*
FileName: BubbleSorting.h
Create Time: 2015/09/04
Modify Time:
Author: <NAME>
Owner: <NAME>
Place: 上海交通大学闵行校区微电子楼301室
Reference: 《程序员面试宝典》——13.2.9 如何进行单链表排序
Description: (1)单链表的冒泡排序算法;
*/
#ifndef _BUBBLESORTING_H_
#define _BUBBLESORTING_H_
#include<stdio.h>
typedef struct node
{
int data;
struct node *next;
}linklist;
linklist* CreateList(int *arr, int len);
void ShowList(linklist *p);
void BubbleSortList(linklist *p);
#endif<file_sep>/CodingPartner/Main_UI/__init__.py
__author__ = 'JD'
from PathPack.Path import *
from tkinter import * #when use realted module, we need to import the realted package
from PathPack.Path import *;from FuncPack.txtManage import *
from tkinter.ttk import * #Combobox
from tkinter import filedialog
import PathPack.Path.__init__
#Main Frame Form
#Manage Record GUI
def Call_Manage_Record_GUI(object):
Manage_Record_GUI_1 = Manage_Record_GUI(object)
class Manage_Record_GUI:
#using Type, Code_Type to find the Record.txt file and locate the position to add record
cmbEditComboList_Code_Type = []
index_list = []
description_list = {}
keywords_list = {}
DirPath_list = {}
FilePath_list = {}
MatchedRecordStr = {}
def __init__(self, object):
self.object = object
self.frm_Manage_Record = Toplevel(self.object)
self.frm_Manage_Record.attributes("-toolwindow", 1)
self.frm_Manage_Record.wm_attributes("-topmost", 1)
self.object.wm_attributes("-disabled", 1)#Disable parent window
self.frm_Manage_Record.title("Manage Record")
self.frm_Manage_Record.resizable(False,False)
self.Init()
#Add Related UI
#Type
def TraveringTypeFiles(self,event):
self.Combobox_Type.delete(0,END)
# Manage_Dir_GUI.cmbEditComboList_Code_Type = self.Combobox_Code_Type.get()
Dirs = [d for d in os.listdir(PathPack.Path.__init__.AbsolutePath) if os.path.isdir((os.path.join(PathPack.Path.__init__.AbsolutePath,d)))]#list only the directory under given directory
if '.git' in Dirs:
Dirs.remove('.git')
if 'CodingPartner' in Dirs:
Dirs.remove('CodingPartner')
if 'FuncModule' in Dirs:
Dirs.remove('FuncModule')
Dirs.append('Function Module')
self.Combobox_Type['value'] = (Dirs)
def TraveringCodeTypeFiles(self,event):
self.Combobox_Code_Type.delete(0,END)
Type = self.Combobox_Type.get()
# Manage_Dir_GUI.cmbEditComboList_Code_Type = self.Combobox_Code_Type.get()
Type_Dict = {"Function Module": PathPack.Path.__init__.Path_FuncModule,"Project": PathPack.Path.__init__.Path_Project} #Map Type to related directory
cmbEditComboList_Code_Type_Const = {"CPlusPlus": "C++","Java": "Java","Python": "Python","CSharp": "C#","SQL": "SQL","HTML_CSS": "Html/CSS","C_Lang": "C_Lang","Matlab": "Matlab"}
Dirs = []
if Type != '':
if os.path.exists(Type_Dict[Type]):
Dirs = [d for d in os.listdir(Type_Dict[Type]) if os.path.isdir(os.path.join(Type_Dict[Type],d))]#list only the directory under given directory
self.Combobox_Code_Type['value'] = (Dirs)
def EnableButton(self):
self.object.wm_attributes("-disabled", 0)#Enable parent window
self.frm_Manage_Record.destroy()
def Init(self):
self.label_Type = Label(self.frm_Manage_Record,anchor = "nw",text="Type") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Type.grid(row=0, column = 0, columnspan = 2)
cmbEditComboList_Type = ['Function Module','Project',]
self.Combobox_Type = Combobox(self.frm_Manage_Record, values = cmbEditComboList_Type, state = 'readonly') #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.Combobox_Type.grid(row=0, column = 2, columnspan = 2)
self.Combobox_Type.bind('<Button-1>', self.TraveringTypeFiles)#<ComboboxSelected>
#Code Type
self.label_Code_Type = Label(self.frm_Manage_Record,anchor = "nw",text="Code Type") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Code_Type.grid(row=0, column = 6, columnspan = 2)
#cmbEditComboList_Code_Type = ['C++','Java','Python','C#','SQL', 'Html/CSS','C', 'Matlab']
self.Combobox_Code_Type = Combobox(self.frm_Manage_Record, state = 'readonly')
self.Combobox_Code_Type.grid(row=0, column = 10, columnspan = 4)
self.Combobox_Code_Type.bind('<Button-1>', self.TraveringCodeTypeFiles)#<ComboboxSelected>
#Description
self.label_Description = Label(self.frm_Manage_Record,anchor = "nw",text="Description") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Description.grid(row=0, column = 14, columnspan = 2)
self.entry_Description = Entry(self.frm_Manage_Record)
self.entry_Description.grid(row=0, column=16, columnspan = 4)
#Keywords
self.label_Keywords = Label(self.frm_Manage_Record,anchor = "nw",text="Keywords") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Keywords.grid(row=0, column = 20, columnspan = 2)
self.entry_Keywords = Entry(self.frm_Manage_Record)
self.entry_Keywords.grid(row=0, column=22, columnspan = 4)
#Directory Path
DirecotryPath = ''
self.button_Dir_Path = Button(self.frm_Manage_Record, text = "Directory", command = lambda:OpenDir(DirecotryPath,self.entry_Dir_Path, self.Combobox_Type.get(), self.frm_Manage_Record))#Button used to add record in Record.txt
self.button_Dir_Path.grid(row=0, column=26, columnspan = 2)
self.entry_Dir_Path = Entry(self.frm_Manage_Record)
self.entry_Dir_Path.grid(row=0, column=28, columnspan = 4)
#File Path
FilePath = ''
self.button_File_Path = Button(self.frm_Manage_Record, text = "File", command = lambda:OpenFile(FilePath,self.entry_File_Path, self.Combobox_Type.get(), self.frm_Manage_Record))#Button used to add record in Record.txt
self.button_File_Path.grid(row=0, column=32, columnspan = 2)
self.entry_File_Path = Entry(self.frm_Manage_Record)
self.entry_File_Path.grid(row=0, column=34, columnspan = 4)
#Add
self.button_Add = Button(self.frm_Manage_Record, text = "Add", command = lambda:ManageRecord_Add(self.frm_Manage_Record,self.Combobox_Type.get(), self.Combobox_Code_Type.get(), self.entry_Description.get(), self.entry_Keywords.get(), self.entry_Dir_Path.get(), self.entry_File_Path.get()))#Button used to add record in Record.txt , command = lambda:OpenFile(FilePath,entry_Path, Combobox_Type.get())
self.button_Add.grid(row=0, column=38, columnspan = 2)
#Delete Related UI
#Keyword_Query
self.label_Keyword_Query = Label(self.frm_Manage_Record,anchor = "nw",text="Keyword") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Keyword_Query.grid(row=1, column = 0, columnspan = 2)
self.entry_Keyword_Query = Entry(self.frm_Manage_Record)
self.entry_Keyword_Query.grid(row=1, column = 2, columnspan = 4)
#Index
self.label_Index = Label(self.frm_Manage_Record,anchor = "nw",text="Index") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Index.grid(row=1, column = 6, columnspan = 2)
self.Combobox_Index = Combobox(self.frm_Manage_Record, state = 'readonly')
self.Combobox_Index.grid(row=1, column = 10, columnspan = 4)
self.Combobox_Index.bind("<<ComboboxSelected>>", self.RenewManageRecord_Delete_UI)#<ComboboxSelected>
#Description
self.label_Description_Delete = Label(self.frm_Manage_Record,anchor = "nw",text="Description") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Description_Delete.grid(row=1, column = 14, columnspan = 2)
self.entry_Description_Delete = Entry(self.frm_Manage_Record)
self.entry_Description_Delete.grid(row=1, column=16, columnspan = 4)
#Keywords
self.label_Keywords_Delete = Label(self.frm_Manage_Record,anchor = "nw",text="Keywords") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Keywords_Delete.grid(row=1, column = 20, columnspan = 2)
self.entry_Keywords_Delete = Entry(self.frm_Manage_Record)
self.entry_Keywords_Delete.grid(row=1, column=22, columnspan = 4)
#Directory Path
self.label_Dir_Path = Label(self.frm_Manage_Record,anchor = "nw",text="Directory") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Dir_Path.grid(row=1, column = 26, columnspan = 2)
self.entry_Dir_Path_Delete = Entry(self.frm_Manage_Record)
self.entry_Dir_Path_Delete.grid(row=1, column=28, columnspan = 4)
#File Path
self.label_File_Path = Label(self.frm_Manage_Record,anchor = "nw",text="File") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_File_Path.grid(row=1, column = 32, columnspan = 2)
self.entry_File_Path_Delete = Entry(self.frm_Manage_Record)
self.entry_File_Path_Delete.grid(row=1, column=34, columnspan = 4)
#Delete
self.button_Delete = Button(self.frm_Manage_Record, text = "Delete", command = lambda:ManageRecord_Delete_Button(self.frm_Manage_Record, self.Combobox_Index.get(), Manage_Record_GUI.MatchedRecordStr, self.entry_Dir_Path_Delete.get(), self.entry_File_Path_Delete.get()))#Button used to delete record in Record.txt
self.button_Delete.grid(row=1, column=38, columnspan = 2)
self.entry_Keyword_Query.bind('<KeyRelease>', self.ManageRecord_Delete_callback)
#make the current main window lay in the middle of screen
self.frm_Manage_Record.update_idletasks()
w = self.frm_Manage_Record.winfo_screenwidth()
h = self.frm_Manage_Record.winfo_screenheight()
size = tuple(int(_) for _ in self.frm_Manage_Record.geometry().split('+')[0].split('x'))
x = w/2 - size[0]/2
y = h/2 - size[1]/2
self.frm_Manage_Record.geometry("%dx%d+%d+%d" % (size + (x, y)))
self.frm_Manage_Record.protocol ("WM_DELETE_WINDOW", self.EnableButton)
def RenewManageRecord_Delete_UI(self, event):
selected_index = self.Combobox_Index.get()
self.entry_Description_Delete.delete(0, END)
self.entry_Description_Delete.insert(0, Manage_Record_GUI.description_list[selected_index])
self.entry_Keywords_Delete.delete(0, END)
self.entry_Keywords_Delete.insert(0, Manage_Record_GUI.keywords_list[selected_index])
self.entry_Dir_Path_Delete.delete(0, END)
self.entry_Dir_Path_Delete.insert(0, Manage_Record_GUI.DirPath_list[selected_index])
self.entry_File_Path_Delete.delete(0, END)
self.entry_File_Path_Delete.insert(0, Manage_Record_GUI.FilePath_list[selected_index])
def ManageRecord_Delete_callback(self,event):
ManageRecord_Delete(self.frm_Manage_Record,self.entry_Keyword_Query.get(), self.Combobox_Index, self.entry_Description_Delete, self.entry_Keywords_Delete, self.entry_Dir_Path_Delete, self.entry_File_Path_Delete, Manage_Record_GUI.index_list, Manage_Record_GUI.description_list, Manage_Record_GUI.keywords_list,Manage_Record_GUI.DirPath_list, Manage_Record_GUI.FilePath_list,Manage_Record_GUI.MatchedRecordStr)
def ManageRecord_Delete_Button(object, index,RecordStrMap,Dir_Path, File_Path):
if index == "" or RecordStrMap == "" or File_Path == "":
object.wm_attributes("-topmost", 0)
showerror("Parameter Error", "Please configure the parameter correctly!")
object.wm_attributes("-topmost", 1)
return
RecordStr = RecordStrMap[index]
#delete file or directory and renew record in Record.txt
if os.path.isdir(Dir_Path) and Dir_Path != "":
object.wm_attributes("-topmost", 0)
result = askyesno("Caution","Do you really want to delete %s?"%Dir_Path)
if result == True:
shutil.rmtree(Dir_Path)#delete directory
Delete_Record_RenewRecordtxt(Dir_Path,RecordStr)#delete related record in file Record.txt
showinfo("Success","\'"+ Dir_Path +"\'"+" directory was deleted")
object.wm_attributes("-topmost", 1)
else:
object.wm_attributes("-topmost", 0)
result = askyesno("Caution","Do you really want to delete %s?"%File_Path)
if result == True:
os.remove(File_Path)#delete file
Delete_Record_RenewRecordtxt(File_Path,RecordStr)#delete related record in file Record.txt
showinfo("Success","\'"+ File_Path +"\'"+" file was deleted")
object.wm_attributes("-topmost", 1)
def Delete_Record_RenewRecordtxt(Path,RecordStr):
Path_CodeTypeRecordPath = str.replace(Path, Path.split('\\')[-2] if Path.split('\\')[-1] == '' else Path.split('\\')[-1], "",1)
Path_TypeRecordPath = str.replace(Path_CodeTypeRecordPath, Path_CodeTypeRecordPath.split('\\')[-2] if Path_CodeTypeRecordPath.split('\\')[-1] == '' else Path_CodeTypeRecordPath.split('\\')[-1], "",1)
CodeType_Recordtxt = Path_CodeTypeRecordPath + "\\Record.txt"
Type_Recordtxt = Path_TypeRecordPath + "\\Record.txt"
fid = open(CodeType_Recordtxt,"r")
lines = fid.readlines()
fid.close()
fid = open(CodeType_Recordtxt,"wt")
for line in lines:
if line == RecordStr:
continue
else:
fid.write(line)
fid.close()
fid = open(Type_Recordtxt,"r")
lines = fid.readlines()
fid.close()
fid = open(Type_Recordtxt,"wt")
for line in lines:
if line == RecordStr:
continue
else:
fid.write(line)
fid.close()
#Manage Directory GUI
def Call_Manage_Dir_GUI(object):
Manage_Dir_GUI_1 = Manage_Dir_GUI(object)
class Manage_Dir_GUI:
#using Type, Code_Type to find the Record.txt file and locate the position to add record
cmbEditComboList_Code_Type = []
def __init__(self, object):
self.object = object
self.frm_Manage_Dir = Toplevel(self.object)
self.frm_Manage_Dir.attributes("-toolwindow", 1)
self.frm_Manage_Dir.wm_attributes("-topmost", 1)
self.object.wm_attributes("-disabled", 1)#Disable parent window
self.frm_Manage_Dir.title("Manage Directory")
self.frm_Manage_Dir.resizable(False,False)
self.Init()
def TraveringCodeTypeFiles(self,event):
self.Combobox_Code_Type['value'] = ("")
Type = self.Combobox_Type.get()
# Manage_Dir_GUI.cmbEditComboList_Code_Type = self.Combobox_Code_Type.get()
Type_Dict = {"Function Module": PathPack.Path.__init__.Path_FuncModule,"Project": PathPack.Path.__init__.Path_Project} #Map Type to related directory
cmbEditComboList_Code_Type_Const = {"CPlusPlus": "C++","Java": "Java","Python": "Python","CSharp": "C#","SQL": "SQL","HTML_CSS": "Html/CSS","C_Lang": "C_Lang","Matlab": "Matlab"}
if Type in Type_Dict:
if Type != "" and os.path.exists(Type_Dict[Type]):
Dirs = [d for d in os.listdir(Type_Dict[Type]) if os.path.isdir(os.path.join(Type_Dict[Type],d))]#list only the directory under given directory
else:
Dirs = [d for d in os.listdir(PathPack.Path.__init__.AbsolutePath + "\\" + Type) if os.path.isdir(os.path.join(PathPack.Path.__init__.AbsolutePath + "\\" + Type,d))]#list only the directory under given directory
self.Combobox_Code_Type['value'] = (Dirs)
def TraveringTypeFiles(self,event):
self.Combobox_Type['value'] = ("")
# Manage_Dir_GUI.cmbEditComboList_Code_Type = self.Combobox_Code_Type.get()
Dirs = [d for d in os.listdir(PathPack.Path.__init__.AbsolutePath) if os.path.isdir((os.path.join(PathPack.Path.__init__.AbsolutePath,d)))]#list only the directory under given directory
if '.git' in Dirs:
Dirs.remove('.git')
if 'CodingPartner' in Dirs:
Dirs.remove('CodingPartner')
if 'FuncModule' in Dirs:
Dirs.remove('FuncModule')
Dirs.append('Function Module')
self.Combobox_Type['value'] = (Dirs)
def EnableButton(self):#when current windows closes, the parent window will be enable.
self.object.wm_attributes("-disabled", 0)#Enable parent window
self.frm_Manage_Dir.destroy()#Destory current window
def Init(self):
#GUI Related
#Type
self.label_Type = Label(self.frm_Manage_Dir,anchor = "nw",text="Type") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Type.grid(row=0, column = 0, columnspan = 2, rowspan = 3)
cmbEditComboList_Type = ['Function Module','Project',]
self.Combobox_Type = Combobox(self.frm_Manage_Dir, values = cmbEditComboList_Type) #anchor:must be n, ne, e, se, s, sw, w, nw, or center , state = 'readonly'
self.Combobox_Type.grid(row=0, column = 2, columnspan = 10, rowspan = 3)
self.Combobox_Type.bind('<Button-1>', self.TraveringTypeFiles)#<ComboboxSelected>
#Code Type
self.label_Code_Type = Label(self.frm_Manage_Dir,anchor = "nw",text="Code Type") #anchor:must be n, ne, e, se, s, sw, w, nw, or center
self.label_Code_Type.grid(row=0, column = 12, columnspan = 2, rowspan = 3)
self.Combobox_Code_Type = Combobox(self.frm_Manage_Dir, values = Manage_Dir_GUI.cmbEditComboList_Code_Type)
self.Combobox_Code_Type.grid(row=0, column = 14, columnspan = 4, rowspan = 3)
self.Combobox_Code_Type.bind('<Button-1>', self.TraveringCodeTypeFiles)#<ComboboxSelected>
#Add
self.button_Add = Button(self.frm_Manage_Dir, text = "Add" , command = lambda:ManageDirectory_Add(self.frm_Manage_Dir,self.Combobox_Type.get(), self.Combobox_Code_Type.get()))#Button used to add Direcotory
self.button_Add.grid(row=4, column=9, columnspan = 2)
self.button_Delete = Button(self.frm_Manage_Dir, text = "Delete" , command = lambda:ManageDirectory_Delete(self.frm_Manage_Dir,self.Combobox_Type.get(), self.Combobox_Code_Type.get()))#Button used to add record in Record.txt , command = lambda:OpenFile(FilePath,entry_Path, Combobox_Type.get())
self.button_Delete.grid(row=4, column=14, columnspan = 2)
#Delete
#make the current main window lay in the middle of screen
self.frm_Manage_Dir.update_idletasks()
w = self.frm_Manage_Dir.winfo_screenwidth()
h = self.frm_Manage_Dir.winfo_screenheight()
size = tuple(int(_) for _ in self.frm_Manage_Dir.geometry().split('+')[0].split('x'))
x = w/2 - size[0]/2
y = h/2 - size[1]/2
self.frm_Manage_Dir.geometry("%dx%d+%d+%d" % (size + (x, y)))
self.frm_Manage_Dir.protocol ("WM_DELETE_WINDOW", self.EnableButton)
def OpenDir(Path,object, Type, Window_Name):#Get Directory
Window_Name.wm_attributes("-topmost", 0)
Path = ''#askopenfilename
Path = filedialog.askdirectory()
object.delete(0, END)
object.insert(1, Path)
Window_Name.wm_attributes("-topmost", 1)
def OpenFile(Path,object, Type, Window_Name):#Get File Directory
Window_Name.wm_attributes("-topmost", 0)
Path = ''#askopenfilename
Path = filedialog.askopenfilename()
object.delete(0, END)
object.insert(1, Path)
Window_Name.wm_attributes("-topmost", 1)
<file_sep>/FuncModule/CPlusPlus/algorithm_3.cpp
/*
@que:写一个生成微信红包的算法,输入值是钱数、红包个数,输出一个数组。
@author:yangchun,chen
@date:3/27/2018
@iqiyi,shanghai
*/
#include<iostream>
#include<vector>
#include<time.h>
#include <numeric>
#include <stdlib.h>
using namespace std;
float accumulate(vector<float>::iterator iter_begin, vector<float>::iterator iter_end){
float sum = 0;
for(vector<float>::iterator item = iter_begin; item != iter_end; item++){
sum += *item;
}
return sum;
}
const vector<float> wechat_redpacket(const float& money, const int&num){
vector<float> money_arr;
srand((unsigned)time(NULL));
//产生1-100的随机数,最小抢到的是0.01元
int num_cnt = num;
while(num_cnt--){
money_arr.push_back(rand()%100 + 1);
}
//统计num个随机数的和
int sum = accumulate(money_arr.begin(), money_arr.end());
//将每个随机数占和的比例乘以红包额度就是抢到的红包,最后一个红包为剩余的额度
float used_money = 0.0;
for(vector<float>::iterator item=money_arr.begin(); item!=money_arr.end();item++){
if(item != money_arr.end()-1){
*item = money * (*item * 1.0/sum);
//精确到2位小数
*item = (int)(*item * 100) * 1.0 / 100;
used_money += *item;
}
else{
cout << "money:" << money << endl;
cout << "used_money:" << used_money << endl;
cout << "left_money:" << money - used_money << endl;
*item = money - used_money;
}
}
return money_arr;
}
int main(){
float money;
int num;
cout << "Please input money:" << endl;
cin >> money;
cout << "Please input num:" << endl;
cin >> num;
const vector<float> readpacket_list = wechat_redpacket(money,num);
cout << "wechat red packet result list:" << endl;
int i = 0;
for(auto &item:readpacket_list ){
cout << i++ << " " << item << " ";
cout << endl;
}
}
<file_sep>/CodingPartner/FuncPack/Project_Manage/__init__.py
__author__ = 'JD'
#Add, Delete, Modify and Query code under the Project directory
<file_sep>/FuncModule/CPlusPlus/MergeBinaryTrees.cpp
/**
@question:https://leetcode.com/problems/merge-two-binary-trees/description/
@Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
Example 1:
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7
@author:yangchun,chen
@date:20180309
*/
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void mergeTreesRecur(TreeNode* t1, TreeNode *t2){
if(t1){
if(t2){
t1->val += t2->val;
if(t1->left == NULL && t1->right != NULL){
t1->left = t2->left;
mergeTreesRecur(t1->right,t2->right);
}
else if(t1->right == NULL && t1->left != NULL){
t1->right = t2->right;
mergeTreesRecur(t1->left,t2->left);
}
else if(t1->right == NULL && t1->left == NULL){
t1->left = t2->left;
t1->right = t2->right;
}
else if(t1->left != NULL && t1->right != NULL)
{
mergeTreesRecur(t1->right,t2->right);
mergeTreesRecur(t1->left,t2->left);
}
}
}
}
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
TreeNode *head = t1;
if(t1 == NULL || t2 == NULL){
return t1 == NULL ? t2 : t1;
}
mergeTreesRecur(t1,t2);
return head;
}
int main(){
TreeNode A1(1),A2(2),B1(3),B2(4),B5(5);
A1.left = &A2;
B1.left = &B2;
B1.right = &B5;
TreeNode *result = mergeTrees(&A1,&B1);
cout << result->val << " " << result->left->val << " " << result->right->val << endl;
return 0;
}
<file_sep>/Project/Python/DeepInsight/que_1.py
import numpy as np
import math
import sys
import os
MAX = 1e5
#declare an input array and intermediate result array
ar = [[MAX,MAX]]*50
br = [[MAX,MAX]]*50
sys.setrecursionlimit(1500)
#calculate Euclidean distance
def Cal_Dis(point1,point2):
return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)
def Find_Smallest_Len(nStart,nEnd):
#print("nStart %d,nEnd:%d"%(nStart,nEnd))
if nStart == nEnd:
return MAX
nMid = int((nStart + nEnd) / 2)
#print("nMid %d"%nMid)
#use "divide and conquer" idea
Dis = min(Find_Smallest_Len(nStart, nMid),Find_Smallest_Len(nMid+1, nEnd))
nTail = 0
#get left points around mid within "Dis"
nIndex = nMid
while nIndex >= nStart:
if ar[nMid][0] - ar[nIndex][0] < Dis:
br[nTail] = ar[nIndex]
nTail += 1
nIndex -= 1
#get right points around mid within "Dis"
nIndex = nMid + 1
while nIndex < nEnd:
if ar[nIndex][0] - ar[nMid][0] < Dis:
br[nTail] = ar[nIndex]
nTail += 1
nIndex += 1
#sorted by y coordinate
#print(br)
br[0:nTail] = sorted(br[0:nTail],key=lambda x:x[1])
for nIndex in (0,1,nTail):
nj = nIndex + 1
while nj < nTail:
if br[nj][1] - br[nIndex][1] < Dis:
Dis1 = Cal_Dis(br[nIndex],br[nj])
if Dis > Dis1:
Dis = min(Dis,Dis1)
nj += 1
return Dis
#main
print("Please input points set txt file name:(like \"data.txt\")")
fileName = raw_input()
file = open(fileName)
lines = file.readlines()
Input=[]
for line in lines:
temp = line.replace('\n','').split(',')
Input.append([float(temp[0]),float(temp[1])])
print(Input)
ar[0:len(Input)] = sorted(Input,key=lambda x:x[0])
#print(ar)
n = len(Input)
Dis = Find_Smallest_Len(0,n)
print("Smallest Distance:")
print(Dis)
<file_sep>/FuncModule/CPlusPlus/ListSorting/ListSorting/BubbleSorting.cpp
/*
FileName: BubbleSorting.h
Create Time: 2015/09/04
Modify Time:
Author: <NAME>
Owner: <NAME>
Place: 上海交通大学闵行校区微电子楼301室
Reference: 《程序员面试宝典》——13.2.9 如何进行单链表排序
Description: (1)单链表的冒泡排序算法;
*/
#include<stdio.h>
#include<stdlib.h>
#include"BubbleSorting.h"
linklist *head = NULL;//将该行代码放到.h文件中就会编译不通过,why?
linklist* CreateList(int*arr, int len)//由数组创建单链表,首结点未存数据
{
int data;
linklist *pCurrent, *rear;
head = (linklist*)malloc(sizeof(linklist));
rear = head;
int count = 0;
while(count<len)
{
pCurrent = (linklist*)malloc(sizeof(linklist));
pCurrent -> data = arr[count];
rear -> next = pCurrent;
rear = pCurrent;
count++;
}
rear -> next = NULL;
return head;
}
void ShowList(linklist *p)//打印单链表
{
while(p)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void BubbleSortList(linklist *p)//链表冒泡排序
{
linklist *_temp = p ->next;
linklist *_node = p ->next;
int temp;
for(;_temp->next;_temp = _temp -> next)//纯粹控制排序趟数的,n-1趟
{
for(_node = p->next; _node->next; _node = _node ->next)//这其实就是最平常的冒泡排序算法写法,只是由于是链表的缘故,不太方便写成循环次数为n + n-1 + ... + 1 = n*(n+1)/2趟(对应比较次数为n-1+n-2+...+1 = n*(n-1)/2),这里循环次数为n*n,比较次数为(n-1)*n
{
if(_node->data > _node ->next->data)//改变大小号就能改变排序结果升降序顺序
{
temp = _node->data;
_node->data =_node->next->data;
_node->next->data = temp;
}
}
}
}<file_sep>/FuncModule/CPlusPlus/JewelsAndStones.cpp
/**
*
@question:https://leetcode.com/problems/jewels-and-stones/description/
@You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A".
Example 1:
Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2:
Input: J = "z", S = "ZZ"
Output: 0
@author:yangchun,chen
@date:20180309
*/
#include <iostream>
#include <string>
#include <set>
using namespace std;
//complex:o(n*n)
int numJewelsInStones(string J, string S) {
int count = 0;
for(int i = 0; i < J.length(); i++){
for(int j = 0; j < S.length(); j++){
if(J.at(i) == S.at(j)){
count++;
}
}
}
return count;
}
//complex:o(n+m)
int numJewelsInStones_hash(string J, string S) {
int res = 0;
set<char> setJ(J.begin(), J.end());
for (char s : S) if (setJ.count(s)) res++;
return res;
}
int main(){
string J = "sj2w";
string S = "sjjjDKE";
cout << "S:" << S << " J:" << J << endl;
cout << "Has " << numJewelsInStones(J,S) << " jewels in stones!" << endl;
cout << "Has " << numJewelsInStones_hash(J,S) << " jewels in stones!" << endl;
}
<file_sep>/FuncModule/CPlusPlus/ByteDance_Interview1.cpp
/*
@ques:给定a,b,c,d,...,k个有序数组,合并成一个有序数组
@author:yangchun,chen
@date:3/30/2018
@pudong,shanghai
*/
#include<iostream>
using namespace std;
#define N 10
#define NUM 4
int idx=1;
int arr_len = 1;
int InputArr[NUM][N] = {0};
int result[NUM*N] = {0};//a-k个数组
//方法1 单个合并完再跟下一个合并
//将数组a和b合并存放到结果数组result中
void MergeTwoArray(int *a, int len_a,int *b, int len_b){
int i = 0,j=0;
int temp[N*NUM] = {0};
//合并两个数组
while(i < len_a && j < len_b){
if(a[i] > b[j]){
temp[i+j] = b[j];
j++;
}
else{
temp[i+j] = a[i];
i++;
}
}
//将数组剩余元素添加到temp结果中
while(i < len_a){
temp[i+j] = a[i];
i++;
}
while(j < len_b){
temp[i+j] = b[j];
j++;
}
//arr_len存放当前temp数组中数据的长度,idx表示遍历了第几个数组
arr_len = (++idx)*N;
//将temp结果拷贝复制给result数组
memcpy(result,temp,arr_len*sizeof(int));
for(int i = 0; i < NUM*N; i++){
cout << temp[i] << " ";
}
cout << endl << arr_len << endl;
//如果所有数组都遍历完了,就退出
if(idx == NUM){
return;
}
//将当前结果result作为第一个参数,下一个数组作为第二个参数,再递归调用函数
MergeTwoArray(result,arr_len,InputArr[idx],N);
}
int main(){
for(auto i = 0; i < N; i++){
InputArr[0][i] = i;
}
for(auto i = -10; i < -10+N; i++){
InputArr[1][i+N] = i;
}
for(auto i = 12; i < 12+N; i++){
InputArr[2][i-12] = i;
}
for(auto i = 7; i < 7+N; i++){
InputArr[3][i-7] = i;
}
memset(result,0,NUM*N);
//
cout << "input:" << endl;
for(int i = 0; i < NUM; i++){
for(int j = 0; j < N; j++){
cout << InputArr[i][j] << " ";
}
}
cout << endl;
MergeTwoArray(InputArr[0],N,InputArr[1],N);
cout << "result:" << endl;
for(int i = 0; i < NUM*N; i++){
cout << result[i] << " ";
}
cout << endl;
return 0;
}
<file_sep>/FuncModule/CPlusPlus/LargestNumber.cpp
/*
@ques:Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
@author:yangchun,chen
@date:3/29/2018
@pudong,shanghai
*/
#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
using namespace std;
//答案错误,会使得121和12的组合错误
//class Solution {
//public:
// int CalLen(int val){
// int len = 0;
// if(!val){
// return 1;
// }
// while(val){
// val /= 10;
// len++;
// }
// return len;
// }
// string largestNumber(vector<int>& nums) {
// //只有一位时直接返回即可
// if(nums.size() == 1){
// return std::to_string(nums[0]);
// }
// vector<int> vals_len;
// int result_len = 0;
// //统计每个整数长度和总的长度
// for(auto &item:nums){
// int temp = CalLen(item);
// cout << "temp:" << temp << endl;
// result_len += temp;
// vals_len.push_back(temp);
// }
// cout << "result_len:" << result_len << endl;
// //将每位整数都右侧添0到总长度
// for(auto i = 0; i < nums.size(); i++){
// nums[i] = nums[i]*pow(10,result_len - vals_len[i]);
// cout << result_len-vals_len[i] << endl;
// cout << "num:" << nums[i] << endl;
// }
// //对数据整体排序,排序前先保留原vector
// vector<int> nums_backup = nums;
// std::sort(nums.begin(),nums.end(),std::greater<int>());
// string strResult;
// //在还原成原有数据并组成字符串
// for(auto i = 0; i < nums.size(); i++){
// cout << "result:" << endl;
// cout << result_len-vals_len[find(nums_backup.begin(),nums_backup.end(),nums[i]) - nums_backup.begin()] << endl;
// cout << (int)nums[i]/pow(10,result_len-vals_len[i]) << endl;
// strResult = strResult.append(std::to_string((int)(nums[i]/pow(10,result_len-vals_len[find(nums_backup.begin(),nums_backup.end(),nums[i]) - nums_backup.begin()] ))));
// }
// return strResult;
// }
//};
class Solution {
public:
string largestNumber(vector<int>& nums) {
string strLargestNumber;
vector<string> str_nums;
//将数字转换成字符
for(auto &item:nums){
str_nums.push_back(std::to_string(item));
}
//添加自定义函数进行字符串的比较,其实所有能用到排序思想的代码都可以转成排序,直接利用sort的自定义函数,或者是在排序算法中修改排序简单的比较大小为子定义规则
std::sort(str_nums.begin(),str_nums.end(),[](string s1,string s2){return s1+s2>s2+s1;});
for(auto &item:str_nums){
strLargestNumber.append(item);
}
//如果首位是0,说明有多个0
if(strLargestNumber[0] == '0'){
return "0";
}
return strLargestNumber;
}
};
int main(){
Solution s;
int arr[] = {121,12};
vector<int> vec(arr,arr+2);
string result = s.largestNumber(vec);
cout << result << endl;
}
<file_sep>/FuncModule/CPlusPlus/BinarySearch/BinaryRecursionSearch.h
int BinaryRecurSearch(int low, int high, int arr[],int val);
<file_sep>/FuncModule/CPlusPlus/Valid_Anagram.cpp
/*
FileName: Valid_Anagram.cpp
Create Time: 2015/10/26
Modify Time:
Author: <NAME>
Owner: <NAME>
Place: 上海交通大学闵行校区微电子楼301室
Reference: https://leetcode.com/problems/valid-anagram/
Description:
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
*/
class Solution {
public:
bool isAnagram(string s, string t) {
int Map[32] = {0};
if(s.length() != t.length())
return false;
for(int i = 0; i < s.length(); i++)
Map[s[i] - 'a']++;
for(int i = 0; i < t.length(); i++)
Map[t[i]- 'a']--;
for(int i = 0; i < s.length(); i++)
{
if(Map[s[i]- 'a'] != 0)
return false;
}
return true;
}
};<file_sep>/FuncModule/CPlusPlus/CountMaxCharTimes/CountMaxCharTimes/main.cpp
/*
FileName: CountMaxCharTimes
Create Time: 2015/09/18
Modify Time:
Author: <NAME>
Owner: <NAME>
Place: 上海交通大学闵行校区西70宿舍12044
Reference:
Description: (1)寻找输入的字符串中出现次数最多的字符以及出现的次数;
*/
#include<iostream>
#include<string>
#include<map>
#include<algorithm>
using namespace std;
//方法1:使用map机制
map<char,int> Map_char_int;
void CountTimesofChar(string Input)
{
int len = Input.size();
for(int i = 0; i < len; i++)//将字符串利用map进行映射
{
Map_char_int[Input[i]]++;
}
map<char,int>::iterator Max = Map_char_int.begin();//用于存储出现次数最多的iterator变量
(*Max).second = 0;
for(map<char,int>::iterator item = Map_char_int.begin(); item != Map_char_int.end(); item++)//遍历Map,寻找出现次数最多的字符
{
if((*item).second > (*Max).second)//*item取的是key值,而(*item).second取的才是value值
{
Max = item;
}
}
cout << (*Max).first << ":" << (*Max).second << endl;//输出字符串中出现次数最多的字符以及次数
}
//方法2:使用最常用方法,更便捷
void CountTimesofStr(string Input)
{
int TimesofChar[26] = {0};//用于存储各个字符出现的次数
int len = Input.size();
int index=0, MaxTimes=0;//用于统计出现最大次数字符在数据TimesofChar中的位置及次数
for(int i = 0; i < len; i++)
{
TimesofChar[Input[i]-'a']++;
}
for(int i = 0; i < 26; i++)
{
if(TimesofChar[i] > MaxTimes)
{
index = i;
MaxTimes = TimesofChar[i];
}
}
cout << char(index + 'a') << ":" << MaxTimes << endl;
}
int main()
{
cout << "Input a string:" << endl;
string Input;
//方法1
//getline(cin, Input);
//CountTimesofChar(Input);
//方法2
getline(cin, Input);
CountTimesofStr(Input);
return 0;
}
<file_sep>/FuncModule/Python/Floyd-Warshall.py
def ConstructPath(p, i, j):
print("construct path %d to %d"%(i,j))
i,j = int(i), int(j)
if(i==j):
print (i,)
elif(p[i,j] == -30000):
print (i,'-',j)
else:
ConstructPath(p, i, p[i,j]);
print(j,)
import numpy as np
graph = np.array([[0,1],[2,1]])
print("graph:")
print(graph)
v = len(graph)
# path reconstruction matrix
p = np.zeros(graph.shape)
for i in range(0,v):
for j in range(0,v):
p[i,j] = i
if (i != j and graph[i,j] == 0):
p[i,j] = -30000
graph[i,j] = 30000 # set zeros to any large number which is bigger then the longest way
for k in range(0,v):
for i in range(0,v):
for j in range(0,v):
if graph[i,j] > graph[i,k] + graph[k,j]:
graph[i,j] = graph[i,k] + graph[k,j]
p[i,j] = p[k,j]
#show graph matrix
print("output:")
print(graph)
# show p matrix
print("p:")
print(p)
# reconstruct the path from 0 to 4
ConstructPath(p,0,1)
<file_sep>/FuncModule/CPlusPlus/BinarySearch/BinaryRecursionSearch.cpp
/**
@author:yangchun,chen
@date:20180308
*/
#include"BinaryRecursionSearch.h"
int BinaryRecurSearch(int low, int high, int arr[],int val){
if(low > high){
return -1;
}
int mid = (low + high)/2;
if(arr[mid] == val){
return mid;
}
else if(arr[mid] > val){
BinaryRecurSearch(low,mid-1,arr,val);
}
else{
BinaryRecurSearch(mid+1,high,arr,val);
}
}
<file_sep>/FuncModule/CPlusPlus/BinarySearch/BinaryTree.cpp
/*
FileName: BinaryTree.cpp
Create Time: 2015/09/03
Modify Time:
Author: <NAME>
Owner: <NAME>
Place: 上海交通大学闵行校区微电子楼301室
Reference: https://leetcode.com/problems/minimum-depth-of-binary-tree/
Description: (1)二叉树的最小深度、最大深度递归算法;
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//求二叉树的最小深度
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
if(!root->left) return 1 + minDepth(root->right);//这两条语句是为了避免因为某个子树为空而直接返回零,而此时这种情况并不满足要求,因为不是叶节点,在求最小深度的时候不能缺,求最大深度的时候可缺
if(!root->right) return 1 + minDepth(root->left);
return 1+min(minDepth(root->left),minDepth(root->right));
}
};
//求二叉树的最大深度,方法1和方法2其实是一样的,只是形式稍微有点不同而已
//方法1
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
/* if(!root->left) return 1 + maxDepth(root->right);//这两条语句是为了避免因为某个子树为空而直接返回零,而此时这种情况并不满足要求,因为不是叶节点,在求最小深度的时候不能缺,求最大深度的时候可缺
if(!root->right) return 1 + maxDepth(root->left); */
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
};
//方法2
class Solution {
public:
int maxDepth(TreeNode *root) {
return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1;//采用后续遍历
}
};<file_sep>/Project/Python/monitor_process/mysetup.py
from distutils.core import setup
import py2exe
#from glob import glob
#import sys
#sys.argv.append('py2exe')
#data_files = [("Microsoft.VC100.CRT", glob(r'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\redist\x86\Microsoft.VC100.CRT\*.*')),
#("Microsoft.VC90.CRT", glob(r'C:\Program Files (x86)\Common Files\Microsoft Shared\VSTO\10.0\*.*'))]
#sys.path.append("C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\redist\\x86\\Microsoft.VC100.CRT")
#sys.path.append("C:\\Program Files (x86)\\Common Files\\Microsoft Shared\\VSTO\\10.0")
#setup(data_files=data_files,
setup(console=["monitor_process_ex_py3.py"],
options = { "py2exe": { "dll_excludes": ["msvcr71.dll","IPHLPAPI.DLL","NSI.dll","WINNSI.DLL","WTSAPI32.dll"] } })
<file_sep>/FuncModule/CPlusPlus/findDisappearedNumbers.cpp
/*
@ques:Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
@author:shujie,wang
@date:3/31/2018
@pudong,shanghai
*/
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
//初始化一个数组为0
vector<int> result(nums.size(),0);
//遍历数组如果值存在在输出数组相应位置存1
for(auto &item:nums){
result[item-1] = 1;
}
nums.clear();
//遍历结果将为0的存储到输出vector中
for(int i = 0; i < result.size();i++){
if(result[i] == 0){
nums.push_back(i+1);
}
}
return nums;
}
};
int main(){
int Arr[6] = {4,3,2,6,1,1};
vector<int> vec(Arr,Arr+6);
Solution s;
vector<int> result = s.findDisappearedNumbers(vec);
for(auto &item:result){
cout << item << " " ;
}
cout << endl;
return 0;
}
|
b5f17a20d0a50aa058299d9e8029ee515f4df94e
|
[
"Makefile",
"C",
"Java",
"Markdown",
"Text",
"Python",
"C++"
] | 75 |
Makefile
|
SpartacusIn21/SourceCodeControl
|
94137d836b3bc35e1d387b20388c0a4cc5b8de9e
|
a42eb479ce5a261cc2fb67c2062c29ad686af733
|
refs/heads/master
|
<repo_name>JasonVann/DLResources<file_sep>/DL_ML Datasets.md
# DLResources
DL/ML Datasets
NLP
Yelp Review dataset
https://www.kaggle.com/omkarsabnis/yelp-reviews-dataset
https://www.yelp.com/dataset/
Quora
https://www.kaggle.com/c/quora-question-pairs
http://knowitall.cs.washington.edu/paralex/
CV
http://yfcc100m.appspot.com/?
Object Detection
https://www.kaggle.com/c/google-ai-open-images-object-detection-track/data
http://host.robots.ox.ac.uk/pascal/VOC/
|
fbe26071c38251940781e50d288bebe284359c33
|
[
"Markdown"
] | 1 |
Markdown
|
JasonVann/DLResources
|
8dfc9460dc66df657e8121a3e034faf2aa283682
|
0b20b49f1c93de5f25fcbc57c763a23f39069412
|
refs/heads/master
|
<repo_name>grab/swift-leak-check<file_sep>/Sources/SwiftLeakCheck/Stack.swift
//
// Stack.swift
// LeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 27/10/2019.
//
public struct Stack<T> {
private var items: [T] = []
public init() {}
public init(items: [T]) {
self.items = items
}
public mutating func push(_ item: T) {
items.append(item)
}
@discardableResult
public mutating func pop() -> T? {
if !items.isEmpty {
return items.removeLast()
} else {
return nil
}
}
public mutating func reset() {
items.removeAll()
}
public func peek() -> T? {
return items.last
}
}
extension Stack: Collection {
public var startIndex: Int {
return items.startIndex
}
public var endIndex: Int {
return items.endIndex
}
public func index(after i: Int) -> Int {
return items.index(after: i)
}
public subscript(_ index: Int) -> T {
return items[items.count - index - 1]
}
}
<file_sep>/Sources/SwiftLeakCheck/Utility.swift
//
// Utility.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 05/12/2019.
//
import Foundation
extension Collection where Index == Int {
subscript (safe index: Int) -> Element? {
if index < 0 || index >= count {
return nil
}
return self[index]
}
}
<file_sep>/README.md
# Swift Leak Checker
A framework, a command-line tool that can detect potential memory leak caused by strongly captured `self` in `escaping` closure
<img src=images/leakcheck_sample.png width=800/>
# Example
Some examples of memory leak that are detected by the tool:
```swift
class X {
private var handler: (() -> Void)!
private var anotherHandler: (() -> Void)!
func setup() {
handler = {
self.doSmth() // <- Leak
}
anotherHandler = { // Outer closure
doSmth { [weak self] in // <- Leak
// .....
}
}
}
}
```
For first leak, `self` holds a strong reference to `handler`, and `handler` holds a strong reference to `self`, which completes a retain cycle.
For second leak, although `self` is captured weakly by the inner closure, but `self` is still implicitly captured strongly by the outer closure, which leaks to the same problem as the first leak
# Usage
There're 2 ways to use this tool: the fastest way is to use the provided SwiftLeakChecker target and start detecting leaks in your code, or you can drop the SwiftLeakCheck framework in your code
and start building your own tool
### SwiftLeakChecker
There is a SwiftLeakChecker target that you can run directly from XCode or as a command line.
**To run from XCode:**
Edit the `SwiftLeakChecker` scheme and change the `/path/to/your/swift/file/or/folder` to an absolute path of a Swift file or directory. Then hit the `Run` button (or `CMD+R`)
<img src="images/leakcheck_sample_xcode.png" width=800/>
**To run from command line:**
```
./SwiftLeakChecker path/to/your/swift/file/or/folder
```
### Build your own tool
The SwiftLeakChecker target is ready to be used as-is. But if you want to build your own tool, do more customisation etc.., then you can follow these steps.
Note: Xcode 11 or later or a Swift 5.2 toolchain or later with the Swift Package Manager is required.
Add this repository to the `Package.swift` manifest of your project:
```swift
// swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "MyAwesomeLeakDetector",
dependencies: [
.package(url: "This repo .git url", .exact("package version")),
],
targets: [
.target(name: "MyAwesomeLeakDetector", dependencies: ["SwiftLeakCheck"]),
]
)
```
Then, import `SwiftLeakCheck` in your Swift code
To create a leak detector and start detecting:
```swift
import SwiftLeakCheck
let url = URL(fileURLWithPath: "absolute/path/to/your/swift/file/or/folder")
let detector = GraphLeakDetector()
let leaks = detector.detect(url)
leaks.forEach { leak in
print("\(leak)")
}
```
# Leak object
Each `Leak` object contains `line`, `column` and `reason` info.
```
{
"line":41,
"column":7,
"reason":"`self` is strongly captured here, from a potentially escaped closure."
}
```
# CI and Danger
The image on top shows a leak issue that was reported by our tool running on Gitlab CI. We use [Danger](https://github.com/danger/danger) to report the `line` and `reason` of every issue detected.
# How it works
We use [SourceKit](http://jpsim.com/uncovering-sourcekit) to get the [AST](http://clang.llvm.org/docs/IntroductionToTheClangAST.html) representation of the source file, then we travel the AST to detect for potential memory leak.
Currently we only check if `self` is captured strongly in an escaping closure, which is one specific case that causes memory leak
To do that, 3 things are checked:
**1. Check if a reference captures `self`**
```swift
block { [weak self] in
guard let strongSelf = self else { return }
let x = SomeClass()
strongSelf.doSmth { [weak strongSelf] in
guard let innerSelf = strongSelf else { return }
x.doSomething()
}
}
```
In this example, `innerSelf` captures `self`, because it is originated from `strongSelf` which is originated from `self`
`x` is also a reference but doesn't capture `self`
**2. Check if a closure is non-escaping**
We use as much information about the closure as possible to determine if it is non-escaping or not.
In the example below, `block` is non-escaping because it's not marked as `@escaping` and it's non-optional
```
func doSmth(block: () -> Void) {
...
}
```
Or if it's anonymous closure, it's non-escaping
```swift
let value = {
return self.doSmth()
}()
```
We can check more complicated case like this:
```swift
func test() {
let block = {
self.xxx
}
doSmth(block)
}
func doSmth(_ block: () -> Void) {
....
}
```
In this case, `block` is passed to a function `doSmth` and is not marked as `@escaping`, hence it's non-escaping
**3. Whether an escaping closure captures self stronlgy from outside**
```swift
block { [weak self] in
guard let strongSelf = self else { return }
self?.doSmth {
strongSelf.x += 1
}
}
```
In this example, we know that:
1. `strongSelf` refers to `self`
2. `doSmth` is escaping (just for example)
3. `strongSelf` (in the inner closure) is defined from outside, and it captures `self` strongly
# False-positive alarms
### If we can't determine if a closure is escaping or non-escaping, we will just treat it as escaping.
It can happen when for eg, the closure is passed to a function that is defined in other source file.
To overcome that, you can define custom rules which have logic to classify a closure as escaping or non-escaping.
# Non-escaping rules
By default, we already did most of the legworks trying to determine if a closure is non-escaping (See #2 of `How it works` section)
But in some cases, there's just not enough information in the source file.
For eg, we know that a closure passed to `DispatchQueue.main.async` will be executed and gone very soon, hence it's safe to treat it as non-escaping. But the `DispatchQueue` code is not defined in the current source file, thus we don't have any information about it.
The solution for this is to define a non-escaping rule. A non-escaping rule is a piece of code that takes in a closure expression and tells us whether the closure is non-escaping or not.
To define a non-escaping rule, extend from `BaseNonEscapeRule` and override `func isNonEscape(arg: FunctionCallArgumentSyntax,....) -> Bool`
Here's a rule that matches `DispatchQueue.main.async` or `DispatchQueue.global(qos:).asyncAfter` :
```swift
open class DispatchQueueRule: NonEscapeRule {
open override isNonEscape(arg: FunctionCallArgumentSyntax?, funcCallExpr: FunctionCallExprSyntax,, graph: Graph) -> Bool {
// Signature of `async` function
let asyncSignature = FunctionSignature(name: "async", params: [
FunctionParam(name: "execute", isClosure: true)
])
// Predicate to match DispatchQueue.main
let mainQueuePredicate = ExprSyntaxPredicate.memberAccess("main", base: ExprSyntaxPredicate.name("DispatchQueue"))
let mainQueueAsyncPredicate = ExprSyntaxPredicate.funcCall(asyncSignature, base: mainQueuePredicate)
if funcCallExpr.match(mainQueueAsyncPredicate) { // Matched DispatchQueue.main.async(...)
return true
}
// Signature of `asyncAfter` function
let asyncAfterSignature = FunctionSignature(name: "asyncAfter", params: [
FunctionParam(name: "deadline"),
FunctionParam(name: "execute", isClosure: true)
])
// Predicate to match DispatchQueue.global(qos: ...) or DispatchQueue.global()
let globalQueuePredicate = ExprSyntaxPredicate.funcCall(
FunctionSignature(name: "global", params: [
FunctionParam(name: "qos", canOmit: true)
]),
base: ExprSyntaxPredicate.name("DispatchQueue")
)
let globalQueueAsyncAfterPredicate = ExprSyntaxPredicate.funcCall(asyncAfterSignature, base: globalQueuePredicate)
if funcCallExpr.match(globalQueueAsyncAfterPredicate) {
return true
}
// Doesn't match either function
return false
}
}
```
Here's another example of rule that matches `UIView.animate(withDurations: animations:)`:
```swift
open class UIViewAnimationRule: BaseNonEscapeRule {
open override func isNonEscape(arg: FunctionCallArgumentSyntax?, funcCallExpr: FunctionCallExprSyntax, graph: Graph) -> Bool {
let signature = FunctionSignature(name: "animate", params: [
FunctionParam(name: "withDuration"),
FunctionParam(name: "animations", isClosure: true)
])
let predicate = ExprSyntaxPredicate.funcCall(signature, base: ExprSyntaxPredicate.name("UIView"))
return funcCallExpr.match(predicate)
}
}
```
After creating the non-escaping rule, pass it to the leak detector:
```swift
let leakDetector = GraphLeakDetector(nonEscapingRules: [DispatchQueueRule(), UIViewAnimationRule()])
```
# Predefined non-escaping rules
There're some ready-to-be-used non-escaping rules:
**1. DispatchQueueRule**
We know that a closure passed to `DispatchQueue.main.async` or its variations is escaping, but the closure will be executed very soon and destroyed after that. So even if it holds a strong reference to `self`, the reference
will be gone quickly. So it's actually ok to treat it as non-escaping
**3. UIViewAnimationRule**
UIView static animation functions. Similar to DispatchQueue, UIView animation closures are escaping but will be executed then destroyed quickly.
**3. UIViewControllerAnimationRule**
UIViewController's present/dismiss functions. Similar to UIView animation rule.
**4. CollectionRules**
Swift Collection map/flatMap/compactMap/sort/filter/forEach. All these Swift Collection functions take in a non-escaping closure
# Write your own detector
In case you want to make your own detector instead of using the provided GraphLeakDetector, create a class that extends from `BaseSyntaxTreeLeakDetector` and override the function
```swift
class MyOwnLeakDetector: BaseSyntaxTreeLeakDetector {
override func detect(_ sourceFileNode: SourceFileSyntax) -> [Leak] {
// Your own implementation
}
}
// Create an instance and start detecting leaks
let detector = MyOwnLeakDetector()
let url = URL(fileURLWithPath: "absolute/path/to/your/swift/file/or/folder")
let leaks = detector.detect(url)
```
### Graph
Graph is the brain of the tool. It processes the AST and give valuable information, such as where a reference is defined, or if a closure is escaping or not.
You probably want to use it if you create your own detector:
```swift
let graph = GraphBuilder.buildGraph(node: sourceFileNode)
```
# Note
1. To check a source file, we use only the AST of that file, and not any other source file. So if you call a function that is defined elsewhere, that information is not available.
2. For non-escaping closure, there's no need to use `self.`. This can help to prevent false-positive
# License
This library is available as open-source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
<file_sep>/Sources/SwiftLeakCheck/BaseSyntaxTreeLeakDetector.swift
//
// BaseSyntaxTreeLeakDetector.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 09/12/2019.
//
import SwiftSyntax
open class BaseSyntaxTreeLeakDetector: LeakDetector {
public init() {}
public func detect(content: String) throws -> [Leak] {
let node = try SyntaxRetrieval.request(content: content)
return detect(node)
}
open func detect(_ sourceFileNode: SourceFileSyntax) -> [Leak] {
fatalError("Implemented by subclass")
}
}
<file_sep>/Sources/SwiftLeakCheck/Graph.swift
//
// Graph.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 11/11/2019.
//
import SwiftSyntax
public protocol Graph {
var sourceFileScope: SourceFileScope { get }
/// Return the corresponding scope of a node if the node is of scope-type (class, func, closure,...)
/// or return the enclosing scope if the node is not scope-type
/// - Parameter node: The node
func scope(for node: Syntax) -> Scope
/// Get the scope that encloses a given node
/// Eg, Scopes that enclose a func could be class, enum,...
/// Or scopes that enclose a statement could be func, closure,...
/// If the node is not enclosed by a scope (eg, sourcefile node), return the scope of the node itself
/// - Parameter node: A node
/// - Returns: The scope that encloses the node
func enclosingScope(for node: Syntax) -> Scope
/// Return the TypeDecl that encloses a given node
/// - Parameter node: given node
func enclosingTypeDecl(for node: Syntax) -> TypeDecl?
/// Find the nearest scope to a symbol, that can resolve the definition of that symbol
/// Usually it is the enclosing scope of the symbol
func closetScopeThatCanResolveSymbol(_ symbol: Symbol) -> Scope?
func resolveExprType(_ expr: ExprSyntax) -> TypeResolve
func resolveVariableType(_ variable: Variable) -> TypeResolve
func resolveType(_ type: TypeSyntax) -> TypeResolve
func getAllRelatedTypeDecls(from typeDecl: TypeDecl) -> [TypeDecl]
func getAllRelatedTypeDecls(from typeResolve: TypeResolve) -> [TypeDecl]
func resolveVariable(_ identifier: IdentifierExprSyntax) -> Variable?
func getVariableReferences(variable: Variable) -> [IdentifierExprSyntax]
func resolveFunction(_ funcCallExpr: FunctionCallExprSyntax) -> (Function, Function.MatchResult.MappingInfo)?
func isClosureEscape(_ closure: ClosureExprSyntax, nonEscapeRules: [NonEscapeRule]) -> Bool
func isCollection(_ node: ExprSyntax) -> Bool
}
final class GraphImpl: Graph {
enum SymbolResolve {
case variable(Variable)
case function(Function)
case typeDecl(TypeDecl)
var variable: Variable? {
switch self {
case .variable(let variable): return variable
default:
return nil
}
}
}
private var mapScopeNodeToScope = [ScopeNode: Scope]()
private var cachedSymbolResolved = [Symbol: SymbolResolve]()
private var cachedReferencesToVariable = [Variable: [IdentifierExprSyntax]]()
private var cachedVariableType = [Variable: TypeResolve]()
private var cachedFunCallExprType = [FunctionCallExprSyntax: TypeResolve]()
private var cachedClosureEscapeCheck = [ClosureExprSyntax: Bool]()
let sourceFileScope: SourceFileScope
init(sourceFileScope: SourceFileScope) {
self.sourceFileScope = sourceFileScope
buildScopeNodeToScopeMapping(root: sourceFileScope)
}
private func buildScopeNodeToScopeMapping(root: Scope) {
mapScopeNodeToScope[root.scopeNode] = root
root.childScopes.forEach { child in
buildScopeNodeToScopeMapping(root: child)
}
}
}
// MARK: - Scope
extension GraphImpl {
func scope(for node: Syntax) -> Scope {
guard let scopeNode = ScopeNode.from(node: node) else {
return enclosingScope(for: node)
}
return scope(for: scopeNode)
}
func enclosingScope(for node: Syntax) -> Scope {
guard let scopeNode = node.enclosingScopeNode else {
let result = scope(for: node)
assert(result == sourceFileScope)
return result
}
return scope(for: scopeNode)
}
func enclosingTypeDecl(for node: Syntax) -> TypeDecl? {
var scopeNode: ScopeNode! = node.enclosingScopeNode
while scopeNode != nil {
if scopeNode.type.isTypeDecl {
return scope(for: scopeNode).typeDecl
}
scopeNode = scopeNode.enclosingScopeNode
}
return nil
}
func scope(for scopeNode: ScopeNode) -> Scope {
guard let result = mapScopeNodeToScope[scopeNode] else {
fatalError("Can't find the scope of node \(scopeNode)")
}
return result
}
func closetScopeThatCanResolveSymbol(_ symbol: Symbol) -> Scope? {
let scope = enclosingScope(for: symbol.node)
// Special case when node is a closure capture item, ie `{ [weak self] in`
// We need to examine node wrt closure's parent
if symbol.node.parent?.is(ClosureCaptureItemSyntax.self) == true {
if let parentScope = scope.parent {
return parentScope
} else {
fatalError("Can't happen")
}
}
if symbol.node.hasAncestor({ $0.is(InheritedTypeSyntax.self) }) {
return scope.parent
}
if symbol.node.hasAncestor({ $0.is(ExtensionDeclSyntax.self) && symbol.node.isDescendent(of: $0.as(ExtensionDeclSyntax.self)!.extendedType._syntaxNode) }) {
return scope.parent
}
return scope
}
}
// MARK: - Symbol resolve
extension GraphImpl {
enum ResolveSymbolOption: Equatable, CaseIterable {
case function
case variable
case typeDecl
}
func _findSymbol(_ symbol: Symbol,
options: [ResolveSymbolOption] = ResolveSymbolOption.allCases,
onResult: (SymbolResolve) -> Bool) -> SymbolResolve? {
var scope: Scope! = closetScopeThatCanResolveSymbol(symbol)
while scope != nil {
if let result = cachedSymbolResolved[symbol], onResult(result) {
return result
}
if let result = _findSymbol(symbol, options: options, in: scope, onResult: onResult) {
cachedSymbolResolved[symbol] = result
return result
}
scope = scope?.parent
}
return nil
}
func _findSymbol(_ symbol: Symbol,
options: [ResolveSymbolOption] = ResolveSymbolOption.allCases,
in scope: Scope,
onResult: (SymbolResolve) -> Bool) -> SymbolResolve? {
let scopesWithRelatedTypeDecl: [Scope]
if let typeDecl = scope.typeDecl {
scopesWithRelatedTypeDecl = getAllRelatedTypeDecls(from: typeDecl).map { $0.scope }
} else {
scopesWithRelatedTypeDecl = [scope]
}
for scope in scopesWithRelatedTypeDecl {
if options.contains(.variable) {
if case let .identifier(node) = symbol, let variable = scope.getVariable(node) {
let result: SymbolResolve = .variable(variable)
if onResult(result) {
cachedReferencesToVariable[variable] = (cachedReferencesToVariable[variable] ?? []) + [node]
return result
}
}
}
if options.contains(.function) {
for function in scope.getFunctionWithSymbol(symbol) {
let result: SymbolResolve = .function(function)
if onResult(result) {
return result
}
}
}
if options.contains(.typeDecl) {
let typeDecls = scope.getTypeDecl(name: symbol.name)
for typeDecl in typeDecls {
let result: SymbolResolve = .typeDecl(typeDecl)
if onResult(result) {
return result
}
}
}
}
return nil
}
}
// MARK: - Variable reference
extension GraphImpl {
@discardableResult
func resolveVariable(_ identifier: IdentifierExprSyntax) -> Variable? {
return _findSymbol(.identifier(identifier), options: [.variable]) { resolve -> Bool in
if resolve.variable != nil {
return true
}
return false
}?.variable
}
func getVariableReferences(variable: Variable) -> [IdentifierExprSyntax] {
return cachedReferencesToVariable[variable] ?? []
}
func couldReferenceSelf(_ node: ExprSyntax) -> Bool {
if node.isCalledExpr() {
return false
}
if let identifierNode = node.as(IdentifierExprSyntax.self) {
guard let variable = resolveVariable(identifierNode) else {
return identifierNode.identifier.text == "self"
}
switch variable.raw {
case .param:
return false
case let .capture(capturedNode):
return couldReferenceSelf(ExprSyntax(capturedNode))
case let .binding(_, valueNode):
if let valueNode = valueNode {
return couldReferenceSelf(valueNode)
}
return false
}
}
return false
}
}
// MARK: - Function resolve
extension GraphImpl {
func resolveFunction(_ funcCallExpr: FunctionCallExprSyntax) -> (Function, Function.MatchResult.MappingInfo)? {
if let identifier = funcCallExpr.calledExpression.as(IdentifierExprSyntax.self) { // doSmth(...) or A(...)
return _findFunction(symbol: .identifier(identifier), funcCallExpr: funcCallExpr)
}
if let memberAccessExpr = funcCallExpr.calledExpression.as(MemberAccessExprSyntax.self) { // a.doSmth(...) or .doSmth(...)
if let base = memberAccessExpr.base {
if couldReferenceSelf(base) {
return _findFunction(symbol: .token(memberAccessExpr.name), funcCallExpr: funcCallExpr)
}
let typeDecls = getAllRelatedTypeDecls(from: resolveExprType(base))
return _findFunction(from: typeDecls, symbol: .token(memberAccessExpr.name), funcCallExpr: funcCallExpr)
} else {
// Base is omitted when the type can be inferred.
// For eg, we can say: let s: String = .init(...)
return nil
}
}
if funcCallExpr.calledExpression.is(OptionalChainingExprSyntax.self) {
// TODO
return nil
}
// Unhandled case
return nil
}
// TODO: Currently we only resolve to `func`. This could resole to `closure` as well
private func _findFunction(symbol: Symbol, funcCallExpr: FunctionCallExprSyntax)
-> (Function, Function.MatchResult.MappingInfo)? {
var result: (Function, Function.MatchResult.MappingInfo)?
_ = _findSymbol(symbol, options: [.function]) { resolve -> Bool in
switch resolve {
case .variable, .typeDecl: // This could be due to cache
return false
case .function(let function):
let mustStop = enclosingScope(for: function._syntaxNode).type.isTypeDecl
switch function.match(funcCallExpr) {
case .argumentMismatch,
.nameMismatch:
return mustStop
case .matched(let info):
guard result == nil else {
// Should not happenn
assert(false, "ambiguous")
return true // Exit
}
result = (function, info)
#if DEBUG
return mustStop // Continue to search to make sure no ambiguity
#else
return true
#endif
}
}
}
return result
}
private func _findFunction(from typeDecls: [TypeDecl], symbol: Symbol, funcCallExpr: FunctionCallExprSyntax)
-> (Function, Function.MatchResult.MappingInfo)? {
for typeDecl in typeDecls {
for function in typeDecl.scope.getFunctionWithSymbol(symbol) {
if case let .matched(info) = function.match(funcCallExpr) {
return (function, info)
}
}
}
return nil
}
}
// MARK: Type resolve
extension GraphImpl {
func resolveVariableType(_ variable: Variable) -> TypeResolve {
if let type = cachedVariableType[variable] {
return type
}
let result = _resolveType(variable.typeInfo)
cachedVariableType[variable] = result
return result
}
func resolveExprType(_ expr: ExprSyntax) -> TypeResolve {
if let optionalExpr = expr.as(OptionalChainingExprSyntax.self) {
return .optional(base: resolveExprType(optionalExpr.expression))
}
if let identifierExpr = expr.as(IdentifierExprSyntax.self) {
if let variable = resolveVariable(identifierExpr) {
return resolveVariableType(variable)
}
if identifierExpr.identifier.text == "self" {
return enclosingTypeDecl(for: expr._syntaxNode).flatMap { .type($0) } ?? .unknown
}
// May be global variable, or type like Int, String,...
return .unknown
}
// if let memberAccessExpr = node.as(MemberAccessExprSyntax.self) {
// guard let base = memberAccessExpr.base else {
// fatalError("Is it possible that `base` is nil ?")
// }
//
// }
if let functionCallExpr = expr.as(FunctionCallExprSyntax.self) {
let result = cachedFunCallExprType[functionCallExpr] ?? _resolveFunctionCallType(functionCallExpr: functionCallExpr)
cachedFunCallExprType[functionCallExpr] = result
return result
}
if let arrayExpr = expr.as(ArrayExprSyntax.self) {
return .sequence(elementType: resolveExprType(arrayExpr.elements[0].expression))
}
if expr.is(DictionaryExprSyntax.self) {
return .dict
}
if expr.is(IntegerLiteralExprSyntax.self) {
return _getAllExtensions(name: ["Int"]).first.flatMap { .type($0) } ?? .name(["Int"])
}
if expr.is(StringLiteralExprSyntax.self) {
return _getAllExtensions(name: ["String"]).first.flatMap { .type($0) } ?? .name(["String"])
}
if expr.is(FloatLiteralExprSyntax.self) {
return _getAllExtensions(name: ["Float"]).first.flatMap { .type($0) } ?? .name(["Float"])
}
if expr.is(BooleanLiteralExprSyntax.self) {
return _getAllExtensions(name: ["Bool"]).first.flatMap { .type($0) } ?? .name(["Bool"])
}
if let tupleExpr = expr.as(TupleExprSyntax.self) {
if tupleExpr.elementList.count == 1, let range = tupleExpr.elementList[0].expression.rangeInfo {
if let leftType = range.left.flatMap({ resolveExprType($0) })?.toNilIfUnknown {
return .sequence(elementType: leftType)
} else if let rightType = range.right.flatMap({ resolveExprType($0) })?.toNilIfUnknown {
return .sequence(elementType: rightType)
} else {
return .unknown
}
}
return .tuple(tupleExpr.elementList.map { resolveExprType($0.expression) })
}
if let subscriptExpr = expr.as(SubscriptExprSyntax.self) {
let sequenceElementType = resolveExprType(subscriptExpr.calledExpression).sequenceElementType
if sequenceElementType != .unknown {
if subscriptExpr.argumentList.count == 1, let argument = subscriptExpr.argumentList.first?.expression {
if argument.rangeInfo != nil {
return .sequence(elementType: sequenceElementType)
}
if resolveExprType(argument).isInt {
return sequenceElementType
}
}
}
return .unknown
}
return .unknown
}
private func _resolveType(_ typeInfo: TypeInfo) -> TypeResolve {
switch typeInfo {
case .exact(let type):
return resolveType(type)
case .inferedFromExpr(let expr):
return resolveExprType(expr)
case .inferedFromClosure(let closureExpr, let paramIndex, let paramCount):
// let x: (X, Y) -> Z = { a,b in ...}
if let closureVariable = enclosingScope(for: Syntax(closureExpr)).getVariableBindingTo(expr: ExprSyntax(closureExpr)) {
switch closureVariable.typeInfo {
case .exact(let type):
guard let argumentsType = (type.as(FunctionTypeSyntax.self))?.arguments else {
// Eg: let onFetchJobs: JobCardsFetcher.OnFetchJobs = { [weak self] jobs in ... }
return .unknown
}
assert(argumentsType.count == paramCount)
return resolveType(argumentsType[paramIndex].type)
case .inferedFromClosure,
.inferedFromExpr,
.inferedFromSequence,
.inferedFromTuple:
assert(false, "Seems wrong")
return .unknown
}
}
// TODO: there's also this case
// var b: ((X) -> Y)!
// b = { x in ... }
return .unknown
case .inferedFromSequence(let sequenceExpr):
let sequenceType = resolveExprType(sequenceExpr)
return sequenceType.sequenceElementType
case .inferedFromTuple(let tupleTypeInfo, let index):
if case let .tuple(types) = _resolveType(tupleTypeInfo) {
return types[index]
}
return .unknown
}
}
func resolveType(_ type: TypeSyntax) -> TypeResolve {
if type.isOptional {
return .optional(base: resolveType(type.wrappedType))
}
if let arrayType = type.as(ArrayTypeSyntax.self) {
return .sequence(elementType: resolveType(arrayType.elementType))
}
if type.is(DictionaryTypeSyntax.self) {
return .dict
}
if let tupleType = type.as(TupleTypeSyntax.self) {
return .tuple(tupleType.elements.map { resolveType($0.type) })
}
if let tokens = type.tokens, let typeDecl = resolveTypeDecl(tokens: tokens) {
return .type(typeDecl)
} else if let name = type.name {
return .name(name)
} else {
return .unknown
}
}
private func _resolveFunctionCallType(functionCallExpr: FunctionCallExprSyntax, ignoreOptional: Bool = false) -> TypeResolve {
if let (function, _) = resolveFunction(functionCallExpr) {
if let type = function.signature.output?.returnType {
return resolveType(type)
} else {
return .unknown // Void
}
}
var calledExpr = functionCallExpr.calledExpression
if let optionalExpr = calledExpr.as(OptionalChainingExprSyntax.self) { // Must be optional closure
if !ignoreOptional {
return .optional(base: _resolveFunctionCallType(functionCallExpr: functionCallExpr, ignoreOptional: true))
} else {
calledExpr = optionalExpr.expression
}
}
// [X]()
if let arrayExpr = calledExpr.as(ArrayExprSyntax.self) {
if let typeIdentifier = arrayExpr.elements[0].expression.as(IdentifierExprSyntax.self) {
if let typeDecl = resolveTypeDecl(tokens: [typeIdentifier.identifier]) {
return .sequence(elementType: .type(typeDecl))
} else {
return .sequence(elementType: .name([typeIdentifier.identifier.text]))
}
} else {
return .sequence(elementType: resolveExprType(arrayExpr.elements[0].expression))
}
}
// [X: Y]()
if calledExpr.is(DictionaryExprSyntax.self) {
return .dict
}
// doSmth() or A()
if let identifierExpr = calledExpr.as(IdentifierExprSyntax.self) {
let identifierResolve = _findSymbol(.identifier(identifierExpr)) { resolve in
switch resolve {
case .function(let function):
return function.match(functionCallExpr).isMatched
case .typeDecl:
return true
case .variable:
return false
}
}
if let identifierResolve = identifierResolve {
switch identifierResolve {
// doSmth()
case .function(let function):
let returnType = function.signature.output?.returnType
return returnType.flatMap { resolveType($0) } ?? .unknown
// A()
case .typeDecl(let typeDecl):
return .type(typeDecl)
case .variable:
break
}
}
}
// x.y()
if let memberAccessExpr = calledExpr.as(MemberAccessExprSyntax.self) {
if let base = memberAccessExpr.base {
let baseType = resolveExprType(base)
if _isCollection(baseType) {
let funcName = memberAccessExpr.name.text
if ["map", "flatMap", "compactMap", "enumerated"].contains(funcName) {
return .sequence(elementType: .unknown)
}
if ["filter", "sorted"].contains(funcName) {
return baseType
}
}
} else {
// Base is omitted when the type can be inferred.
// For eg, we can say: let s: String = .init(...)
return .unknown
}
}
return .unknown
}
}
// MARK: - TypeDecl resolve
extension GraphImpl {
func resolveTypeDecl(tokens: [TokenSyntax]) -> TypeDecl? {
guard tokens.count > 0 else {
return nil
}
return _resolveTypeDecl(token: tokens[0], onResult: { typeDecl in
var currentScope = typeDecl.scope
for token in tokens[1...] {
if let scope = currentScope.getTypeDecl(name: token.text).first?.scope {
currentScope = scope
} else {
return false
}
}
return true
})
}
private func _resolveTypeDecl(token: TokenSyntax, onResult: (TypeDecl) -> Bool) -> TypeDecl? {
let result = _findSymbol(.token(token), options: [.typeDecl]) { resolve in
if case let .typeDecl(typeDecl) = resolve {
return onResult(typeDecl)
}
return false
}
if let result = result, case let .typeDecl(scope) = result {
return scope
}
return nil
}
func getAllRelatedTypeDecls(from: TypeDecl) -> [TypeDecl] {
var result: [TypeDecl] = _getAllExtensions(typeDecl: from)
if !from.isExtension {
result = [from] + result
} else {
if let originalDecl = resolveTypeDecl(tokens: from.tokens) {
result = [originalDecl] + result
}
}
return result + result.flatMap { typeDecl -> [TypeDecl] in
guard let inheritanceTypes = typeDecl.inheritanceTypes else {
return []
}
return inheritanceTypes
.compactMap { resolveTypeDecl(tokens: $0.typeName.tokens ?? []) }
.flatMap { getAllRelatedTypeDecls(from: $0) }
}
}
func getAllRelatedTypeDecls(from: TypeResolve) -> [TypeDecl] {
switch from.wrappedType {
case .type(let typeDecl):
return getAllRelatedTypeDecls(from: typeDecl)
case .sequence:
return _getAllExtensions(name: ["Array"]) + _getAllExtensions(name: ["Collection"])
case .dict:
return _getAllExtensions(name: ["Dictionary"]) + _getAllExtensions(name: ["Collection"])
case .name, .tuple, .unknown:
return []
case .optional:
// Can't happen
return []
}
}
private func _getAllExtensions(typeDecl: TypeDecl) -> [TypeDecl] {
guard let name = _getTypeDeclFullPath(typeDecl)?.map({ $0.text }) else { return [] }
return _getAllExtensions(name: name)
}
private func _getAllExtensions(name: [String]) -> [TypeDecl] {
return sourceFileScope.childScopes
.compactMap { $0.typeDecl }
.filter { $0.isExtension && $0.name == name }
}
// For eg, type path for C in be example below is A.B.C
// class A {
// struct B {
// enum C {
// Returns nil if the type is nested inside non-type entity like function
private func _getTypeDeclFullPath(_ typeDecl: TypeDecl) -> [TokenSyntax]? {
let tokens = typeDecl.tokens
if typeDecl.scope.parent?.type == .sourceFileNode {
return tokens
}
if let parentTypeDecl = typeDecl.scope.parent?.typeDecl, let parentTokens = _getTypeDeclFullPath(parentTypeDecl) {
return parentTokens + tokens
}
return nil
}
}
// MARK: - Classification
extension GraphImpl {
func isClosureEscape(_ closure: ClosureExprSyntax, nonEscapeRules: [NonEscapeRule]) -> Bool {
func _isClosureEscape(_ expr: ExprSyntax, isFuncParam: Bool) -> Bool {
// check cache
if let closureNode = expr.as(ClosureExprSyntax.self), let cachedResult = cachedClosureEscapeCheck[closureNode] {
return cachedResult
}
// If it's a param, and it's inside an escaping closure, then it's also escaping
// For eg:
// func doSmth(block: @escaping () -> Void) {
// someObject.callBlock {
// block()
// }
// }
// Here block is a param and it's used inside an escaping closure
if isFuncParam {
if let parentClosure = expr.getEnclosingClosureNode() {
if isClosureEscape(parentClosure, nonEscapeRules: nonEscapeRules) {
return true
}
}
}
// Function call expression: {...}()
if expr.isCalledExpr() {
return false // Not escape
}
// let x = closure
// `x` may be used anywhere
if let variable = enclosingScope(for: expr._syntaxNode).getVariableBindingTo(expr: expr) {
let references = getVariableReferences(variable: variable)
for reference in references {
if _isClosureEscape(ExprSyntax(reference), isFuncParam: isFuncParam) == true {
return true // Escape
}
}
}
// Used as argument in function call: doSmth(a, b, c: {...}) or doSmth(a, b) {...}
if let (functionCall, argument) = expr.getEnclosingFunctionCallExpression() {
if let (function, matchedInfo) = resolveFunction(functionCall) {
let param: FunctionParameterSyntax!
if let argument = argument {
param = matchedInfo.argumentToParamMapping[argument]
} else {
param = matchedInfo.trailingClosureArgumentToParam
}
guard param != nil else { fatalError("Something wrong") }
// If the param is marked as `@escaping`, we still need to check with the non-escaping rules
// If the param is not marked as `@escaping`, and it's optional, we don't know anything about it
// If the param is not marked as `@escaping`, and it's not optional, we know it's non-escaping for sure
if !param.isEscaping && param.type?.isOptional != true {
return false
}
// get the `.function` scope where we define this func
let scope = self.scope(for: function._syntaxNode)
assert(scope.type.isFunction)
guard let variableForParam = scope.variables.first(where: { $0.raw.token == (param.secondName ?? param.firstName) }) else {
fatalError("Can't find the Variable that wrap the param")
}
let references = getVariableReferences(variable: variableForParam)
for referennce in references {
if _isClosureEscape(ExprSyntax(referennce), isFuncParam: true) == true {
return true
}
}
return false
} else {
// Can't resolve the function
// Use custom rules
for rule in nonEscapeRules {
if rule.isNonEscape(closureNode: expr, graph: self) {
return false
}
}
// Still can't figure out using custom rules, assume closure is escaping
return true
}
}
return false // It's unlikely the closure is escaping
}
let result = _isClosureEscape(ExprSyntax(closure), isFuncParam: false)
cachedClosureEscapeCheck[closure] = result
return result
}
func isCollection(_ node: ExprSyntax) -> Bool {
let type = resolveExprType(node)
return _isCollection(type)
}
private func _isCollection(_ type: TypeResolve) -> Bool {
let isCollectionTypeName: ([String]) -> Bool = { (name: [String]) in
return name == ["Array"] || name == ["Dictionary"] || name == ["Set"]
}
switch type {
case .tuple,
.unknown:
return false
case .sequence,
.dict:
return true
case .optional(let base):
return _isCollection(base)
case .name(let name):
return isCollectionTypeName(name)
case .type(let typeDecl):
let allTypeDecls = getAllRelatedTypeDecls(from: typeDecl)
for typeDecl in allTypeDecls {
if isCollectionTypeName(typeDecl.name) {
return true
}
for inherritedName in (typeDecl.inheritanceTypes?.map { $0.typeName.name ?? [""] } ?? []) {
// If it extends any of the collection types or implements Collection protocol
if isCollectionTypeName(inherritedName) || inherritedName == ["Collection"] {
return true
}
}
}
return false
}
}
}
private extension Scope {
func getVariableBindingTo(expr: ExprSyntax) -> Variable? {
return variables.first(where: { variable -> Bool in
switch variable.raw {
case .param, .capture: return false
case let .binding(_, valueNode):
return valueNode != nil ? valueNode! == expr : false
}
})
}
}
private extension TypeResolve {
var toNilIfUnknown: TypeResolve? {
switch self {
case .unknown: return nil
default: return self
}
}
}
<file_sep>/Sources/SwiftLeakCheck/SourceFileScope.swift
//
// SourceFileScope.swift
// SwiftLeakCheck
//
// Created by <NAME> on 04/01/2020.
//
import SwiftSyntax
public class SourceFileScope: Scope {
let node: SourceFileSyntax
init(node: SourceFileSyntax, parent: Scope?) {
self.node = node
super.init(scopeNode: .sourceFileNode(node), parent: parent)
}
}
<file_sep>/Sources/SwiftLeakCheck/NonEscapeRules/ExprSyntaxPredicate.swift
//
// ExprSyntaxPredicate.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 26/12/2019.
//
import SwiftSyntax
open class ExprSyntaxPredicate {
public let match: (ExprSyntax?) -> Bool
public init(_ match: @escaping (ExprSyntax?) -> Bool) {
self.match = match
}
public static let any: ExprSyntaxPredicate = .init { _ in true }
}
// MARK: - Identifier predicate
extension ExprSyntaxPredicate {
public static func name(_ text: String) -> ExprSyntaxPredicate {
return .name({ $0 == text })
}
public static func name(_ namePredicate: @escaping (String) -> Bool) -> ExprSyntaxPredicate {
return .init({ expr -> Bool in
guard let identifierExpr = expr?.as(IdentifierExprSyntax.self) else {
return false
}
return namePredicate(identifierExpr.identifier.text)
})
}
}
// MARK: - Function call predicate
extension ExprSyntaxPredicate {
public static func funcCall(name: String,
base basePredicate: ExprSyntaxPredicate) -> ExprSyntaxPredicate {
return .funcCall(namePredicate: { $0 == name }, base: basePredicate)
}
public static func funcCall(namePredicate: @escaping (String) -> Bool,
base basePredicate: ExprSyntaxPredicate) -> ExprSyntaxPredicate {
return .funcCall(predicate: { funcCallExpr -> Bool in
guard let symbol = funcCallExpr.symbol else {
return false
}
return namePredicate(symbol.text)
&& basePredicate.match(funcCallExpr.base)
})
}
public static func funcCall(signature: FunctionSignature,
base basePredicate: ExprSyntaxPredicate) -> ExprSyntaxPredicate {
return .funcCall(predicate: { funcCallExpr -> Bool in
return signature.match(funcCallExpr).isMatched
&& basePredicate.match(funcCallExpr.base)
})
}
public static func funcCall(predicate: @escaping (FunctionCallExprSyntax) -> Bool) -> ExprSyntaxPredicate {
return .init({ expr -> Bool in
guard let funcCallExpr = expr?.as(FunctionCallExprSyntax.self) else {
return false
}
return predicate(funcCallExpr)
})
}
}
// MARK: - MemberAccess predicate
extension ExprSyntaxPredicate {
public static func memberAccess(_ memberPredicate: @escaping (String) -> Bool,
base basePredicate: ExprSyntaxPredicate) -> ExprSyntaxPredicate {
return .init({ expr -> Bool in
guard let memberAccessExpr = expr?.as(MemberAccessExprSyntax.self) else {
return false
}
return memberPredicate(memberAccessExpr.name.text)
&& basePredicate.match(memberAccessExpr.base)
})
}
public static func memberAccess(_ member: String, base basePredicate: ExprSyntaxPredicate) -> ExprSyntaxPredicate {
return .memberAccess({ $0 == member }, base: basePredicate)
}
}
public extension ExprSyntax {
func match(_ predicate: ExprSyntaxPredicate) -> Bool {
return predicate.match(self)
}
}
// Convenient
public extension FunctionCallExprSyntax {
func match(_ predicate: ExprSyntaxPredicate) -> Bool {
return predicate.match(ExprSyntax(self))
}
}
<file_sep>/Sources/SwiftLeakCheck/NonEscapeRules/UIViewControllerAnimationRule.swift
//
// UIViewControllerAnimationRule.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 30/12/2019.
//
import SwiftSyntax
/// Eg, someViewController.present(vc, animated: true, completion: { ... })
/// or someViewController.dismiss(animated: true) { ... }
open class UIViewControllerAnimationRule: BaseNonEscapeRule {
private let signatures: [FunctionSignature] = [
FunctionSignature(name: "present", params: [
FunctionParam(name: nil), // "viewControllerToPresent"
FunctionParam(name: "animated"),
FunctionParam(name: "completion", isClosure: true, canOmit: true)
]),
FunctionSignature(name: "dismiss", params: [
FunctionParam(name: "animated"),
FunctionParam(name: "completion", isClosure: true, canOmit: true)
]),
FunctionSignature(name: "transition", params: [
FunctionParam(name: "from"),
FunctionParam(name: "to"),
FunctionParam(name: "duration"),
FunctionParam(name: "options", canOmit: true),
FunctionParam(name: "animations", isClosure: true),
FunctionParam(name: "completion", isClosure: true, canOmit: true)
])
]
open override func isNonEscape(arg: FunctionCallArgumentSyntax?,
funcCallExpr: FunctionCallExprSyntax,
graph: Graph) -> Bool {
// Make sure the func is called from UIViewController
guard isCalledFromUIViewController(funcCallExpr: funcCallExpr, graph: graph) else {
return false
}
// Now we can check each signature and ignore the base that is already checked
for signature in signatures {
if funcCallExpr.match(.funcCall(signature: signature, base: .any)) {
return true
}
}
return false
}
open func isUIViewControllerType(name: [String]) -> Bool {
let typeName = name.last ?? ""
let candidates = [
"UIViewController",
"UITableViewController",
"UICollectionViewController",
"UIAlertController",
"UIActivityViewController",
"UINavigationController",
"UITabBarController",
"UIMenuController",
"UISearchController"
]
return candidates.contains(typeName) || typeName.hasSuffix("ViewController")
}
private func isUIViewControllerType(typeDecl: TypeDecl) -> Bool {
if isUIViewControllerType(name: typeDecl.name) {
return true
}
let inheritantTypes = (typeDecl.inheritanceTypes ?? []).map { $0.typeName }
for inheritantType in inheritantTypes {
if isUIViewControllerType(name: inheritantType.name ?? []) {
return true
}
}
return false
}
private func isCalledFromUIViewController(funcCallExpr: FunctionCallExprSyntax, graph: Graph) -> Bool {
guard let base = funcCallExpr.base else {
// No base, eg: doSmth()
// class SomeClass {
// func main() {
// doSmth()
// }
// }
// In this case, we find the TypeDecl where this func is called from (Eg, SomeClass)
if let typeDecl = graph.enclosingTypeDecl(for: funcCallExpr._syntaxNode) {
return isUIViewControllerType(typeDecl: typeDecl)
} else {
return false
}
}
// Eg: base.doSmth()
// We check if base is UIViewController
let typeResolve = graph.resolveExprType(base)
switch typeResolve.wrappedType {
case .type(let typeDecl):
let allTypeDecls = graph.getAllRelatedTypeDecls(from: typeDecl)
for typeDecl in allTypeDecls {
if isUIViewControllerType(typeDecl: typeDecl) {
return true
}
}
return false
case .name(let name):
return isUIViewControllerType(name: name)
case .dict,
.sequence,
.tuple,
.optional, // Can't happen
.unknown:
return false
}
}
}
<file_sep>/Tests/SwiftLeakCheckTests/StackTests.swift
//
// StackTests.swift
// SwiftLeakCheckTests
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 27/10/2019.
//
import XCTest
@testable import SwiftLeakCheck
final class StackTests: XCTestCase {
func testEnumerationOrder() {
var stack = Stack<Int>()
stack.push(5)
stack.push(4)
stack.push(3)
stack.push(2)
stack.push(1)
let a = [1, 2, 3, 4, 5]
// Map
XCTAssertEqual(stack.map { $0 }, a)
// Loop
var arr1 = [Int]()
stack.forEach { arr1.append($0) }
XCTAssertEqual(arr1, a)
var arr2 = [Int]()
for num in stack {
arr2.append(num)
}
XCTAssertEqual(arr2, a)
}
func testPushPopPeek() {
var stack = Stack<Int>()
stack.push(5)
XCTAssertEqual(stack.peek(), 5)
stack.push(4)
XCTAssertEqual(stack.pop(), 4)
XCTAssertEqual(stack.peek(), 5)
stack.push(3)
stack.push(2)
XCTAssertEqual(stack.pop(), 2)
stack.push(1)
XCTAssertEqual(stack.map { $0 }, [1, 3, 5])
}
func testPopEmpty() {
var stack = Stack<Int>()
stack.push(1)
XCTAssertEqual(stack.pop(), 1)
XCTAssertEqual(stack.pop(), nil)
}
func testReset() {
var stack = Stack<Int>()
stack.push(5)
stack.push(4)
stack.reset()
XCTAssertEqual(stack.map { $0 }, [])
}
}
<file_sep>/Sources/SwiftLeakCheck/TypeDecl.swift
//
// TypeDecl.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 04/01/2020.
//
import SwiftSyntax
// Class, struct, enum or extension
public struct TypeDecl: Equatable {
/// The name of the class/struct/enum/extension.
/// For class/struct/enum, it's 1 element
/// For extension, it could be multiple. Eg, extension X.Y.Z {...}
public let tokens: [TokenSyntax]
public let inheritanceTypes: [InheritedTypeSyntax]?
// Must be class/struct/enum/extension
public let scope: Scope
public var name: [String] {
return tokens.map { $0.text }
}
public var isExtension: Bool {
return scope.type == .extensionNode
}
}
<file_sep>/Sources/SwiftLeakCheck/NonEscapeRules/CollectionRules.swift
//
// CollectionRules.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 29/10/2019.
//
import SwiftSyntax
/// Swift Collection functions like forEach, map, flatMap, sorted,....
public enum CollectionRules {
public private(set) static var rules: [NonEscapeRule] = {
return [
CollectionForEachRule(),
CollectionCompactMapRule(),
CollectionMapRule(),
CollectionFilterRule(),
CollectionSortRule(),
CollectionFlatMapRule(),
CollectionFirstWhereRule(),
CollectionContainsRule(),
CollectionMaxMinRule()
]
}()
}
open class CollectionForEachRule: BaseNonEscapeRule {
public let mustBeCollection: Bool
private let signature = FunctionSignature(name: "forEach", params: [
FunctionParam(name: nil, isClosure: true)
])
public init(mustBeCollection: Bool = false) {
self.mustBeCollection = mustBeCollection
}
open override func isNonEscape(arg: FunctionCallArgumentSyntax?,
funcCallExpr: FunctionCallExprSyntax,
graph: Graph) -> Bool {
return funcCallExpr.match(.funcCall(signature: signature, base: .init { expr in
return !self.mustBeCollection || isCollection(expr, graph: graph)
}))
}
}
open class CollectionCompactMapRule: BaseNonEscapeRule {
private let signature = FunctionSignature(name: "compactMap", params: [
FunctionParam(name: nil, isClosure: true)
])
open override func isNonEscape(arg: FunctionCallArgumentSyntax?,
funcCallExpr: FunctionCallExprSyntax,
graph: Graph) -> Bool {
return funcCallExpr.match(.funcCall(signature: signature, base: .init { expr in
return isCollection(expr, graph: graph)
}))
}
}
open class CollectionMapRule: BaseNonEscapeRule {
private let signature = FunctionSignature(name: "map", params: [
FunctionParam(name: nil, isClosure: true)
])
open override func isNonEscape(arg: FunctionCallArgumentSyntax?,
funcCallExpr: FunctionCallExprSyntax,
graph: Graph) -> Bool {
return funcCallExpr.match(.funcCall(signature: signature, base: .init { expr in
return isCollection(expr, graph: graph) || isOptional(expr, graph: graph)
}))
}
}
open class CollectionFlatMapRule: BaseNonEscapeRule {
private let signature = FunctionSignature(name: "flatMap", params: [
FunctionParam(name: nil, isClosure: true)
])
open override func isNonEscape(arg: FunctionCallArgumentSyntax?,
funcCallExpr: FunctionCallExprSyntax,
graph: Graph) -> Bool {
return funcCallExpr.match(.funcCall(signature: signature, base: .init { expr in
return isCollection(expr, graph: graph) || isOptional(expr, graph: graph)
}))
}
}
open class CollectionFilterRule: BaseNonEscapeRule {
private let signature = FunctionSignature(name: "filter", params: [
FunctionParam(name: nil, isClosure: true)
])
open override func isNonEscape(arg: FunctionCallArgumentSyntax?,
funcCallExpr: FunctionCallExprSyntax,
graph: Graph) -> Bool {
return funcCallExpr.match(.funcCall(signature: signature, base: .init { expr in
return isCollection(expr, graph: graph)
}))
}
}
open class CollectionSortRule: BaseNonEscapeRule {
private let sortSignature = FunctionSignature(name: "sort", params: [
FunctionParam(name: "by", isClosure: true)
])
private let sortedSignature = FunctionSignature(name: "sorted", params: [
FunctionParam(name: "by", isClosure: true)
])
open override func isNonEscape(arg: FunctionCallArgumentSyntax?,
funcCallExpr: FunctionCallExprSyntax,
graph: Graph) -> Bool {
return funcCallExpr.match(.funcCall(signature: sortSignature, base: .init { return isCollection($0, graph: graph) }))
|| funcCallExpr.match(.funcCall(signature: sortedSignature, base: .init { return isCollection($0, graph: graph) }))
}
}
open class CollectionFirstWhereRule: BaseNonEscapeRule {
private let firstWhereSignature = FunctionSignature(name: "first", params: [
FunctionParam(name: "where", isClosure: true)
])
private let firstIndexWhereSignature = FunctionSignature(name: "firstIndex", params: [
FunctionParam(name: "where", isClosure: true)
])
open override func isNonEscape(arg: FunctionCallArgumentSyntax?,
funcCallExpr: FunctionCallExprSyntax,
graph: Graph) -> Bool {
let base = ExprSyntaxPredicate { expr in
return isCollection(expr, graph: graph)
}
return funcCallExpr.match(.funcCall(signature: firstWhereSignature, base: base))
|| funcCallExpr.match(.funcCall(signature: firstIndexWhereSignature, base: base))
}
}
open class CollectionContainsRule: BaseNonEscapeRule {
let signature = FunctionSignature(name: "contains", params: [
FunctionParam(name: "where", isClosure: true)
])
open override func isNonEscape(arg: FunctionCallArgumentSyntax?,
funcCallExpr: FunctionCallExprSyntax,
graph: Graph) -> Bool {
return funcCallExpr.match(.funcCall(signature: signature, base: .init { expr in
return isCollection(expr, graph: graph) }))
}
}
open class CollectionMaxMinRule: BaseNonEscapeRule {
private let maxSignature = FunctionSignature(name: "max", params: [
FunctionParam(name: "by", isClosure: true)
])
private let minSignature = FunctionSignature(name: "min", params: [
FunctionParam(name: "by", isClosure: true)
])
open override func isNonEscape(arg: FunctionCallArgumentSyntax?,
funcCallExpr: FunctionCallExprSyntax,
graph: Graph) -> Bool {
return funcCallExpr.match(.funcCall(signature: maxSignature, base: .init { return isCollection($0, graph: graph) }))
|| funcCallExpr.match(.funcCall(signature: minSignature, base: .init { return isCollection($0, graph: graph) }))
}
}
private func isCollection(_ expr: ExprSyntax?, graph: Graph) -> Bool {
guard let expr = expr else {
return false
}
return graph.isCollection(expr)
}
private func isOptional(_ expr: ExprSyntax?, graph: Graph) -> Bool {
guard let expr = expr else {
return false
}
return graph.resolveExprType(expr).isOptional
}
<file_sep>/Tests/SwiftLeakCheckTests/LeakDetectorTests.swift
//
// LeakDetectorTests.swift
// SwiftLeakCheckTests
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 27/10/2019.
//
import XCTest
import SwiftLeakCheck
final class LeakDetectorTests: XCTestCase {
func testLeak1() {
verify(fileName: "Leak1")
}
func testLeak2() {
verify(fileName: "Leak2")
}
func testNestedClosure() {
verify(fileName: "NestedClosure")
}
func testNonEscapingClosure() {
verify(fileName: "NonEscapingClosure")
}
func testUIViewAnimation() {
verify(fileName: "UIViewAnimation")
}
func testUIViewControllerAnimation() {
verify(fileName: "UIViewControllerAnimation")
}
func testEscapingAttribute() {
verify(fileName: "EscapingAttribute")
}
func testIfElse() {
verify(fileName: "IfElse")
}
func testFuncResolve() {
verify(fileName: "FuncResolve")
}
func testTypeInfer() {
verify(fileName: "TypeInfer")
}
func testTypeResolve() {
verify(fileName: "TypeResolve")
}
func testDispatchQueue() {
verify(fileName: "DispatchQueue")
}
func testExtensions() {
verify(fileName: "Extensions")
}
private func verify(fileName: String, extension: String? = nil) {
do {
guard let url = bundle.url(forResource: fileName, withExtension: `extension`) else {
XCTFail("File \(fileName + (`extension`.flatMap { ".\($0)" } ?? "")) doesn't exist")
return
}
let content = try String(contentsOf: url)
verify(content: content)
} catch {
XCTFail(error.localizedDescription)
}
}
private func verify(content: String) {
let lines = content.components(separatedBy: "\n")
let expectedLeakAtLines = lines.enumerated().compactMap { (lineNumber, line) -> Int? in
if line.trimmingCharacters(in: .whitespacesAndNewlines).hasSuffix("// Leak") {
return lineNumber + 1
}
return nil
}
do {
let leakDetector = GraphLeakDetector()
leakDetector.nonEscapeRules = [
UIViewAnimationRule(),
UIViewControllerAnimationRule(),
DispatchQueueRule()
] + CollectionRules.rules
let leaks = try leakDetector.detect(content: content)
let leakAtLines = leaks.map { $0.line }
let leakAtLinesUnique = NSOrderedSet(array: leakAtLines).array as! [Int]
XCTAssertEqual(leakAtLinesUnique, expectedLeakAtLines)
} catch {
XCTFail(error.localizedDescription)
}
}
private lazy var bundle: Bundle = {
return Bundle(for: type(of: self))
}()
}
<file_sep>/Sources/SwiftLeakCheck/Leak.swift
//
// LeakDetection.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 27/10/2019.
//
import Foundation
import SwiftSyntax
open class Leak: CustomStringConvertible, Encodable {
public let node: IdentifierExprSyntax
public let capturedNode: ExprSyntax?
public let sourceLocationConverter: SourceLocationConverter
public private(set) lazy var line: Int = {
return sourceLocationConverter.location(for: node.positionAfterSkippingLeadingTrivia).line ?? -1
}()
public private(set) lazy var column: Int = {
return sourceLocationConverter.location(for: node.positionAfterSkippingLeadingTrivia).column ?? -1
}()
public init(node: IdentifierExprSyntax,
capturedNode: ExprSyntax?,
sourceLocationConverter: SourceLocationConverter) {
self.node = node
self.capturedNode = capturedNode
self.sourceLocationConverter = sourceLocationConverter
}
private enum CodingKeys: CodingKey {
case line
case column
case reason
}
open func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(line, forKey: .line)
try container.encode(column, forKey: .column)
let reason: String = {
return "`self` is strongly captured here, from a potentially escaped closure."
}()
try container.encode(reason, forKey: .reason)
}
open var description: String {
return """
`self` is strongly captured at (line: \(line), column: \(column))"),
from a potentially escaped closure.
"""
}
}
<file_sep>/Sources/SwiftLeakCheck/SwiftSyntax+Extensions.swift
//
// SwiftSyntax+Extensions.swift
// LeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 27/10/2019.
//
import SwiftSyntax
public extension SyntaxProtocol {
func isBefore(_ node: SyntaxProtocol) -> Bool {
return positionAfterSkippingLeadingTrivia.utf8Offset < node.positionAfterSkippingLeadingTrivia.utf8Offset
}
func getEnclosingNode<T: SyntaxProtocol>(_ type: T.Type) -> T? {
var parent = self.parent
while parent != nil && parent!.is(type) == false {
parent = parent?.parent
if parent == nil { return nil }
}
return parent?.as(type)
}
func getEnclosingClosureNode() -> ClosureExprSyntax? {
return getEnclosingNode(ClosureExprSyntax.self)
}
}
extension Syntax {
func isDescendent(of node: Syntax) -> Bool {
return hasAncestor { $0 == node }
}
// TODO (Le): should we consider self as ancestor of self like this ?
func hasAncestor(_ predicate: (Syntax) -> Bool) -> Bool {
if predicate(self) { return true }
var parent = self.parent
while parent != nil {
if predicate(parent!) {
return true
}
parent = parent?.parent
}
return false
}
}
public extension ExprSyntax {
/// Returns the enclosing function call to which the current expr is passed as argument. We also return the corresponding
/// argument of the current expr, or nil if current expr is trailing closure
func getEnclosingFunctionCallExpression() -> (function: FunctionCallExprSyntax, argument: FunctionCallArgumentSyntax?)? {
var function: FunctionCallExprSyntax?
var argument: FunctionCallArgumentSyntax?
if let parent = parent?.as(FunctionCallArgumentSyntax.self) { // Normal function argument
assert(parent.parent?.is(FunctionCallArgumentListSyntax.self) == true)
function = parent.parent?.parent?.as(FunctionCallExprSyntax.self)
argument = parent
} else if let parent = parent?.as(FunctionCallExprSyntax.self),
self.is(ClosureExprSyntax.self),
parent.trailingClosure == self.as(ClosureExprSyntax.self)
{ // Trailing closure
function = parent
}
guard function != nil else {
// Not function call
return nil
}
return (function: function!, argument: argument)
}
func isCalledExpr() -> Bool {
if let parentNode = parent?.as(FunctionCallExprSyntax.self) {
if parentNode.calledExpression == self {
return true
}
}
return false
}
var rangeInfo: (left: ExprSyntax?, op: TokenSyntax, right: ExprSyntax?)? {
if let expr = self.as(SequenceExprSyntax.self) {
let elements = expr.elements
guard elements.count == 3, let op = elements[1].rangeOperator else {
return nil
}
return (left: elements[elements.startIndex], op: op, right: elements[elements.index(before: elements.endIndex)])
}
if let expr = self.as(PostfixUnaryExprSyntax.self) {
if expr.operatorToken.isRangeOperator {
return (left: nil, op: expr.operatorToken, right: expr.expression)
} else {
return nil
}
}
if let expr = self.as(PrefixOperatorExprSyntax.self) {
assert(expr.operatorToken != nil)
if expr.operatorToken!.isRangeOperator {
return (left: expr.postfixExpression, op: expr.operatorToken!, right: nil)
} else {
return nil
}
}
return nil
}
private var rangeOperator: TokenSyntax? {
guard let op = self.as(BinaryOperatorExprSyntax.self) else {
return nil
}
return op.operatorToken.isRangeOperator ? op.operatorToken : nil
}
}
public extension TokenSyntax {
var isRangeOperator: Bool {
return text == "..." || text == "..<"
}
}
public extension TypeSyntax {
var isOptional: Bool {
return self.is(OptionalTypeSyntax.self) || self.is(ImplicitlyUnwrappedOptionalTypeSyntax.self)
}
var wrappedType: TypeSyntax {
if let optionalType = self.as(OptionalTypeSyntax.self) {
return optionalType.wrappedType
}
if let implicitOptionalType = self.as(ImplicitlyUnwrappedOptionalTypeSyntax.self) {
return implicitOptionalType.wrappedType
}
return self
}
var tokens: [TokenSyntax]? {
if self == wrappedType {
if let type = self.as(MemberTypeIdentifierSyntax.self) {
if let base = type.baseType.tokens {
return base + [type.name]
}
return nil
}
if let type = self.as(SimpleTypeIdentifierSyntax.self) {
return [type.name]
}
return nil
}
return wrappedType.tokens
}
var name: [String]? {
return tokens?.map { $0.text }
}
var isClosure: Bool {
return wrappedType.is(FunctionTypeSyntax.self)
|| (wrappedType.as(AttributedTypeSyntax.self))?.baseType.isClosure == true
|| (wrappedType.as(TupleTypeSyntax.self)).flatMap { $0.elements.count == 1 && $0.elements[$0.elements.startIndex].type.isClosure } == true
}
}
/// `gurad let a = b, ... `: `let a = b` is a OptionalBindingConditionSyntax
public extension OptionalBindingConditionSyntax {
func isGuardCondition() -> Bool {
return parent?.is(ConditionElementSyntax.self) == true
&& parent?.parent?.is(ConditionElementListSyntax.self) == true
&& parent?.parent?.parent?.is(GuardStmtSyntax.self) == true
}
}
public extension FunctionCallExprSyntax {
var base: ExprSyntax? {
return calledExpression.baseAndSymbol?.base
}
var symbol: TokenSyntax? {
return calledExpression.baseAndSymbol?.symbol
}
}
// Only used for the FunctionCallExprSyntax extension above
private extension ExprSyntax {
var baseAndSymbol: (base: ExprSyntax?, symbol: TokenSyntax)? {
// base.symbol()
if let memberAccessExpr = self.as(MemberAccessExprSyntax.self) {
return (base: memberAccessExpr.base, symbol: memberAccessExpr.name)
}
// symbol()
if let identifier = self.as(IdentifierExprSyntax.self) {
return (base: nil, symbol: identifier.identifier)
}
// expr?.()
if let optionalChainingExpr = self.as(OptionalChainingExprSyntax.self) {
return optionalChainingExpr.expression.baseAndSymbol
}
// expr<T>()
if let specializeExpr = self.as(SpecializeExprSyntax.self) {
return specializeExpr.expression.baseAndSymbol
}
assert(false, "Unhandled case")
return nil
}
}
public extension FunctionParameterSyntax {
var isEscaping: Bool {
guard let attributedType = type?.as(AttributedTypeSyntax.self) else {
return false
}
return attributedType.attributes?.contains(where: { $0.as(AttributeSyntax.self)?.attributeName.text == "escaping" }) == true
}
}
/// Convenient
extension ArrayElementListSyntax {
subscript(_ i: Int) -> ArrayElementSyntax {
let index = self.index(startIndex, offsetBy: i)
return self[index]
}
}
extension FunctionCallArgumentListSyntax {
subscript(_ i: Int) -> FunctionCallArgumentSyntax {
let index = self.index(startIndex, offsetBy: i)
return self[index]
}
}
extension ExprListSyntax {
subscript(_ i: Int) -> ExprSyntax {
let index = self.index(startIndex, offsetBy: i)
return self[index]
}
}
extension PatternBindingListSyntax {
subscript(_ i: Int) -> PatternBindingSyntax {
let index = self.index(startIndex, offsetBy: i)
return self[index]
}
}
extension TupleTypeElementListSyntax {
subscript(_ i: Int) -> TupleTypeElementSyntax {
let index = self.index(startIndex, offsetBy: i)
return self[index]
}
}
<file_sep>/Sources/SwiftLeakCheck/GraphBuilder.swift
//
// GraphBuilder.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 29/10/2019.
//
import SwiftSyntax
final class GraphBuilder {
static func buildGraph(node: SourceFileSyntax) -> GraphImpl {
// First round: build the graph
let visitor = GraphBuilderVistor()
visitor.walk(node)
let graph = GraphImpl(sourceFileScope: visitor.sourceFileScope)
// Second round: resolve the references
ReferenceBuilderVisitor(graph: graph).walk(node)
return graph
}
}
class BaseGraphVistor: SyntaxAnyVisitor {
override func visit(_ node: UnknownDeclSyntax) -> SyntaxVisitorContinueKind {
return .skipChildren
}
override func visit(_ node: UnknownExprSyntax) -> SyntaxVisitorContinueKind {
return .skipChildren
}
override func visit(_ node: UnknownStmtSyntax) -> SyntaxVisitorContinueKind {
return .skipChildren
}
override func visit(_ node: UnknownTypeSyntax) -> SyntaxVisitorContinueKind {
return .skipChildren
}
override func visit(_ node: UnknownPatternSyntax) -> SyntaxVisitorContinueKind {
return .skipChildren
}
}
fileprivate final class GraphBuilderVistor: BaseGraphVistor {
fileprivate var sourceFileScope: SourceFileScope!
private var stack = Stack<Scope>()
override func visitAny(_ node: Syntax) -> SyntaxVisitorContinueKind {
if let scopeNode = ScopeNode.from(node: node) {
if case let .sourceFileNode(node) = scopeNode {
assert(stack.peek() == nil)
sourceFileScope = SourceFileScope(node: node, parent: stack.peek())
stack.push(sourceFileScope)
} else {
let scope = Scope(scopeNode: scopeNode, parent: stack.peek())
stack.push(scope)
}
}
#if DEBUG
if node.is(ElseBlockSyntax.self) || node.is(ElseIfContinuationSyntax.self) {
assertionFailure("Unhandled case")
}
#endif
return super.visitAny(node)
}
override func visitAnyPost(_ node: Syntax) {
if let scopeNode = ScopeNode.from(node: node) {
assert(stack.peek()?.scopeNode == scopeNode)
stack.pop()
}
super.visitAnyPost(node)
}
// Note: this is not necessarily in a func x(param...)
// Take this example:
// x.block { param in ... }
// Swift treats `param` as ClosureParamSyntax , but if we put `param` in open and close parathenses,
// Swift will treat it as FunctionParameterSyntax
override func visit(_ node: FunctionParameterSyntax) -> SyntaxVisitorContinueKind {
_ = super.visit(node)
guard let scope = stack.peek(), scope.type.isFunction || scope.type == .enumCaseNode else {
fatalError()
}
guard let name = node.secondName ?? node.firstName else {
assert(scope.type == .enumCaseNode)
return .visitChildren
}
guard name.tokenKind != .wildcardKeyword else {
return .visitChildren
}
scope.addVariable(Variable.from(node, scope: scope))
return .visitChildren
}
override func visit(_ node: ClosureCaptureItemSyntax) -> SyntaxVisitorContinueKind {
_ = super.visit(node)
guard let scope = stack.peek(), scope.isClosure else {
fatalError()
}
Variable.from(node, scope: scope).flatMap { scope.addVariable($0) }
return .visitChildren
}
override func visit(_ node: ClosureParamSyntax) -> SyntaxVisitorContinueKind {
_ = super.visit(node)
guard let scope = stack.peek(), scope.isClosure else {
fatalError("A closure should be found for a ClosureParam node. Stack may have been corrupted")
}
scope.addVariable(Variable.from(node, scope: scope))
return .visitChildren
}
override func visit(_ node: PatternBindingSyntax) -> SyntaxVisitorContinueKind {
_ = super.visit(node)
guard let scope = stack.peek() else {
fatalError()
}
Variable.from(node, scope: scope).forEach {
scope.addVariable($0)
}
return .visitChildren
}
override func visit(_ node: OptionalBindingConditionSyntax) -> SyntaxVisitorContinueKind {
_ = super.visit(node)
guard let scope = stack.peek() else {
fatalError()
}
let isGuardCondition = node.isGuardCondition()
assert(!isGuardCondition || scope.type == .guardNode)
let scopeThatOwnVariable = (isGuardCondition ? scope.parent! : scope)
if let variable = Variable.from(node, scope: scopeThatOwnVariable) {
scopeThatOwnVariable.addVariable(variable)
}
return .visitChildren
}
override func visit(_ node: ForInStmtSyntax) -> SyntaxVisitorContinueKind {
_ = super.visit(node)
guard let scope = stack.peek(), scope.type == .forLoopNode else {
fatalError()
}
Variable.from(node, scope: scope).forEach { variable in
scope.addVariable(variable)
}
return .visitChildren
}
}
/// Visit the tree and resolve references
private final class ReferenceBuilderVisitor: BaseGraphVistor {
private let graph: GraphImpl
init(graph: GraphImpl) {
self.graph = graph
}
override func visit(_ node: IdentifierExprSyntax) -> SyntaxVisitorContinueKind {
graph.resolveVariable(node)
return .visitChildren
}
}
private extension Scope {
var isClosure: Bool {
return type == .closureNode
}
}
<file_sep>/Sources/SwiftLeakCheck/LeakDetector.swift
//
// LeakDetector.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 27/10/2019.
//
import SwiftSyntax
import Foundation
public protocol LeakDetector {
func detect(content: String) throws -> [Leak]
}
extension LeakDetector {
public func detect(_ filePath: String) throws -> [Leak] {
return try detect(content: String(contentsOfFile: filePath))
}
public func detect(_ url: URL) throws -> [Leak] {
return try detect(content: String(contentsOf: url))
}
}
<file_sep>/Sources/SwiftLeakCheck/BackwardCompatiblity.swift
//
// Tmp.swift
// SwiftLeakCheck
//
// Created by <NAME> on 07/02/2021.
//
import SwiftSyntax
// For backward-compatible with Swift compiler 4.2 type names
public typealias FunctionCallArgumentListSyntax = TupleExprElementListSyntax
public typealias FunctionCallArgumentSyntax = TupleExprElementSyntax
<file_sep>/Sources/SwiftLeakCheck/SyntaxRetrieval.swift
//
// SyntaxRetrieval.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 09/12/2019.
//
import SwiftSyntax
public enum SyntaxRetrieval {
public static func request(content: String) throws -> SourceFileSyntax {
return try SyntaxParser.parse(
source: content
)
}
}
<file_sep>/Sources/SwiftLeakCheck/DirectoryScanner.swift
//
// DirectoryScanner.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 09/12/2019.
//
import Foundation
public final class DirectoryScanner {
private let callback: (URL, inout Bool) -> Void
private var shouldStop = false
public init(callback: @escaping (URL, inout Bool) -> Void) {
self.callback = callback
}
public func scan(url: URL) {
if shouldStop {
shouldStop = false // Clear
return
}
let isDirectory = (try? url.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory ?? false
if !isDirectory {
callback(url, &shouldStop)
} else {
let enumerator = FileManager.default.enumerator(
at: url,
includingPropertiesForKeys: nil,
options: [.skipsSubdirectoryDescendants],
errorHandler: nil
)!
for childPath in enumerator {
if let url = childPath as? URL {
scan(url: url)
if shouldStop {
return
}
}
}
}
}
}
<file_sep>/Sources/SwiftLeakCheck/FunctionSignature.swift
//
// FunctionSignature.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 15/12/2019.
//
import SwiftSyntax
public struct FunctionSignature {
public let funcName: String
public let params: [FunctionParam]
public init(name: String, params: [FunctionParam]) {
self.funcName = name
self.params = params
}
public static func from(functionDeclExpr: FunctionDeclSyntax) -> (FunctionSignature, [FunctionParam: FunctionParameterSyntax]) {
let funcName = functionDeclExpr.identifier.text
let params = functionDeclExpr.signature.input.parameterList.map { FunctionParam(param: $0) }
let mapping = Dictionary(uniqueKeysWithValues: zip(params, functionDeclExpr.signature.input.parameterList))
return (FunctionSignature(name: funcName, params: params), mapping)
}
public enum MatchResult: Equatable {
public struct MappingInfo: Equatable {
let argumentToParamMapping: [FunctionCallArgumentSyntax: FunctionParam]
let trailingClosureArgumentToParam: FunctionParam?
}
case nameMismatch
case argumentMismatch
case matched(MappingInfo)
var isMatched: Bool {
switch self {
case .nameMismatch,
.argumentMismatch:
return false
case .matched:
return true
}
}
}
public func match(_ functionCallExpr: FunctionCallExprSyntax) -> MatchResult {
guard funcName == functionCallExpr.symbol?.text else {
return .nameMismatch
}
print("Debug: \(functionCallExpr)")
return match((ArgumentListWrapper(functionCallExpr.argumentList), functionCallExpr.trailingClosure))
}
private func match(_ rhs: (ArgumentListWrapper, ClosureExprSyntax?)) -> MatchResult {
let (arguments, trailingClosure) = rhs
guard params.count > 0 else {
if arguments.count == 0 && trailingClosure == nil {
return .matched(.init(argumentToParamMapping: [:], trailingClosureArgumentToParam: nil))
} else {
return .argumentMismatch
}
}
let firstParam = params[0]
if firstParam.canOmit {
let matchResult = removingFirstParam().match(rhs)
if matchResult.isMatched {
return matchResult
}
}
guard arguments.count > 0 else {
// In order to match, trailingClosure must be firstParam, there're no more params
guard let trailingClosure = trailingClosure else {
return .argumentMismatch
}
if params.count > 1 {
return .argumentMismatch
}
if isMatched(param: firstParam, trailingClosure: trailingClosure) {
return .matched(.init(argumentToParamMapping: [:], trailingClosureArgumentToParam: firstParam))
} else {
return .argumentMismatch
}
}
let firstArgument = arguments[0]
guard isMatched(param: firstParam, argument: firstArgument) else {
return .argumentMismatch
}
let matchResult = removingFirstParam().match((arguments.removingFirst(), trailingClosure))
if case let .matched(matchInfo) = matchResult {
var argumentToParamMapping = matchInfo.argumentToParamMapping
argumentToParamMapping[firstArgument] = firstParam
return .matched(.init(argumentToParamMapping: argumentToParamMapping, trailingClosureArgumentToParam: matchInfo.trailingClosureArgumentToParam))
} else {
return .argumentMismatch
}
}
// TODO: type matching
private func isMatched(param: FunctionParam, argument: FunctionCallArgumentSyntax) -> Bool {
return param.name == argument.label?.text
}
private func isMatched(param: FunctionParam, trailingClosure: ClosureExprSyntax) -> Bool {
return param.isClosure
}
private func removingFirstParam() -> FunctionSignature {
return FunctionSignature(name: funcName, params: Array(params[1...]))
}
}
public struct FunctionParam: Hashable {
public let name: String?
public let secondName: String? // This acts as a way to differentiate param when name is omitted. Don't remove this
public let canOmit: Bool
public let isClosure: Bool
public init(name: String?,
secondName: String? = nil,
isClosure: Bool = false,
canOmit: Bool = false) {
assert(name != "_")
self.name = name
self.secondName = secondName
self.isClosure = isClosure
self.canOmit = canOmit
}
public init(param: FunctionParameterSyntax) {
name = (param.firstName?.text == "_" ? nil : param.firstName?.text)
secondName = param.secondName?.text
isClosure = (param.type?.isClosure == true)
canOmit = param.defaultArgument != nil
}
}
private struct ArgumentListWrapper {
let argumentList: FunctionCallArgumentListSyntax
private let startIndex: Int
init(_ argumentList: FunctionCallArgumentListSyntax) {
self.init(argumentList, startIndex: 0)
}
private init(_ argumentList: FunctionCallArgumentListSyntax, startIndex: Int) {
self.argumentList = argumentList
self.startIndex = startIndex
}
func removingFirst() -> ArgumentListWrapper {
return ArgumentListWrapper(argumentList, startIndex: startIndex + 1)
}
subscript(_ i: Int) -> FunctionCallArgumentSyntax {
return argumentList[startIndex + i]
}
var count: Int {
return argumentList.count - startIndex
}
}
<file_sep>/Sources/SwiftLeakCheck/NonEscapeRules/UIViewAnimationRule.swift
//
// UIViewAnimationRule.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 28/10/2019.
//
import SwiftSyntax
/// Eg, UIView.animate(..., animations: {...}) {
/// .....
/// }
open class UIViewAnimationRule: BaseNonEscapeRule {
private let signatures: [FunctionSignature] = [
FunctionSignature(name: "animate", params: [
FunctionParam(name: "withDuration"),
FunctionParam(name: "animations", isClosure: true)
]),
FunctionSignature(name: "animate", params: [
FunctionParam(name: "withDuration"),
FunctionParam(name: "animations", isClosure: true),
FunctionParam(name: "completion", isClosure: true, canOmit: true)
]),
FunctionSignature(name: "animate", params: [
FunctionParam(name: "withDuration"),
FunctionParam(name: "delay"),
FunctionParam(name: "options", canOmit: true),
FunctionParam(name: "animations", isClosure: true),
FunctionParam(name: "completion", isClosure: true, canOmit: true)
]),
FunctionSignature(name: "animate", params: [
FunctionParam(name: "withDuration"),
FunctionParam(name: "delay"),
FunctionParam(name: "usingSpringWithDamping"),
FunctionParam(name: "initialSpringVelocity"),
FunctionParam(name: "options", canOmit: true),
FunctionParam(name: "animations", isClosure: true),
FunctionParam(name: "completion", isClosure: true, canOmit: true)
]),
FunctionSignature(name: "transition", params: [
FunctionParam(name: "from"),
FunctionParam(name: "to"),
FunctionParam(name: "duration"),
FunctionParam(name: "options"),
FunctionParam(name: "completion", isClosure: true, canOmit: true),
]),
FunctionSignature( name: "transition", params: [
FunctionParam(name: "with"),
FunctionParam(name: "duration"),
FunctionParam(name: "options"),
FunctionParam(name: "animations", isClosure: true, canOmit: true),
FunctionParam(name: "completion", isClosure: true, canOmit: true),
]),
FunctionSignature(name: "animateKeyframes", params: [
FunctionParam(name: "withDuration"),
FunctionParam(name: "delay", canOmit: true),
FunctionParam(name: "options", canOmit: true),
FunctionParam(name: "animations", isClosure: true),
FunctionParam(name: "completion", isClosure: true)
])
]
open override func isNonEscape(arg: FunctionCallArgumentSyntax?,
funcCallExpr: FunctionCallExprSyntax,
graph: Graph) -> Bool {
// Check if base is `UIView`, if not we can end early without checking any of the signatures
guard funcCallExpr.match(.funcCall(namePredicate: { _ in true }, base: .name("UIView"))) else {
return false
}
// Now we can check each signature and ignore the base (already checked)
for signature in signatures {
if funcCallExpr.match(.funcCall(signature: signature, base: .any)) {
return true
}
}
return false
}
}
<file_sep>/Sources/SwiftLeakCheck/Scope.swift
//
// Scope.swift
// LeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 27/10/2019.
//
import SwiftSyntax
public enum ScopeNode: Hashable, CustomStringConvertible {
case sourceFileNode(SourceFileSyntax)
case classNode(ClassDeclSyntax)
case structNode(StructDeclSyntax)
case enumNode(EnumDeclSyntax)
case enumCaseNode(EnumCaseDeclSyntax)
case extensionNode(ExtensionDeclSyntax)
case funcNode(FunctionDeclSyntax)
case initialiseNode(InitializerDeclSyntax)
case closureNode(ClosureExprSyntax)
case ifBlockNode(CodeBlockSyntax, IfStmtSyntax) // If block in a `IfStmtSyntax`
case elseBlockNode(CodeBlockSyntax, IfStmtSyntax) // Else block in a `IfStmtSyntax`
case guardNode(GuardStmtSyntax)
case forLoopNode(ForInStmtSyntax)
case whileLoopNode(WhileStmtSyntax)
case subscriptNode(SubscriptDeclSyntax)
case accessorNode(AccessorDeclSyntax)
case variableDeclNode(CodeBlockSyntax) // var x: Int { ... }
case switchCaseNode(SwitchCaseSyntax)
public static func from(node: Syntax) -> ScopeNode? {
if let sourceFileNode = node.as(SourceFileSyntax.self) {
return .sourceFileNode(sourceFileNode)
}
if let classNode = node.as(ClassDeclSyntax.self) {
return .classNode(classNode)
}
if let structNode = node.as(StructDeclSyntax.self) {
return .structNode(structNode)
}
if let enumNode = node.as(EnumDeclSyntax.self) {
return .enumNode(enumNode)
}
if let enumCaseNode = node.as(EnumCaseDeclSyntax.self) {
return .enumCaseNode(enumCaseNode)
}
if let extensionNode = node.as(ExtensionDeclSyntax.self) {
return .extensionNode(extensionNode)
}
if let funcNode = node.as(FunctionDeclSyntax.self) {
return .funcNode(funcNode)
}
if let initialiseNode = node.as(InitializerDeclSyntax.self) {
return .initialiseNode(initialiseNode)
}
if let closureNode = node.as(ClosureExprSyntax.self) {
return .closureNode(closureNode)
}
if let codeBlockNode = node.as(CodeBlockSyntax.self), codeBlockNode.parent?.is(IfStmtSyntax.self) == true {
let parent = (codeBlockNode.parent?.as(IfStmtSyntax.self))!
if codeBlockNode == parent.body {
return .ifBlockNode(codeBlockNode, parent)
} else if codeBlockNode == parent.elseBody?.as(CodeBlockSyntax.self) {
return .elseBlockNode(codeBlockNode, parent)
}
return nil
}
if let guardNode = node.as(GuardStmtSyntax.self) {
return .guardNode(guardNode)
}
if let forLoopNode = node.as(ForInStmtSyntax.self) {
return .forLoopNode(forLoopNode)
}
if let whileLoopNode = node.as(WhileStmtSyntax.self) {
return .whileLoopNode(whileLoopNode)
}
if let subscriptNode = node.as(SubscriptDeclSyntax.self) {
return .subscriptNode(subscriptNode)
}
if let accessorNode = node.as(AccessorDeclSyntax.self) {
return .accessorNode(accessorNode)
}
if let codeBlockNode = node.as(CodeBlockSyntax.self),
codeBlockNode.parent?.is(PatternBindingSyntax.self) == true,
codeBlockNode.parent?.parent?.is(PatternBindingListSyntax.self) == true,
codeBlockNode.parent?.parent?.parent?.is(VariableDeclSyntax.self) == true {
return .variableDeclNode(codeBlockNode)
}
if let switchCaseNode = node.as(SwitchCaseSyntax.self) {
return .switchCaseNode(switchCaseNode)
}
return nil
}
public var node: Syntax {
switch self {
case .sourceFileNode(let node): return node._syntaxNode
case .classNode(let node): return node._syntaxNode
case .structNode(let node): return node._syntaxNode
case .enumNode(let node): return node._syntaxNode
case .enumCaseNode(let node): return node._syntaxNode
case .extensionNode(let node): return node._syntaxNode
case .funcNode(let node): return node._syntaxNode
case .initialiseNode(let node): return node._syntaxNode
case .closureNode(let node): return node._syntaxNode
case .ifBlockNode(let node, _): return node._syntaxNode
case .elseBlockNode(let node, _): return node._syntaxNode
case .guardNode(let node): return node._syntaxNode
case .forLoopNode(let node): return node._syntaxNode
case .whileLoopNode(let node): return node._syntaxNode
case .subscriptNode(let node): return node._syntaxNode
case .accessorNode(let node): return node._syntaxNode
case .variableDeclNode(let node): return node._syntaxNode
case .switchCaseNode(let node): return node._syntaxNode
}
}
public var type: ScopeType {
switch self {
case .sourceFileNode: return .sourceFileNode
case .classNode: return .classNode
case .structNode: return .structNode
case .enumNode: return .enumNode
case .enumCaseNode: return .enumCaseNode
case .extensionNode: return .extensionNode
case .funcNode: return .funcNode
case .initialiseNode: return .initialiseNode
case .closureNode: return .closureNode
case .ifBlockNode, .elseBlockNode: return .ifElseNode
case .guardNode: return .guardNode
case .forLoopNode: return .forLoopNode
case .whileLoopNode: return .whileLoopNode
case .subscriptNode: return .subscriptNode
case .accessorNode: return .accessorNode
case .variableDeclNode: return .variableDeclNode
case .switchCaseNode: return .switchCaseNode
}
}
public var enclosingScopeNode: ScopeNode? {
return node.enclosingScopeNode
}
public var description: String {
return "\(node)"
}
}
public enum ScopeType: Equatable {
case sourceFileNode
case classNode
case structNode
case enumNode
case enumCaseNode
case extensionNode
case funcNode
case initialiseNode
case closureNode
case ifElseNode
case guardNode
case forLoopNode
case whileLoopNode
case subscriptNode
case accessorNode
case variableDeclNode
case switchCaseNode
public var isTypeDecl: Bool {
return self == .classNode
|| self == .structNode
|| self == .enumNode
|| self == .extensionNode
}
public var isFunction: Bool {
return self == .funcNode
|| self == .initialiseNode
|| self == .closureNode
|| self == .subscriptNode
}
}
open class Scope: Hashable, CustomStringConvertible {
public let scopeNode: ScopeNode
public let parent: Scope?
public private(set) var variables = Stack<Variable>()
public private(set) var childScopes = [Scope]()
public var type: ScopeType {
return scopeNode.type
}
public var childFunctions: [Function] {
return childScopes
.compactMap { scope in
if case let .funcNode(funcNode) = scope.scopeNode {
return funcNode
}
return nil
}
}
public var childTypeDecls: [TypeDecl] {
return childScopes
.compactMap { $0.typeDecl }
}
public var typeDecl: TypeDecl? {
switch scopeNode {
case .classNode(let node):
return TypeDecl(tokens: [node.identifier], inheritanceTypes: node.inheritanceClause?.inheritedTypeCollection.map { $0 }, scope: self)
case .structNode(let node):
return TypeDecl(tokens: [node.identifier], inheritanceTypes: node.inheritanceClause?.inheritedTypeCollection.map { $0 }, scope: self)
case .enumNode(let node):
return TypeDecl(tokens: [node.identifier], inheritanceTypes: node.inheritanceClause?.inheritedTypeCollection.map { $0 }, scope: self)
case .extensionNode(let node):
return TypeDecl(tokens: node.extendedType.tokens!, inheritanceTypes: node.inheritanceClause?.inheritedTypeCollection.map { $0 }, scope: self)
default:
return nil
}
}
// Whether a variable can be used before it's declared. This is true for node that defines type, such as class, struct, enum,....
// Otherwise if a variable is inside func, or closure, or normal block (if, guard,..), it must be declared before being used
public var canUseVariableOrFuncInAnyOrder: Bool {
return type == .classNode
|| type == .structNode
|| type == .enumNode
|| type == .extensionNode
|| type == .sourceFileNode
}
public init(scopeNode: ScopeNode, parent: Scope?) {
self.parent = parent
self.scopeNode = scopeNode
parent?.childScopes.append(self)
if let parent = parent {
assert(scopeNode.node.isDescendent(of: parent.scopeNode.node))
}
}
func addVariable(_ variable: Variable) {
assert(variable.scope == self)
variables.push(variable)
}
func getVariable(_ node: IdentifierExprSyntax) -> Variable? {
let name = node.identifier.text
for variable in variables.filter({ $0.name == name }) {
// Special case: guard let `x` = x else { ... }
// or: let x = x.doSmth()
// Here x on the right cannot be resolved to x on the left
if case let .binding(_, valueNode) = variable.raw,
valueNode != nil && node._syntaxNode.isDescendent(of: valueNode!._syntaxNode) {
continue
}
if variable.raw.token.isBefore(node) {
return variable
} else if !canUseVariableOrFuncInAnyOrder {
// Stop
break
}
}
return nil
}
func getFunctionWithSymbol(_ symbol: Symbol) -> [Function] {
return childFunctions.filter { function in
if function.identifier.isBefore(symbol.node) || canUseVariableOrFuncInAnyOrder {
return function.identifier.text == symbol.name
}
return false
}
}
func getTypeDecl(name: String) -> [TypeDecl] {
return childTypeDecls
.filter { typeDecl in
return typeDecl.name == [name]
}
}
open var description: String {
return "\(scopeNode)"
}
}
// MARK: - Hashable
extension Scope {
open func hash(into hasher: inout Hasher) {
scopeNode.hash(into: &hasher)
}
public static func == (_ lhs: Scope, _ rhs: Scope) -> Bool {
return lhs.scopeNode == rhs.scopeNode
}
}
extension SyntaxProtocol {
public var enclosingScopeNode: ScopeNode? {
var parent = self.parent
while parent != nil {
if let scopeNode = ScopeNode.from(node: parent!) {
return scopeNode
}
parent = parent?.parent
}
return nil
}
}
<file_sep>/Sources/SwiftLeakCheck/Variable.swift
//
// Variable.swift
// LeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 27/10/2019.
//
import SwiftSyntax
public enum RawVariable {
case capture(capturedNode: IdentifierExprSyntax)
case param(token: TokenSyntax)
case binding(token: TokenSyntax, valueNode: ExprSyntax?)
var token: TokenSyntax {
switch self {
case .capture(let capturedNode): return capturedNode.identifier
case .binding(let token, _): return token
case .param(let token): return token
}
}
}
indirect enum TypeInfo {
case exact(TypeSyntax)
case inferedFromExpr(ExprSyntax)
case inferedFromSequence(ExprSyntax)
case inferedFromTuple(tupleType: TypeInfo, index: Int)
case inferedFromClosure(ClosureExprSyntax, paramIndex: Int, paramCount: Int)
}
// Represent a variable declaration. Eg
// var a = 1
// let b = c // b is the Variable, c is not (c is a reference)
// block { [unowned x] in // x is a Variable
// func doSmth(a: Int, b: String) // a, b are Variables
public class Variable: Hashable, CustomStringConvertible {
public let raw: RawVariable
public var name: String { return raw.token.text }
let typeInfo: TypeInfo
public let memoryAttribute: MemoryAttribute?
public let scope: Scope
var valueNode: ExprSyntax? {
switch raw {
case .binding(_, let valueNode): return valueNode
case .param, .capture: return nil
}
}
var capturedNode: IdentifierExprSyntax? {
switch raw {
case .capture(let capturedNode): return capturedNode
case .binding, .param: return nil
}
}
public var isStrong: Bool {
return memoryAttribute?.isStrong ?? true
}
public var description: String {
return "\(raw)"
}
private init(raw: RawVariable,
typeInfo: TypeInfo,
scope: Scope,
memoryAttribute: MemoryAttribute? = nil) {
self.raw = raw
self.typeInfo = typeInfo
self.scope = scope
self.memoryAttribute = memoryAttribute
}
public static func from(_ node: ClosureCaptureItemSyntax, scope: Scope) -> Variable? {
assert(scope.scopeNode == node.enclosingScopeNode)
guard let identifierExpr = node.expression.as(IdentifierExprSyntax.self) else {
// There're cases such as { [loggedInState.services] in ... }, which probably we don't need to care about
return nil
}
let memoryAttribute: MemoryAttribute? = {
guard let specifier = node.specifier?.first else {
return nil
}
assert(node.specifier!.count <= 1, "Unhandled case")
guard let memoryAttribute = MemoryAttribute.from(specifier.text) else {
fatalError("Unhandled specifier \(specifier.text)")
}
return memoryAttribute
}()
return Variable(
raw: .capture(capturedNode: identifierExpr),
typeInfo: .inferedFromExpr(ExprSyntax(identifierExpr)),
scope: scope,
memoryAttribute: memoryAttribute
)
}
public static func from(_ node: ClosureParamSyntax, scope: Scope) -> Variable {
guard let closure = node.getEnclosingClosureNode() else {
fatalError()
}
assert(scope.scopeNode == .closureNode(closure))
return Variable(
raw: .param(token: node.name),
typeInfo: .inferedFromClosure(closure, paramIndex: node.indexInParent, paramCount: node.parent!.children.count),
scope: scope
)
}
public static func from(_ node: FunctionParameterSyntax, scope: Scope) -> Variable {
assert(node.enclosingScopeNode == scope.scopeNode)
guard let token = node.secondName ?? node.firstName else {
fatalError()
}
assert(token.tokenKind != .wildcardKeyword, "Unhandled case")
assert(node.attributes == nil, "Unhandled case")
guard let type = node.type else {
// Type is omited, must be used in closure signature
guard case let .closureNode(closureNode) = scope.scopeNode else {
fatalError("Only closure can omit the param type")
}
return Variable(
raw: .param(token: token),
typeInfo: .inferedFromClosure(closureNode, paramIndex: node.indexInParent, paramCount: node.parent!.children.count),
scope: scope
)
}
return Variable(raw: .param(token: token), typeInfo: .exact(type), scope: scope)
}
public static func from(_ node: PatternBindingSyntax, scope: Scope) -> [Variable] {
guard let parent = node.parent?.as(PatternBindingListSyntax.self) else {
fatalError()
}
assert(parent.parent?.is(VariableDeclSyntax.self) == true, "Unhandled case")
func _typeFromNode(_ node: PatternBindingSyntax) -> TypeInfo {
// var a: Int
if let typeAnnotation = node.typeAnnotation {
return .exact(typeAnnotation.type)
}
// var a = value
if let value = node.initializer?.value {
return .inferedFromExpr(value)
}
// var a, b, .... = value
let indexOfNextNode = node.indexInParent + 1
return _typeFromNode(parent[indexOfNextNode])
}
let type = _typeFromNode(node)
if let identifier = node.pattern.as(IdentifierPatternSyntax.self) {
let memoryAttribute: MemoryAttribute? = {
if let modifier = node.parent?.parent?.as(VariableDeclSyntax.self)!.modifiers?.first {
return MemoryAttribute.from(modifier.name.text)
}
return nil
}()
return [
Variable(
raw: .binding(token: identifier.identifier, valueNode: node.initializer?.value),
typeInfo: type,
scope: scope,
memoryAttribute: memoryAttribute
)
]
}
if let tuple = node.pattern.as(TuplePatternSyntax.self) {
return extractVariablesFromTuple(tuple, tupleType: type, tupleValue: node.initializer?.value, scope: scope)
}
return []
}
public static func from(_ node: OptionalBindingConditionSyntax, scope: Scope) -> Variable? {
if let left = node.pattern.as(IdentifierPatternSyntax.self) {
let right = node.initializer.value
let type: TypeInfo
if let typeAnnotation = node.typeAnnotation {
type = .exact(typeAnnotation.type)
} else {
type = .inferedFromExpr(right)
}
return Variable(
raw: .binding(token: left.identifier, valueNode: right),
typeInfo: type,
scope: scope,
memoryAttribute: .strong
)
}
return nil
}
public static func from(_ node: ForInStmtSyntax, scope: Scope) -> [Variable] {
func _variablesFromPattern(_ pattern: PatternSyntax) -> [Variable] {
if let identifierPattern = pattern.as(IdentifierPatternSyntax.self) {
return [
Variable(
raw: .binding(token: identifierPattern.identifier, valueNode: nil),
typeInfo: .inferedFromSequence(node.sequenceExpr),
scope: scope
)
]
}
if let tuplePattern = pattern.as(TuplePatternSyntax.self) {
return extractVariablesFromTuple(
tuplePattern,
tupleType: .inferedFromSequence(node.sequenceExpr),
tupleValue: nil,
scope: scope
)
}
if pattern.is(WildcardPatternSyntax.self) {
return []
}
if let valueBindingPattern = pattern.as(ValueBindingPatternSyntax.self) {
return _variablesFromPattern(valueBindingPattern.valuePattern)
}
assert(false, "Unhandled pattern in for statement: \(pattern)")
return []
}
return _variablesFromPattern(node.pattern)
}
private static func extractVariablesFromTuple(_ tuplePattern: TuplePatternSyntax,
tupleType: TypeInfo,
tupleValue: ExprSyntax?,
scope: Scope) -> [Variable] {
return tuplePattern.elements.enumerated().flatMap { (index, element) -> [Variable] in
let elementType: TypeInfo = .inferedFromTuple(tupleType: tupleType, index: index)
let elementValue: ExprSyntax? = {
if let tupleValue = tupleValue?.as(TupleExprSyntax.self) {
return tupleValue.elementList[index].expression
}
return nil
}()
if let identifierPattern = element.pattern.as(IdentifierPatternSyntax.self) {
return [
Variable(
raw: .binding(token: identifierPattern.identifier, valueNode: elementValue),
typeInfo: elementType,
scope: scope
)
]
}
if let childTuplePattern = element.pattern.as(TuplePatternSyntax.self) {
return extractVariablesFromTuple(
childTuplePattern,
tupleType: elementType,
tupleValue: elementValue,
scope: scope
)
}
if element.pattern.is(WildcardPatternSyntax.self) {
return []
}
assertionFailure("I don't think there's any other kind")
return []
}
}
}
// MARK: - Hashable
public extension Variable {
static func == (_ lhs: Variable, _ rhs: Variable) -> Bool {
return lhs.raw.token == rhs.raw.token
}
func hash(into hasher: inout Hasher) {
hasher.combine(raw.token)
}
}
public enum MemoryAttribute: Hashable {
case weak
case unowned
case strong
public var isStrong: Bool {
switch self {
case .weak,
.unowned:
return false
case .strong:
return true
}
}
public static func from(_ text: String) -> MemoryAttribute? {
switch text {
case "weak":
return .weak
case "unowned":
return .unowned
default:
return nil
}
}
}
<file_sep>/Sources/SwiftLeakChecker/main.swift
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
import Foundation
import SwiftLeakCheck
enum CommandLineError: Error, LocalizedError {
case missingFileName
var errorDescription: String? {
switch self {
case .missingFileName:
return "Missing file or directory name"
}
}
}
do {
let arguments = CommandLine.arguments
guard arguments.count > 1 else {
throw CommandLineError.missingFileName
}
let path = arguments[1]
let url = URL(fileURLWithPath: path)
let dirScanner = DirectoryScanner(callback: { fileUrl, shouldStop in
do {
guard fileUrl.pathExtension == "swift" else {
return
}
print("Scan \(fileUrl)")
let leakDetector = GraphLeakDetector()
leakDetector.nonEscapeRules = [
UIViewAnimationRule(),
UIViewControllerAnimationRule(),
DispatchQueueRule()
] + CollectionRules.rules
let startDate = Date()
let leaks = try leakDetector.detect(fileUrl)
let endDate = Date()
print("Finished in \(endDate.timeIntervalSince(startDate)) seconds")
leaks.forEach { leak in
print(leak.description)
}
} catch {}
})
dirScanner.scan(url: url)
} catch {
print("\(error.localizedDescription)")
}
<file_sep>/Sources/SwiftLeakCheck/NonEscapeRules/NonEscapeRule.swift
//
// NonEscapeRule.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 28/10/2019.
//
import SwiftSyntax
public protocol NonEscapeRule {
func isNonEscape(closureNode: ExprSyntax, graph: Graph) -> Bool
}
open class BaseNonEscapeRule: NonEscapeRule {
public init() {}
public func isNonEscape(closureNode: ExprSyntax, graph: Graph) -> Bool {
guard let (funcCallExpr, arg) = closureNode.getEnclosingFunctionCallExpression() else {
return false
}
return isNonEscape(
arg: arg,
funcCallExpr: funcCallExpr,
graph: graph
)
}
/// Returns whether a given argument is escaping in a function call
///
/// - Parameters:
/// - arg: The closure argument, or nil if it's trailing closure
/// - funcCallExpr: the source FunctionCallExprSyntax
/// - graph: Source code graph. Use it to retrieve more info
/// - Returns: true if the closure is non-escaping, false otherwise
open func isNonEscape(arg: FunctionCallArgumentSyntax?,
funcCallExpr: FunctionCallExprSyntax,
graph: Graph) -> Bool {
return false
}
}
<file_sep>/Sources/SwiftLeakCheck/Symbol.swift
//
// Symbol.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 03/01/2020.
//
import SwiftSyntax
public enum Symbol: Hashable {
case token(TokenSyntax)
case identifier(IdentifierExprSyntax)
var node: Syntax {
switch self {
case .token(let node): return node._syntaxNode
case .identifier(let node): return node._syntaxNode
}
}
var name: String {
switch self {
case .token(let node): return node.text
case .identifier(let node): return node.identifier.text
}
}
}
<file_sep>/Sources/SwiftLeakCheck/GraphLeakDetector.swift
//
// GraphLeakDetector.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 12/11/2019.
//
import SwiftSyntax
public final class GraphLeakDetector: BaseSyntaxTreeLeakDetector {
public var nonEscapeRules: [NonEscapeRule] = []
override public func detect(_ sourceFileNode: SourceFileSyntax) -> [Leak] {
var res: [Leak] = []
let graph = GraphBuilder.buildGraph(node: sourceFileNode)
let sourceLocationConverter = SourceLocationConverter(file: "", tree: sourceFileNode)
let visitor = LeakSyntaxVisitor(graph: graph, nonEscapeRules: nonEscapeRules, sourceLocationConverter: sourceLocationConverter) { leak in
res.append(leak)
}
visitor.walk(sourceFileNode)
return res
}
}
private final class LeakSyntaxVisitor: BaseGraphVistor {
private let graph: GraphImpl
private let sourceLocationConverter: SourceLocationConverter
private let onLeakDetected: (Leak) -> Void
private let nonEscapeRules: [NonEscapeRule]
init(graph: GraphImpl,
nonEscapeRules: [NonEscapeRule],
sourceLocationConverter: SourceLocationConverter,
onLeakDetected: @escaping (Leak) -> Void) {
self.graph = graph
self.sourceLocationConverter = sourceLocationConverter
self.nonEscapeRules = nonEscapeRules
self.onLeakDetected = onLeakDetected
}
override func visit(_ node: IdentifierExprSyntax) -> SyntaxVisitorContinueKind {
detectLeak(node)
return .skipChildren
}
private func detectLeak(_ node: IdentifierExprSyntax) {
var leak: Leak?
defer {
if let leak = leak {
onLeakDetected(leak)
}
}
if node.getEnclosingClosureNode() == nil {
// Not inside closure -> ignore
return
}
if !graph.couldReferenceSelf(ExprSyntax(node)) {
return
}
var currentScope: Scope! = graph.closetScopeThatCanResolveSymbol(.identifier(node))
var isEscape = false
while currentScope != nil {
if let variable = currentScope.getVariable(node) {
if !isEscape {
// No leak
return
}
switch variable.raw {
case .param:
fatalError("Can't happen since a param cannot reference `self`")
case let .capture(capturedNode):
if variable.isStrong && isEscape {
leak = Leak(node: node, capturedNode: ExprSyntax(capturedNode), sourceLocationConverter: sourceLocationConverter)
}
case let .binding(_, valueNode):
if let referenceNode = valueNode?.as(IdentifierExprSyntax.self) {
if variable.isStrong && isEscape {
leak = Leak(node: node, capturedNode: ExprSyntax(referenceNode), sourceLocationConverter: sourceLocationConverter)
}
} else {
fatalError("Can't reference `self`")
}
}
return
}
if case let .closureNode(closureNode) = currentScope.scopeNode {
isEscape = graph.isClosureEscape(closureNode, nonEscapeRules: nonEscapeRules)
}
currentScope = currentScope.parent
}
if isEscape {
leak = Leak(node: node, capturedNode: nil, sourceLocationConverter: sourceLocationConverter)
return
}
}
}
<file_sep>/Sources/SwiftLeakCheck/TypeResolve.swift
//
// TypeResolve.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 03/01/2020.
//
import SwiftSyntax
public indirect enum TypeResolve: Equatable {
case optional(base: TypeResolve)
case sequence(elementType: TypeResolve)
case dict
case tuple([TypeResolve])
case name([String])
case type(TypeDecl)
case unknown
public var isOptional: Bool {
return self != self.wrappedType
}
public var wrappedType: TypeResolve {
switch self {
case .optional(let base):
return base.wrappedType
case .sequence,
.dict,
.tuple,
.name,
.type,
.unknown:
return self
}
}
public var name: [String]? {
switch self {
case .optional(let base):
return base.name
case .name(let tokens):
return tokens
case .type(let typeDecl):
return typeDecl.name
case .sequence,
.dict,
.tuple,
.unknown:
return nil
}
}
public var sequenceElementType: TypeResolve {
switch self {
case .optional(let base):
return base.sequenceElementType
case .sequence(let elementType):
return elementType
case .dict,
.tuple,
.name,
.type,
.unknown:
return .unknown
}
}
}
internal extension TypeResolve {
var isInt: Bool {
return name == ["Int"]
}
}
<file_sep>/Sources/SwiftLeakCheck/Function.swift
//
// Function.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 18/11/2019.
//
import SwiftSyntax
public typealias Function = FunctionDeclSyntax
public extension Function {
enum MatchResult: Equatable {
public struct MappingInfo: Equatable {
let argumentToParamMapping: [FunctionCallArgumentSyntax: FunctionParameterSyntax]
let trailingClosureArgumentToParam: FunctionParameterSyntax?
}
case nameMismatch
case argumentMismatch
case matched(MappingInfo)
var isMatched: Bool {
switch self {
case .nameMismatch,
.argumentMismatch:
return false
case .matched:
return true
}
}
}
func match(_ functionCallExpr: FunctionCallExprSyntax) -> MatchResult {
let (signature, mapping) = FunctionSignature.from(functionDeclExpr: self)
switch signature.match(functionCallExpr) {
case .nameMismatch:
return .nameMismatch
case .argumentMismatch:
return .argumentMismatch
case .matched(let matchedInfo):
return .matched(.init(
argumentToParamMapping: matchedInfo.argumentToParamMapping.mapValues { mapping[$0]! },
trailingClosureArgumentToParam: matchedInfo.trailingClosureArgumentToParam.flatMap { mapping[$0] }))
}
}
}
<file_sep>/Sources/SwiftLeakCheck/NonEscapeRules/DispatchQueueRule.swift
//
// DispatchQueueRule.swift
// SwiftLeakCheck
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
// Created by <NAME> on 28/10/2019.
//
import SwiftSyntax
open class DispatchQueueRule: BaseNonEscapeRule {
private let signatures: [FunctionSignature] = [
FunctionSignature(name: "async", params: [
FunctionParam(name: "group", canOmit: true),
FunctionParam(name: "qos", canOmit: true),
FunctionParam(name: "flags", canOmit: true),
FunctionParam(name: "execute", isClosure: true)
]),
FunctionSignature(name: "async", params: [
FunctionParam(name: "group", canOmit: true),
FunctionParam(name: "execute")
]),
FunctionSignature(name: "sync", params: [
FunctionParam(name: "flags", canOmit: true),
FunctionParam(name: "execute", isClosure: true)
]),
FunctionSignature(name: "sync", params: [
FunctionParam(name: "execute")
]),
FunctionSignature(name: "asyncAfter", params: [
FunctionParam(name: "deadline"),
FunctionParam(name: "qos", canOmit: true),
FunctionParam(name: "flags", canOmit: true),
FunctionParam(name: "execute", isClosure: true)
]),
FunctionSignature(name: "asyncAfter", params: [
FunctionParam(name: "wallDeadline"),
FunctionParam(name: "qos", canOmit: true),
FunctionParam(name: "flags", canOmit: true),
FunctionParam(name: "execute", isClosure: true)
])
]
private let mainQueuePredicate: ExprSyntaxPredicate = .memberAccess("main", base: .name("DispatchQueue"))
private let globalQueuePredicate: ExprSyntaxPredicate = .funcCall(
signature: FunctionSignature(name: "global", params: [.init(name: "qos", canOmit: true)]),
base: .name("DispatchQueue")
)
open override func isNonEscape(arg: FunctionCallArgumentSyntax?,
funcCallExpr: FunctionCallExprSyntax,
graph: Graph) -> Bool {
for signature in signatures {
for queue in [mainQueuePredicate, globalQueuePredicate] {
let predicate: ExprSyntaxPredicate = .funcCall(signature: signature, base: queue)
if funcCallExpr.match(predicate) {
return true
}
}
}
let isDispatchQueuePredicate: ExprSyntaxPredicate = .init { expr -> Bool in
guard let expr = expr else { return false }
let typeResolve = graph.resolveExprType(expr)
switch typeResolve.wrappedType {
case .name(let name):
return self.isDispatchQueueType(name: name)
case .type(let typeDecl):
let allTypeDecls = graph.getAllRelatedTypeDecls(from: typeDecl)
for typeDecl in allTypeDecls {
if self.isDispatchQueueType(typeDecl: typeDecl) {
return true
}
}
return false
case .dict,
.sequence,
.tuple,
.optional, // Can't happen
.unknown:
return false
}
}
for signature in signatures {
let predicate: ExprSyntaxPredicate = .funcCall(signature: signature, base: isDispatchQueuePredicate)
if funcCallExpr.match(predicate) {
return true
}
}
return false
}
private func isDispatchQueueType(name: [String]) -> Bool {
return name == ["DispatchQueue"]
}
private func isDispatchQueueType(typeDecl: TypeDecl) -> Bool {
if self.isDispatchQueueType(name: typeDecl.name) {
return true
}
for inheritedType in (typeDecl.inheritanceTypes ?? []) {
if self.isDispatchQueueType(name: inheritedType.typeName.name ?? []) {
return true
}
}
return false
}
}
<file_sep>/Package.swift
// swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
//
// Copyright 2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
//
import PackageDescription
let package = Package(
name: "SwiftLeakCheck",
products: [
.library(name: "SwiftLeakCheck", targets: ["SwiftLeakCheck"]),
.executable(name: "SwiftLeakChecker", targets: ["SwiftLeakChecker"])
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
.package(url: "https://github.com/apple/swift-syntax", .exact("0.50300.0")),
// For Swift toolchain 5.2 and above
// .package(name: "SwiftSyntax", url: "https://github.com/apple/swift-syntax", .exact("0.50300.0")),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "SwiftLeakChecker",
dependencies: [
"SwiftLeakCheck"
]
),
.target(
name: "SwiftLeakCheck",
dependencies: [
"SwiftSyntax"
]
),
.testTarget(
name: "SwiftLeakCheckTests",
dependencies: ["SwiftLeakCheck"]
)
]
)
|
a9f6df055048acd24b3aec749e9e381381d1980f
|
[
"Swift",
"Markdown"
] | 31 |
Swift
|
grab/swift-leak-check
|
a65212337318eeb1ff0a4a0262b4133b871592ac
|
f2d7d34a2e21e6fd7ba81f94816b958f7c80b0dc
|
refs/heads/master
|
<file_sep>body{
margin: 0 1% !important;
padding: 10px !important;
}
#header{
width: 100%;
background-color: SkyBlue;
padding: 50px 70px;
}
#header h1{
text-align: center;
font-family: inherit;
font-weight: 500;
line-height: 1.1;
font-size: 63px;
vertical-align: center;
}
#header2{
width: 100%;
background-color: #fefefe;
padding: 50px 70px;
}
#header3{
width: 100%;
background-color: SpringGreen;
padding: 50px 70px;
}
#header4{
font-family: Times New Roman;
text-align: center;
width: 100%;
font-weight: 500;
background-color: SpringGreen;
padding: 50px 70px;
}
#lsize{
font-family: Arial;
font-weight: 500;
line-height: 1.1;
font-size: 30px;
}
#osize{
font-size: 20px;
}<file_sep><%@page import="fr.epita.quiz.datamodel.Questions"%>
<%@page import="fr.epita.quiz.services.GenericORMDao"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<%
List<Questions> questionsList = (List<Questions>)session.getAttribute("questionsList");
session.removeAttribute("questionsList");
%>
<head>
<%
Boolean auth = (Boolean) session.getAttribute("authenticated");
if (auth == null || !auth) {
%>
<meta http-equiv="refresh" content="0; URL=index.html">
<%
}
%>
<link href="resources/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="resources/css/custom-styles.css" />
</head>
<body>
<div class="container">
<div>
<div class="jumbotron">
<div class="container">
<h1 class="text-info" align="center">List of all Questions</h1>
</div>
<div align="left"><a href="<%=request.getContextPath()%>/usersService">List of Users</a></div>
<div align="right">
<a href="selectQuestionType.jsp">Question Type</a>
</div>
<div> <a href="question.jsp">Create New Question</a></div>
<div align="right">
<a href="adminLogin.html">Logout</a>
</div>
</div>
</div>
<div class="container">
<h3 class="text-info">Search Results</h3>
<form class="form-horizontal" method="post" action="modifyQuestion">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Quiz Name</th>
<th>Question</th>
<th>Answer1</th>
<th>Answer2</th>
<th>Answer3</th>
<th>Answer4</th>
<th>Correctanswer</th>
<th>QuestionType</th>
</tr>
</thead>
<tbody>
<%
if (questionsList == null || questionsList.isEmpty()){
%>
<tr>
<td colspan="7">No result</td>
</tr>
<%
} else{
for (Questions id : questionsList){
%>
<tr>
<td><input name="selection" type="radio" value="<%=id.getId()%>"/></td>
<td><%=id.getQuizName() %></td>
<td><%=id.getQuestion() %></td>
<td><%=id.getAnswer1() %></td>
<td><%=id.getAnswer2() %></td>
<td><%=id.getAnswer3() %></td>
<td><%=id.getAnswer4() %></td>
<td><%=id.getCorrectanswer() %></td>
<td><%=id.getType() %></td>
</tr>
<%}
}%>
</tbody>
</table>
</div>
<div class="form-group" align="center">
<div class=" col-sm-offset-2 col-sm-10 text-right">
<button type="submit" style="margin-right: 30px" class="btn btn-primary" value="Modify" name="modify">Modify</button>
<button type="submit" style="margin-right: 30px"class="btn btn-danger" value="Delete" name="delete">Delete</button>
<button type="submit" style="margin-right: 30px"class="btn btn-danger" value="DeleteAll" name="deleteAll">Delete All</button>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
<file_sep>package fr.epita.quiz.web.services.user;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.exception.DataException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import fr.epita.quiz.datamodel.TypeOfRoles;
import fr.epita.quiz.datamodel.Users;
import fr.epita.quiz.services.UsersDAO;
import fr.epita.quiz.web.actions.SpringServlet;
/**
*
* @author Sindhu
*
*/
@Service
@Transactional
@WebServlet(urlPatterns = "/modifyUser")
public class ModifyUser extends SpringServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LogManager.getLogger(ModifyUser.class);
@Autowired
private UsersDAO repository;
public ModifyUser() {
// TODO Auto-generated constructor stub
}
/*
* (non-Javadoc)
*
* @see
* javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (request.getParameter("update") != null) {
final Users user = new Users();
user.setMail(request.getParameter("mail"));
user.setUser_name(request.getParameter("user_name"));
user.setPsswd(request.getParameter("psswd"));
user.setEnable(true);
user.setUserRoleId(Integer.parseInt(request.getParameter("id")));
user.setRole(TypeOfRoles.valueOf(request.getParameter("role")));
try {
repository.create(user);
LOGGER.info("User updated Sucessfully");
response.sendRedirect("usersList.jsp");
} catch (DataException e) {
LOGGER.error(e);
e.printStackTrace();
}
} else if (request.getParameter("delete") != null) {
try {
Users deleteUser = repository.getUsersById(Integer.parseInt(request.getParameter("selection")));
repository.delete(deleteUser);
LOGGER.info("User deleted Sucessfully");
response.sendRedirect("usersList.jsp");
} catch (DataException e) {
LOGGER.error(e);
e.printStackTrace();
}
} else if (request.getParameter("modify") != null) {
try {
Users editUser = repository.getUsersById(Integer.parseInt(request.getParameter("selection")));
request.getSession().setAttribute("Users", editUser);
LOGGER.info("Page RedirectedSucessfully");
response.sendRedirect("updateUser.jsp");
} catch (NumberFormatException e) {
LOGGER.error(e);
e.printStackTrace();
}
}
}
}
<file_sep>package fr.epita.quiz.services;
import fr.epita.quiz.datamodel.Users;
/**
*
* @author Sindhu
*
*/
public class UsersDAO extends GenericORMDao<Users> {
@Override
protected WhereClauseBuilder getWhereClauseBuilder(Users entity) {
return null;
}
}
<file_sep>package fr.epita.quiz.services;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import javax.inject.Inject;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import fr.epita.quiz.datamodel.Questions;
import fr.epita.quiz.datamodel.Users;
/**
*
* @author Sindhu
*
* @param <T>
*/
public abstract class GenericORMDao<T> {
@Inject
SessionFactory sf;
/**
*
* @param entity
*/
public final void create(T entity) {
if (!beforeCreate(entity)) {
return;
}
final Session session = sf.openSession();
final Transaction tx = session.beginTransaction();
session.saveOrUpdate(entity);
tx.commit();
session.close();
}
/**
*
* @param entity
* @return
*/
protected boolean beforeCreate(T entity) {
return entity != null;
}
/**
*
* @param entity
*/
public final void delete(T entity) {
final Session session = sf.openSession();
final Transaction tx = session.beginTransaction();
session.delete(entity);
tx.commit();
session.close();
}
/**
*
* @param entity
*/
public final void deleteAll(List<T> entity) {
final Session session = sf.openSession();
final Transaction tx = session.beginTransaction();
session.delete(entity);
tx.commit();
session.close();
}
/**
*
* @param entity
* @return
*/
@SuppressWarnings("unchecked")
public final List<T> getQuizName(T entity) {
final Session session = sf.openSession();
final WhereClauseBuilder<T> wcb = getWhereClauseBuilder(entity);
final Query getTypeQuery = session.createQuery(wcb.getQueryString()).setProperties(wcb.getParameters());
for (final Entry<String, Object> parameterEntry : wcb.getParameters().entrySet()) {
getTypeQuery.setParameter(parameterEntry.getKey(), parameterEntry.getValue());
}
return getTypeQuery.list();
}
/**
*
* @param entity
* @return
*/
public final List<Questions> getQuestions(Questions entity) {
final Session session = sf.openSession();
String hql = "from Questions s where s.quizName = :quizName";
Query<Questions> query = session.createQuery(hql);
query.setParameter("quizName", entity.getQuizName());
List<Questions> result = query.getResultList();
return result;
}
/**
*
* @param entity
* @return
*/
public Collection<T> searchAll(T entity) {
List<T> list = new ArrayList<>();
final Session session = sf.openSession();
list = (List<T>) session.createQuery("from Questions", Questions.class).list();
return list;
}
/**
*
* @param entity
* @return
*/
public Collection<T> searchUsers(T entity) {
final Session session = sf.openSession();
return (List<T>) session.createQuery("from Users", Users.class).list();
}
/**
*
* @param id
* @return
*/
public Users getUsersById(int id) {
final Session session = sf.openSession();
return session.get(Users.class, id);
}
/**
*
* @param username
* @return
*/
public Users getUsersByUserName(String username) {
final Session session = sf.openSession();
String hql = "from Users s where s.username = :username";
Query<Users> query = session.createQuery(hql);
query.setParameter("username", username);
List<Users> use = query.getResultList();
return use.get(0);
}
/**
*
* @param id
* @return
*/
public Questions getById(int id) {
final Session session = sf.openSession();
return session.get(Questions.class, id);
}
/**
*
* @param entity
* @return
*/
public final List<T> search(T entity) {
final Session session = sf.openSession();
final WhereClauseBuilder<T> wcb = getWhereClauseBuilder(entity);
final Query searchQuery = session.createQuery(wcb.getQueryString());
for (final Entry<String, Object> parameterEntry : wcb.getParameters().entrySet()) {
searchQuery.setParameter(parameterEntry.getKey(), parameterEntry.getValue());
}
return searchQuery.list();
}
/**
*
* @param entity
* @return
*/
protected abstract WhereClauseBuilder getWhereClauseBuilder(T entity);
// Old conception
// protected abstract String getSearchQuery(T entity);
//
// protected abstract void completeQuery(T entity, Query toBeCompleted);
}
<file_sep>package fr.epita.quiz.web.actions;
import java.io.IOException;
import java.util.List;
import javax.inject.Inject;
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 org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.exception.DataException;
import org.springframework.beans.factory.annotation.Autowired;
import fr.epita.quiz.datamodel.TypeOfRoles;
import fr.epita.quiz.datamodel.Users;
import fr.epita.quiz.services.AuthenticationService;
import fr.epita.quiz.services.UsersDAO;
/**
* @author Sindhu
*
* Servlet implementation class Login
*/
@WebServlet(urlPatterns = "/login")
public class Login extends SpringServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LogManager.getLogger(Login.class);
@Inject
AuthenticationService auth;
@Autowired
private UsersDAO repository;
/**
* Default constructor.
*/
public Login() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
/*
* (non-Javadoc)
*
* @see
* javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (request.getParameter("login") != null) {
try {
final String login = request.getParameter("login");
final String password = request.getParameter("password");
List<Users> users = (List<Users>) repository.searchUsers(new Users());
for (Users user : users) {
if (user.getUser_name().equals(login) && user.getPsswd().equals(password)) {
final boolean authenticated = auth.authenticate(login, password);
request.getSession().setAttribute("authenticated", authenticated);
request.getSession().setAttribute("userName", login);
if (user.getRole().name().equals(TypeOfRoles.Admin.name())) {
LOGGER.info("Admin Login Sucessfully");
response.sendRedirect("selectQuestionType.jsp");
} else if (user.getRole().name().equals(TypeOfRoles.User.name())) {
LOGGER.info("User Login Sucessfully");
response.sendRedirect("selectQuiz.jsp");
}
}
}
} catch (Exception e) {
LOGGER.error(e);
LOGGER.info("Incorrect User Name or Password");
e.printStackTrace();
request.getRequestDispatcher("error.jsp").forward(request, response);
}
} else if (request.getParameter("registerAdmin") != null) {
try {
createUsers(request, response, TypeOfRoles.Admin);
LOGGER.info("Admin Registered Sucessfully");
} catch (Exception e) {
LOGGER.error(e);
e.printStackTrace();
}
} else if (request.getParameter("registerUser") != null) {
try {
createUsers(request, response, TypeOfRoles.User);
LOGGER.info("User Registered Sucessfully");
} catch (Exception e) {
LOGGER.error(e);
e.printStackTrace();
}
} else {
LOGGER.error("Login Authentication Failed");
request.getSession().setAttribute("authenticated", false);
request.getRequestDispatcher("error.jsp").forward(request, response);
}
}
/**
*
* @param request
* @param response
* @param roleType
* @throws ServletException
* @throws IOException
*/
private void createUsers(HttpServletRequest request, HttpServletResponse response, TypeOfRoles roleType)
throws ServletException, IOException {
final Users user = prepareUser(request, roleType);
try {
repository.create(user);
LOGGER.info("User Registered Sucessfully");
response.sendRedirect(request.getContextPath() + "/index.html");
} catch (DataException e) {
LOGGER.error(e);
e.printStackTrace();
}
}
/**
* @param request
* @param roleType
* @return
*/
private Users prepareUser(HttpServletRequest request, TypeOfRoles roleType) {
final Users user = new Users();
user.setUser_name(request.getParameter("user_name"));
user.setPsswd(request.getParameter("psswd"));
user.setMail(request.getParameter("mail"));
user.setEnable(true);
user.setRole(roleType);
return user;
}
}
<file_sep>package fr.epita.quiz.web.services;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import fr.epita.quiz.datamodel.Questions;
import fr.epita.quiz.datamodel.TypeOFQuestions;
import fr.epita.quiz.services.CreateQuestionDAO;
import fr.epita.quiz.web.actions.SpringServlet;
/**
*
* @author Sindhu
*
*/
@Service
@Transactional
@WebServlet(urlPatterns = "/questionAction")
public class QuestionAction extends SpringServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LogManager.getLogger(QuestionAction.class);
@Autowired
private CreateQuestionDAO repository;
public QuestionAction() {
// TODO Auto-generated constructor stub
}
/*
* (non-Javadoc)
*
* @see
* javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (request.getParameter("mcq") != null) {
try {
final Questions addQuestion = prepareQuestion(request);
repository.create(addQuestion);
LOGGER.info("Question created Sucessfully");
response.sendRedirect("questionList");
} catch (Exception e) {
LOGGER.error(e);
LOGGER.info("Question creation Failed");
e.printStackTrace();
}
} else if (request.getParameter("open") != null) {
try {
final Questions addQuestion = prepareOpenQuestion(request);
repository.create(addQuestion);
LOGGER.info("Question created Sucessfully");
response.sendRedirect("questionList");
} catch (Exception e) {
LOGGER.error(e);
LOGGER.info("Question creation Failed");
e.printStackTrace();
}
} else if (request.getParameter("assoc") != null) {
LOGGER.info("THIS FUNTIONALITY NOT PROVIDED YET");
}
}
/**
* @param request
* @return
*/
private Questions prepareQuestion(HttpServletRequest request) {
final Questions addQuestion = new Questions();
addQuestion.setQuestion(request.getParameter("question"));
addQuestion.setAnswer1(request.getParameter("answer1"));
addQuestion.setAnswer2(request.getParameter("answer2"));
addQuestion.setAnswer3(request.getParameter("answer3"));
addQuestion.setAnswer4(request.getParameter("answer4"));
String correctAnswer = request.getParameter("correctanswer");
addQuestion.setCorrectanswer(request.getParameter(correctAnswer));
addQuestion.setQuizName(request.getParameter("quizName"));
addQuestion.setType(TypeOFQuestions.MCQ);
return addQuestion;
}
/**
* @param request
* @return
*/
private Questions prepareOpenQuestion(HttpServletRequest request) {
final Questions addQuestion = new Questions();
addQuestion.setQuestion(request.getParameter("question"));
addQuestion.setQuizName(request.getParameter("quizName"));
addQuestion.setAnswer1("N/A");
addQuestion.setAnswer2("N/A");
addQuestion.setAnswer3("N/A");
addQuestion.setAnswer4("N/A");
addQuestion.setType(TypeOFQuestions.OPN);
return addQuestion;
}
}
<file_sep>package fr.epita.quiz.web.actions;
import java.io.IOException;
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 org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import fr.epita.quiz.datamodel.Users;
import fr.epita.quiz.services.UsersDAO;
/**
*
* @author Sindhu
*
*/
@WebServlet(urlPatterns = "/forgotPassword")
public class Password extends SpringServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LogManager.getLogger(Password.class);
@Autowired
private UsersDAO repository;
/**
* Default constructor.
*/
public Password() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
/*
* (non-Javadoc)
*
* @see
* javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (request.getParameter("forgotPassword") != null) {
try {
// users.setUsername(request.getParameter("username"));
// users.setEmail(request.getParameter("email"));
Users user = (Users) repository.getUsersByUserName(request.getParameter("username"));
if (!user.equals(null) && (user.getMail().equals(request.getParameter("email")))) {
request.getSession().setAttribute("user", user);
LOGGER.info("Redirected to change password");
response.sendRedirect("resetPassword.jsp");
} else {
LOGGER.error("Wrong username or Password Entered");
request.getRequestDispatcher("error.jsp").forward(request, response);
}
} catch (Exception e) {
LOGGER.error("Something Went Wrong!!!");
e.printStackTrace();
}
} else if (request.getParameter("resetPassword") != null) {
try {
Users users = new Users();
String newPsswd = request.getParameter("newpassword");
String verifyPassword = request.getParameter("verifypassword");
users = repository.getUsersById(Integer.parseInt(request.getParameter("id")));
if (newPsswd.equals(verifyPassword)) {
users.setPsswd(newPsswd);
repository.create(users);
LOGGER.error("Password Changed Sucessfully!!!");
response.sendRedirect("index.html");
} else {
LOGGER.warn("Password did not match!!!");
request.getRequestDispatcher("resetPassword.jsp").forward(request, response);
}
} catch (NumberFormatException e) {
LOGGER.error("Something Went Wrong!!!");
e.printStackTrace();
}
} else {
LOGGER.error("Forget Password Request Failed");
request.getRequestDispatcher("error.jsp").forward(request, response);
}
}
}
<file_sep>/**
* Ce fichier est la propriété de <NAME>
* Code application :
* Composant :
*/
package fr.epita.quiz.tests;
import javax.inject.Inject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import fr.epita.quiz.datamodel.Questions;
import fr.epita.quiz.datamodel.TypeOFQuestions;
/**
* <h3>Description</h3>
* <p>
* This class allows to ...
* </p>
*
* <h3>Usage</h3>
* <p>
* This class should be used as follows:
*
* <pre>
* <code>${type_name} instance = new ${type_name}();</code>
* </pre>
* </p>
*
* @since $${version}
* @see See also $${link}
* @author ${user}
*
* ${tags}
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext.xml" })
public class TestCase {
private static final Logger LOGGER = LogManager.getLogger(TestCase.class);
@Inject
SessionFactory sf;
@Test
public void testMethod() {
// given
Assert.assertNotNull(sf);
final Questions question = new Questions();
question.setQuestion("How to configure Hibernate?");
question.setType(TypeOFQuestions.MCQ);
final Session session = sf.openSession();
// when
final Transaction tx = session.beginTransaction();
session.saveOrUpdate(question);
tx.commit();
// then
// TODO
}
}
<file_sep><%@page import="fr.epita.quiz.datamodel.Questions"%>
<%@page import="fr.epita.quiz.services.GenericORMDao"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<%
List<String> ques = (List<String>)session.getAttribute("ques");
session.removeAttribute("ques");
%>
<head>
<%
Boolean auth = (Boolean) session.getAttribute("authenticated");
if (auth == null || !auth) {
%>
<meta http-equiv="refresh" content="0; URL=index.html">
<%
}
%>
<link href="resources/bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div>
<div class="jumbotron">
<div class="container">
<h1 class="text-info" align="center">List of all Quiz's Name</h1>
</div>
</div>
</div>
<div class="container">
<h3 class="text-info"> Choose any Quiz</h3>
<form class="form-horizontal" method="post" action="examServices">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Select</th>
<th>Quiz Name</th>
</tr>
</thead>
<tbody>
<%
if (ques == null || ques.isEmpty()){
%>
<tr>
<td colspan="3">No result</td>
</tr>
<%
} else{
for (String quest : ques){
%>
<tr>
<td><input name="selection" type="radio" value="<%=quest.toString()%>"/></td>
<%-- <td> <label for="id" name="id" id="id" value="<%=id.getId() %>"><%=id.getId() %></label></td> --%>
<%-- <td><%=id.getId() %></td>
--%>
<td><%=quest.toString() %></td>
</tr>
<%}
}%>
</tbody>
</table>
</div>
<div class="form-group">
<div class=" col-sm-offset-2 col-sm-10 text-right">
<button type="submit" class="btn btn-primary" value="quizName" name="quizName">Select</button>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
<file_sep>package fr.epita.quiz.services;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import fr.epita.quiz.datamodel.Questions;
/**
*
* @author Sindhu
*
*/
public class QuestionDAO {
@Inject
@Named("questionQuery")
String query;
/**
*
* @param entity
* @return
*/
protected WhereClauseBuilder<Questions> getWhereClauseBuilder(Questions entity) {
final WhereClauseBuilder<Questions> wcb = new WhereClauseBuilder<>();
wcb.setQueryString(query);
final Map<String, Object> parameters = new LinkedHashMap<>();
parameters.put("question", entity.getQuestion());
wcb.setParameters(parameters);
return wcb;
}
// @Override
// protected String getSearchQuery(Question question) {
// return query;
// }
//
// /*
// * (non-Javadoc)
// * @see
// fr.epita.quiz.services.GenericHibernateDao#completeQuery(org.hibernate.query.Query)
// */
// @Override
// protected void completeQuery(Question question, Query toBeCompleted) {
//
// toBeCompleted.setParameter("type", question.getType());
// toBeCompleted.setParameter("question", question.getQuestion());
// }
/*
* (non-Javadoc)
*
* @see
* fr.epita.quiz.services.GenericHibernateDao#getWhereClauseBuilder(java.lang.
* Object)
*/
}
<file_sep>/**
* Ce fichier est la propriété de <NAME>
* Code application :
* Composant :
*/
package fr.epita.quiz.tests;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import fr.epita.quiz.datamodel.Questions;
import fr.epita.quiz.datamodel.TypeOFQuestions;
import fr.epita.quiz.datamodel.TypeOfRoles;
import fr.epita.quiz.datamodel.Users;
import fr.epita.quiz.services.CreateQuestionDAO;
import fr.epita.quiz.services.UsersDAO;
/**
* <h3>Description</h3>
* <p>
* This class allows to ...
* </p>
*
* <h3>Usage</h3>
* <p>
* This class should be used as follows:
*
* <pre>
* <code>${type_name} instance = new ${type_name}();</code>
* </pre>
* </p>
*
* @since $${version}
* @see See also $${link}
* @author ${user}
*
* ${tags}
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext.xml" })
public class TestMCQAndQuestion {
@Inject
CreateQuestionDAO questDAO;
@Inject
UsersDAO userDAO;
@Inject
SessionFactory factory;
// @Test
public void testSaveOrUpdateQuestion() {
final Session session = factory.openSession();
final Transaction tx = session.beginTransaction();
final Questions question = new Questions();
question.setQuestion("How to configure Hibernate?");
question.setType(TypeOFQuestions.MCQ);
question.setCorrectanswer(
"add dependency and create a bean of session factory with data source properties and hibernate poperties injecting to Spring and propertis of java packages need to be scanned by hibenate ");
questDAO.create(question);
questDAO.create(question);
tx.commit();
session.close();
}
// @Test
public void testGetQuizType() {
final Questions question = new Questions();
question.setType(TypeOFQuestions.MCQ);
List<Questions> stri = questDAO.getQuizName(question);
System.out.println(stri.size());
}
@Test
public void testGetByUserName() {
Users user = new Users();
user = userDAO.getUsersByUserName("Sindhu");
System.out.println(user.getUser_name());
}
// @Test
public void testGetQuestionsByQuizType() {
final Questions question = new Questions();
question.setQuizName("test");
List<Questions> stri = questDAO.getQuestions(question);
System.out.println(stri.size());
}
// @Test
public void testGetAllQuestions() {
final Questions question = new Questions();
List<Questions> questions = questDAO.getQuestions(question);
System.out.println(questions.size());
}
// @Test
public void testCreateOrUpdateUser() {
final Session session = factory.openSession();
final Transaction tx = session.beginTransaction();
final Users user = new Users();
user.setUser_name("tetuser");
user.setMail("<EMAIL>");
user.setPsswd("<PASSWORD>");
user.setRole(TypeOfRoles.Admin);
user.setEnable(true);
userDAO.create(user);
tx.commit();
session.close();
}
// @Test
public void testGetAllUsers() {
final Users user = new Users();
List<Users> users = (List<Users>) userDAO.searchUsers(user);
System.out.println(users.size());
}
// @Test
public void testDeleteAllQuestion() {
final List<Questions> question = new ArrayList<Questions>();
questDAO.deleteAll(question);
}
// @Test
public void testDeleteQuestionById() {
final Questions ques = new Questions();
ques.setId(101);
questDAO.delete(ques);
}
}
<file_sep>package fr.epita.quiz.datamodel;
/**
*
* @author Sindhu
*
*/
public enum TypeOfRoles {
Admin, User
}
|
e12742bc942fd4057abfb9391cf442139263b785
|
[
"Java",
"Java Server Pages",
"CSS"
] | 13 |
Java
|
SindhuraVegi/Quiz-Manager
|
5b9e9a7bcbd2535180da082173766db17044a0e7
|
b135b99409480ed994ffa9c5d15e50b2c6a1b6f6
|
refs/heads/master
|
<repo_name>dan-king-93/CV<file_sep>/README.md
# CV
CV is a project for displaying my personal CV as a website
## Installation
Use the package manager [pip](https://pip.pypa.io/en/stable/) to install foobar.
```bash
pip install foobar
```
## Usage
```python
import foobar
foobar.pluralize('word') # returns 'words'
foobar.pluralize('goose') # returns 'geese'
foobar.singularize('phenomena') # returns 'phenomenon'
```
## Note to me
This is just shown above as a good way of making one in the future
## Random Link
[<NAME>](https://www.johnlewis.co.uk)
|
7d8783534a2898fadba5a8a69538b3a285732936
|
[
"Markdown"
] | 1 |
Markdown
|
dan-king-93/CV
|
ef83382f42d8b8533f52d7a1b0e1dc41be212764
|
32092184e50cf940de51c6a56f873eeaf0731c9e
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.