branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>gevinjanitto/PraktikumWebC<file_sep>/FINAL PROJECT/mahasiswa/kelas.php <?php session_start(); error_reporting(0); if(!isset($_SESSION['email'])) { header('location:../index.php'); exit(); }?><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, shrink-to-fit=no, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>MAHASISWA</title> <link href="../css/bootstrap1.min.css" rel="stylesheet"> <link href="../css/simplesidebar.css" rel="stylesheet"> <link href="../css/stylee.css" rel="stylesheet"> <link href="../css/tabell.css" rel="stylesheet"> </head> <body> <div id="wrapper"> <!-- side bar --> <div id="sidebar-wrapper" style="padding-top:50px;"> <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"> <!-- Beranda --> <div class="pinggir"><br> <a href="data.php" style="text-decoration:none; color:white;">DATA DIRI</a><br><br> <a href="mahasiswa.php" style="text-decoration:none; color:white;">DAFTAR MAHASISWA</a><br><br> <a href="dosen.php" style="text-decoration:none; color:white;">DAFTAR DOSEN</a><br><br> <div class="panel panel-default" style="color:black"> <a href="kelas.php" style="text-decoration:none; color:black;">DAFTAR KELAS</a></div><br> <a href="bimbingan.php" style="text-decoration:none; color:white;">DAFTAR BIMBINGAN</a><br><br> <a href="krs.php" style="text-decoration:none; color:white;">KRS</a><br> </div> </div> </div> <!-- content --> </form> <div id="page-content-wrapper"> <!-- title --> <div class="container-fluid"> <div style="margin-top:45px;"></div> </div> <!-- title --> <div class="container-fluid"> <!-- breadcrumb --> <ol class="breadcrumb"> <li><a href="data.php">Mahasiswa</a></li> <li class="active">Daftar Kelas UNUD</li> </ol> <!-- title --> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <p style="font-size:23px;color:#000000;"><b></span> DAFTAR KELAS UNUD</b></p> <hr style="border:1px solid #000000;padding:0;margin:0px 0px 20px 0px;"> </div> </div> <!-- Form --> <div class="panel-body"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <table class="fl-table" width="50%"><thead> <tr><th>NO</th><th>NAMA KELAS</th><th>NAMA DOSEN</th><th>JAM</th><th>KUOTA</th><th>STATUS</th><th>AKSI</th></tr></thead><tbody> <?php $email=$_SESSION['email']; $koneksi = mysqli_connect("localhost","root","","web") or die(mysqli_error()); $sql1 = mysqli_query($koneksi, "SELECT * FROM kelas INNER JOIN dosen ON kelas.id_dsn = dosen.id_dsn"); $row = mysqli_fetch_assoc($sql1); $no=1; foreach ($sql1 as $row){ $id = $row['nama_kelas']; echo "<tr> <td>$no</td> <td>".$row['nama_kelas']."</td> <td>".$row['nama_dsn']."</td> <td>".$row['jam_kelas']."</td> <td>".$row['kuota_kelas']."</td> <td>".$row['status_kelas']."</td> <td><a href='../proses/gabung.php?id=$id'><input style='width:70px; height:25px; font-size: 10px; background-color: #324960;margin-left: 0px;' class='btn btn-md btn-success' value='Gabung' ></a> <a href='../mahasiswa/kelas_lihat.php?id=$id'><input style='width:50px; height:25px; font-size: 10px; background-color: #4fc3a1;' class='btn btn-md btn-success' value='Lihat' ></td></a>"; $no++; } ?> </tbody> </table> </div> </div> </div> <!-- end wrapper --> <!--start navigasi--> <!-- start navigasi --> <nav class="navbar navbar-default navbar-fixed-top" id="navbar-color" style="font-size:13px;"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <div style="margin-left:20px;"><a href="#menu-toggle" id="menu-toggle"><img src="../img/logo.png" widht="200" height="50"><h2 style="color:white;float:right;margin-left:10px;margin-top: 7px;: bold"><b>UNIVERSITAS UDAYANA</b></h2></a></div> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav navbar-right"> <li ><a href="#" id="navbar-color"><span id="clock"></span> </a></li> <li class="dropdown"> <?php $sql = mysqli_query($koneksi, "SELECT * FROM user_login WHERE email_user = '$email"); $row = mysqli_fetch_assoc($sql);?> <a class="dropdown-toggle" data-toggle="dropdown" href="#" id="navbar-color"><img src="../img/3.png" width="20" height="20"> Welcome,<?php if($row['id_role']=='1'){echo "Admin";} else if($row['id_role']=='2'){echo "Dosen";} else{echo "Mahasiswa";}?> <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="../nasabah/data.php">Pengaturan</a></li> <li><a href="../proses/logout.php">Keluar</a></li> </ul> </li> </ul> </div> </div> </nav> </div> </div> </div> <!-- Waktu --> <!-- jQuery --> <script src="../js/jquery.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="../js/bootstrap.min.js"></script> <!-- Menu Toggle Script --> <script> $("#menu-toggle").click(function(e) { e.preventDefault(); $("#wrapper").toggleClass("toggled"); }); </script> <script> $("#menu-togglee").click(function(e) { e.preventDefault(); $("#wrapper").toggleClass("toggled"); }); </script> <script type="text/javascript"> function cek() { if (confirm("Apakah Data Telah Sesuai?")) { return true; } else { alert("Perubahan Dibatalkan !"); return false; } } </script> </body> </html><file_sep>/FINAL PROJECT/web.sql -- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: May 29, 2020 at 01:38 PM -- Server version: 10.1.19-MariaDB -- PHP Version: 7.0.13 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `web` -- -- -------------------------------------------------------- -- -- Table structure for table `admin` -- CREATE TABLE `admin` ( `id_admin` int(2) NOT NULL, `nama_admin` varchar(50) NOT NULL, `jk_admin` varchar(40) NOT NULL, `telp_admin` varchar(15) NOT NULL, `email_admin` varchar(40) NOT NULL, `foto_admin` varchar(40) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Triggers `admin` -- DELIMITER $$ CREATE TRIGGER `hapus_admin` AFTER DELETE ON `admin` FOR EACH ROW BEGIN DELETE FROM berita WHERE id_admin = old.id_admin; DELETE FROM foto WHERE id_admin = old.id_admin; END $$ DELIMITER ; -- -------------------------------------------------------- -- -- Table structure for table `bimbingan` -- CREATE TABLE `bimbingan` ( `id_bimbingan` int(11) NOT NULL, `id_dsn` int(11) NOT NULL, `id_mhs` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `bimbingan` -- INSERT INTO `bimbingan` (`id_bimbingan`, `id_dsn`, `id_mhs`) VALUES (3, 1, 28), (4, 2, 28); -- -------------------------------------------------------- -- -- Table structure for table `dosen` -- CREATE TABLE `dosen` ( `id_dsn` int(8) NOT NULL, `nidn_dsn` varchar(10) NOT NULL, `nama_dsn` varchar(50) NOT NULL, `email_dsn` varchar(40) NOT NULL, `telp_dsn` varchar(15) NOT NULL, `alamat_dsn` varchar(50) NOT NULL, `kabkot_dsn` varchar(30) NOT NULL, `jk_dsn` varchar(20) NOT NULL, `tgllahir_dsn` date NOT NULL, `tmplahir_dsn` varchar(30) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `dosen` -- INSERT INTO `dosen` (`id_dsn`, `nidn_dsn`, `nama_dsn`, `email_dsn`, `telp_dsn`, `alamat_dsn`, `kabkot_dsn`, `jk_dsn`, `tgllahir_dsn`, `tmplahir_dsn`) VALUES (1, '51156515', '<NAME>', '<EMAIL>', '089656626292', 'jl salawati 2', 'Denpasar', 'Laki - laki', '2020-05-13', 'Denpasar'), (2, '1551', '<NAME>', '<EMAIL>', '089656626292', 'jl salawati 2', 'Denpasar', 'Laki - laki', '2020-05-13', 'Denpasar'); -- -------------------------------------------------------- -- -- Table structure for table `gabung` -- CREATE TABLE `gabung` ( `id_join` int(11) NOT NULL, `id_mhs` int(11) NOT NULL, `id_kelas` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `gabung` -- INSERT INTO `gabung` (`id_join`, `id_mhs`, `id_kelas`) VALUES (1, 28, 1), (18, 28, 1), (19, 1, 9), (20, 28, 9), (21, 0, 0), (22, 0, 0), (23, 0, 0), (24, 0, 0), (25, 0, 0), (26, 0, 0), (27, 0, 0), (28, 0, 0), (29, 0, 1), (30, 0, 9), (31, 0, 1), (32, 0, 1), (33, 0, 1), (34, 28, 1); -- -------------------------------------------------------- -- -- Table structure for table `kelas` -- CREATE TABLE `kelas` ( `id_kelas` int(11) NOT NULL, `nama_kelas` varchar(100) NOT NULL, `jam_kelas` varchar(20) NOT NULL, `kuota_kelas` int(11) NOT NULL, `id_dsn` int(11) NOT NULL, `status_kelas` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `kelas` -- INSERT INTO `kelas` (`id_kelas`, `nama_kelas`, `jam_kelas`, `kuota_kelas`, `id_dsn`, `status_kelas`) VALUES (1, 'Algoritma Pemrograman B', '12.00 - 14.50', 25, 2, 'aktif'), (9, 'Pengolahan Data Digital A', '13.00 - 14.00', 21, 2, 'aktif'); -- -------------------------------------------------------- -- -- Table structure for table `krs` -- CREATE TABLE `krs` ( `id_krs` int(11) NOT NULL, `semester` varchar(25) NOT NULL, `id_mhs` int(11) NOT NULL, `id_mk` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `krs` -- INSERT INTO `krs` (`id_krs`, `semester`, `id_mhs`, `id_mk`) VALUES (1, 'Ganjil 2020/2021', 28, 1), (2, 'Ganjil 2020/2021', 28, 2); -- -------------------------------------------------------- -- -- Table structure for table `mahasiswa` -- CREATE TABLE `mahasiswa` ( `id_mhs` int(8) NOT NULL, `nim_mhs` varchar(10) NOT NULL, `nama_mhs` varchar(50) NOT NULL, `email_mhs` varchar(40) NOT NULL, `telp_mhs` varchar(15) NOT NULL, `alamat_mhs` varchar(50) NOT NULL, `kabkot_mhs` varchar(30) NOT NULL, `jk_mhs` varchar(20) NOT NULL, `tgllahir_mhs` date NOT NULL, `tmplahir_mhs` varchar(30) NOT NULL, `fakultas_mhs` varchar(100) NOT NULL, `prodi_mhs` varchar(50) NOT NULL, `status_mhs` varchar(60) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `mahasiswa` -- INSERT INTO `mahasiswa` (`id_mhs`, `nim_mhs`, `nama_mhs`, `email_mhs`, `telp_mhs`, `alamat_mhs`, `kabkot_mhs`, `jk_mhs`, `tgllahir_mhs`, `tmplahir_mhs`, `fakultas_mhs`, `prodi_mhs`, `status_mhs`) VALUES (28, '1708561084', '<NAME>', '<EMAIL>', '089686380483', 'jl kusuma dewa no 7', 'Denpasar', 'Laki-laki', '2020-05-08', 'Bandung', 'FAKULTAS MATEMATIKA DAN ILMU PENGETAHUAN ALAM', 'INFORMATIKA', ''); -- -------------------------------------------------------- -- -- Table structure for table `matakuliah` -- CREATE TABLE `matakuliah` ( `id_mk` int(11) NOT NULL, `kode_mk` char(6) NOT NULL, `nama_mk` varchar(100) NOT NULL, `sks` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `matakuliah` -- INSERT INTO `matakuliah` (`id_mk`, `kode_mk`, `nama_mk`, `sks`) VALUES (1, 'IF1234', 'Pengolahan Data Digital', 3), (2, 'IF1235', 'Algoritma Pemrograman', 3); -- -------------------------------------------------------- -- -- Table structure for table `user_login` -- CREATE TABLE `user_login` ( `email_user` varchar(40) NOT NULL, `password_user` varchar(25) NOT NULL, `id_role` int(11) NOT NULL, `waktu_daftar` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `user_login` -- INSERT INTO `user_login` (`email_user`, `password_user`, `id_role`, `waktu_daftar`) VALUES ('admin', 'admin', 1, '2020-05-28'), ('<EMAIL>', 'ajik345', 2, '2020-05-03'), ('<EMAIL>', 'gevin345', 3, '2020-05-28'); -- -- Triggers `user_login` -- DELIMITER $$ CREATE TRIGGER `tambah_user` BEFORE INSERT ON `user_login` FOR EACH ROW BEGIN IF (new.id_role = '1') THEN INSERT INTO admin(email_admin) VALUES(new.email_user); ELSEIF (new.id_role = '2') THEN INSERT INTO dosen(email_dsn) VALUES(new.email_user); ELSE INSERT INTO mahasiswa(email_mhs) VALUES(new.email_user); END IF; END $$ DELIMITER ; -- -- Indexes for dumped tables -- -- -- Indexes for table `admin` -- ALTER TABLE `admin` ADD PRIMARY KEY (`id_admin`); -- -- Indexes for table `bimbingan` -- ALTER TABLE `bimbingan` ADD PRIMARY KEY (`id_bimbingan`), ADD KEY `id_dosen` (`id_dsn`), ADD KEY `id_mahasiswa` (`id_mhs`); -- -- Indexes for table `dosen` -- ALTER TABLE `dosen` ADD PRIMARY KEY (`id_dsn`); -- -- Indexes for table `gabung` -- ALTER TABLE `gabung` ADD PRIMARY KEY (`id_join`), ADD KEY `id_mahasiswa` (`id_mhs`), ADD KEY `id_kelas` (`id_kelas`); -- -- Indexes for table `kelas` -- ALTER TABLE `kelas` ADD PRIMARY KEY (`id_kelas`), ADD KEY `id_dosen` (`id_dsn`); -- -- Indexes for table `krs` -- ALTER TABLE `krs` ADD PRIMARY KEY (`id_krs`), ADD KEY `id_mk` (`id_mk`), ADD KEY `id_mahasiswa` (`id_mhs`); -- -- Indexes for table `mahasiswa` -- ALTER TABLE `mahasiswa` ADD PRIMARY KEY (`id_mhs`); -- -- Indexes for table `matakuliah` -- ALTER TABLE `matakuliah` ADD PRIMARY KEY (`id_mk`); -- -- Indexes for table `user_login` -- ALTER TABLE `user_login` ADD PRIMARY KEY (`email_user`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `admin` -- ALTER TABLE `admin` MODIFY `id_admin` int(2) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `bimbingan` -- ALTER TABLE `bimbingan` MODIFY `id_bimbingan` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `dosen` -- ALTER TABLE `dosen` MODIFY `id_dsn` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `gabung` -- ALTER TABLE `gabung` MODIFY `id_join` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=35; -- -- AUTO_INCREMENT for table `kelas` -- ALTER TABLE `kelas` MODIFY `id_kelas` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10; -- -- AUTO_INCREMENT for table `krs` -- ALTER TABLE `krs` MODIFY `id_krs` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `mahasiswa` -- ALTER TABLE `mahasiswa` MODIFY `id_mhs` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=29; -- -- AUTO_INCREMENT for table `matakuliah` -- ALTER TABLE `matakuliah` MODIFY `id_mk` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/Tugas 11 FILTER SORTING/simakk.sql -- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: May 06, 2020 at 03:56 PM -- Server version: 10.1.19-MariaDB -- PHP Version: 7.0.13 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `simakk` -- -- -------------------------------------------------------- -- -- Table structure for table `mahasiswa` -- CREATE TABLE `mahasiswa` ( `nim` varchar(10) NOT NULL, `namalengkap` varchar(50) DEFAULT NULL, `kelamin` enum('Laki-laki','Perempuan','','') DEFAULT NULL, `tempat` varchar(30) DEFAULT NULL, `tanggal` date DEFAULT NULL, `alamat` varchar(100) DEFAULT NULL, `agama` enum('Islam','Protestan','Katolik','Hindu','Buddha','Kong Hu Cu') DEFAULT NULL, `telp` varchar(15) DEFAULT NULL, `fakultas` enum('FEB','FK','FH','FT','FP','FEB','FAPET','FMIPA','FTP','FISIP') DEFAULT NULL, `prodi` varchar(50) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `mahasiswa` -- INSERT INTO `mahasiswa` (`nim`, `namalengkap`, `kelamin`, `tempat`, `tanggal`, `alamat`, `agama`, `telp`, `fakultas`, `prodi`) VALUES ('1706521082', 'Java', 'Perempuan', 'Karangasem', '1999-03-22', 'jl apae kaden', 'Buddha', '087675453265', 'FEB', 'ekonomi'), ('170756262', '<NAME>', 'Perempuan', 'Denpasar', '1999-12-13', 'Denpasar', 'Katolik', '089767564545', 'FT', 'Sipil'), ('1708441055', 'IIK mamak Tuwe', 'Perempuan', 'Karangasem', '1999-12-31', '<NAME>', 'Protestan', '0861612616', 'FISIP', 'HI'), ('1708531085', '<NAME>', 'Perempuan', 'Karangasem', '1999-11-01', '<NAME>', 'Hindu', '0817666264', 'FK', 'dokter'), ('1708561063', '<NAME>', 'Laki-laki', 'Denpasar', '1998-04-08', 'jl padang sambian', 'Hindu', '0894996162', 'FMIPA', 'Informatika'), ('1708561065', '<NAME>', 'Laki-laki', 'Denpasar', '1999-12-15', 'jl p salawati', 'Hindu', '08161616969', 'FMIPA', 'Informatika'), ('1708561074', '<NAME>', 'Perempuan', 'Denpasar', '1999-12-13', 'jl bypass n0 98', '<NAME>', '089765345265', 'FP', 'pertanian'), ('1708561075', '<NAME>', 'Laki-laki', 'Karangasem', '1999-12-31', '<NAME>', 'Hindu', '081453278666', 'FMIPA', 'Informatika'), ('1708561077', 'I Made Satya Vyasa', 'Laki-laki', 'Denpasar', '1999-08-09', '<NAME>', 'Hindu', '087777777777', 'FMIPA', 'Informatika'), ('1708561084', '<NAME>', 'Laki-laki', 'Bandung', '1999-04-25', 'jl kusuma dewa no 7', 'Protestan', '089686380483', 'FMIPA', 'Informatika'); -- -- Indexes for dumped tables -- -- -- Indexes for table `mahasiswa` -- ALTER TABLE `mahasiswa` ADD PRIMARY KEY (`nim`); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/FINAL PROJECT/index.php <!DOCTYPE html> <html lang="zxx" class="no-js"> <head> <!-- Mobile Specific Meta --> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Favicon--> <link rel="shortcut icon" href="img/fav.png"> <!-- Author Meta --> <meta name="author" content="CodePixar"> <!-- Meta Description --> <meta name="description" content=""> <!-- Meta Keyword --> <meta name="keywords" content=""> <!-- meta character set --> <meta charset="UTF-8"> <!-- Site Title --> <title>WEB SISTEM INFORMASI UNUD</title> <link href="https://fonts.googleapis.com/css?family=Poppins:300,500,600" rel="stylesheet"> <!-- CSS ============================================= --> <link rel="stylesheet" href="css/linearicons.css"> <link rel="stylesheet" href="css/owl.carousel.css"> <link rel="stylesheet" href="css/font-awesome.min.css"> <link rel="stylesheet" href="css/nice-select.css"> <link rel="stylesheet" href="css/magnific-popup.css"> <link rel="stylesheet" href="css/bootstrap.css"> <link rel="stylesheet" href="css/main.css"> </head> <body> <div class="main-wrapper-first"> <header> <div class="container"> <div class="header-wrap"> <div class="header-top d-flex justify-content-between align-items-center"> <div class="logo"> <a href="index.html"><img src="img/logo.png" alt=""></a> </div> <div class="main-menubar d-flex align-items-center"> <nav class="hide"> <a href="#">Home</a> <a href="#visi">Visi</a> <a href="#galery">Galery</a> <a href="#sejarah">Sejarah</a> <a href="#login">Login</a> <a href="#about">About</a> </nav> <div class="menu-bar"><span class="lnr lnr-menu"></span></div> </div> </div> </div> </div> </header> <div class="banner-area"> <div class="container"> <div class="row justify-content-center height align-items-center"> <div class="col-lg-8"> <div class="banner-content text-center"> <span class="text-white top text-uppercase">SISTEM INFORMASI</span> <h1 class="text-white text-uppercase">UNIVERSITAS UDAYANA</h1> <a href="#login" class="primary-btn d-inline-flex align-items-center"><span class="mr-10">LOGIN</span><span class="lnr lnr-arrow-right"></span></a> </div> </div> </div> </div> </div> <!-- Start home --> <section id="visi" class="featured-area"> <div class="container"> <div class="row"> <div class="col-md-4"> <div class="single-feature d-flex flex-wrap justify-content-between"> <div class="icon d-flex align-items-center justify-content-center"> <span class="lnr lnr-eye"></span> </div> <div class="desc"> <h6 class="title text-uppercase">Visi</h6> <p>Terwujudnya perguruan tinggi yang unggul, mandiri, dan berbudaya.</p> </div> </div> </div> <div class="col-md-4"> <div class="single-feature d-flex flex-wrap justify-content-between"> <div class="icon d-flex align-items-center justify-content-center"> <span class="lnr lnr-rocket"></span> </div> <div class="desc"> <h6 class="title text-uppercase">Misi</h6> <p>Menghasilkan karya inovatif dan prospektif bagi kemajuan Unud serta perekonomian nasional </p> </div> </div> </div> <div class="col-md-4"> <div class="single-feature d-flex flex-wrap justify-content-between"> <div class="icon d-flex align-items-center justify-content-center"> <span class="lnr lnr-diamond"></span> </div> <div class="desc"> <h6 class="title text-uppercase">Tujuan</h6> <p>Menghasilkan lulusan bermutu yang memiliki kompetensi tinggi dalam penguasaan ilmu pengetahuan, teknologi, dan seni</p> </div> </div> </div> </div> </div> </section> <!-- End home --> <!-- Start galeri --> </div> <div class="main-wrapper"> <section id="galery" class="amazing-works-area"> <div class="row justify-content-center"> <div class="col-lg-8"> <div class="section-title text-center"> <h3>GALERY</h3> <span class="text-uppercase">EVENT DI UNIVERSITAS UDAYANA</span> </div> </div> </div> <div class="active-works-carousel mt-40"> <div class="item"> <div class="thumb" style="background: url(img/w1.jpg);"></div> <div class="caption text-center"> <h6 class="text-uppercase">Student Day 2017</h6> <p>Merupakan acara pengenalan kampus yang diselenggarakan oleh BEM Udayana untuk mahasiswa baru</p> </div> </div> <div class="item"> <div class="thumb" style="background: url(img/w2.jpg);"></div> <div class="caption text-center"> <h6 class="text-uppercase"><NAME> 2019</h6> <p>Merupakan acara taunan dari BEM Udayana untuk memperingati hari Ulang Tahun Universitas Udayana dengan mengadakan perlombaan antar fakultas</p> </div> </div> <div class="item"> <div class="thumb" style="background: url(img/w3.jpg);"></div> <div class="caption text-center"> <h6 class="text-uppercase">Udayana Jazz Festival ke 9</h6> <p>Merupakan acara taunan BEM udayana untuk mengadakan konser musik yang mengundang artis ternama, pada taun itu ada Raisa dan Isyana</p> </div> </div> <div class="item"> <div class="thumb" style="background: url(img/w4.jpg);"></div> <div class="caption text-center"> <h6 class="text-uppercase">PMU ke 7</h6> <p>Merupakan acara taunan BEM udayana untuk melatih kepemimpinan mahasiswa baru yang nantinya diharapkan untuk meneruskan BEM</p> </div> </div> <div class="item"> <div class="thumb" style="background: url(img/w5.jpg);"></div> <div class="caption text-center"> <h6 class="text-uppercase">INVENTION 2018</h6> <p>Merupakan perlombaan IT antar SMA dan Universitas tingkat Nasional yang diselenggarakan oleh Prodi Informatika</p> </div> </div> <div class="item"> <div class="thumb" style="background: url(img/w6.jpg);"></div> <div class="caption text-center"> <h6 class="text-uppercase">Udayana Jazz Vestival ke 8</h6> <p>Merupakan acara taunan BEM udayana untuk mengadakan konser musik yang mengundang artis ternama, pada taun itu ada HIVI dan <NAME></p> </div> </div> </div> </section> </div> <div class="main-wrapper"> <!-- End galery --> <!-- Start Sejarah --> <section id="sejarah" class="story-area"> <div class="container"> <div class="row align-items-center"> <div class="col-lg-3"> <div class="story-title"> <h3 class="text-white">Sejarah</h3> <span class="text-uppercase text-white">Universitas Udayana</span> </div> </div> <div class="col-lg-6"> <div class="story-box"> <h6 class="text-uppercase">Sejarah universitas Udayana</h6> <p>Cikal bakal Unud adalah Fakultas Sastra Udayana cabang Universitas Airlangga yang diresmikan oleh P. J. M. Presiden Republik Indonesia Ir. Soekarno, dibuka oleh J. M. Menteri P.P dan K. Prof. DR. Priyono pada tanggal 29 September 1958 sebagaimana tertulis pada Prasasti di Fakultas Sastra Jalan Nias Denpasar. </p> <a href="#" class="primary-btn hover d-inline-flex align-items-center"><span class="lnr lnr-history">&nbsp&nbsp&nbsp&nbsp</span><span class="mr-10">29 September 1958</span></span></a> </div> </div> </div> </div> </section> <!-- End sejarah --> <!-- Start login --> <section id="login" class="subscription-area"> <div class="container"> <div class="row justify-content-center"> <div class="col-lg-8"> <div class="section-title text-center"> <h3>Login</h3> <span class="text-uppercase">Silahkan masukan email dan password anda</span> </div> </div> </div> <div class="row justify-content-center"> <div class="col-lg-6"> <?php error_reporting(0); $koneksi = mysqli_connect("localhost","root","","web") or die(mysqli_error()); if(isset($_POST['log'])){ $email = $_POST['email']; $pass = $_POST['pass']; if($email == NULL || $pass == NULL){ echo"<script>alert('Anda belum mengisi form!');document.location.href='index.php'</script>"; } $sql = "SELECT * FROM user_login WHERE email_user='$email' AND password_user='$pass'"; $result = mysqli_query($koneksi,$sql); if(mysqli_num_rows($result)>0){ while($row = mysqli_fetch_assoc($result)){ session_start(); $_SESSION['email'] = $row['email_user']; if($row['id_role'] == '1'){ echo '<script language="javascript">alert("Anda berhasil LOGIN sebagai Admin!");document.location="admin/data.php";</script>';} else if($row['id_role'] == '2'){ echo '<script language="javascript">alert("Anda berhasil LOGIN sebagai Dosen!");document.location="dosen/data.php";</script>'; } else { echo '<script language="javascript">alert("Anda berhasil LOGIN sebagai Mahasiswa!");document.location="mahasiswa/data.php";</script>'; } } }else{ echo"<script>alert('Username atau password salah!');document.location.href='index.php'</script>"; } } ?> <form action="" method="post" class="subscription relative"> <input type="text" name="email" placeholder="E-mail" required> <input type="password" name="pass" placeholder="<PASSWORD>" required> <button class="primary-btn hover d-inline-flex align-items-center" name="log"><span class="mr-10">Login</span><span class="lnr lnr-arrow-right"></span></button> </form> <br><a class="nav-link" data-toggle="modal" data-target="#daftar" style="cursor: pointer;">Daftar Mahasiswa?</a> </div> </div> </div> </section> <!-- End login --> <!-- Start tentang --> <section id="about" class="footer-widget-area"> <div class="container"> <div class="row"> <div class="col-md-4"> <div class="single-widget d-flex flex-wrap justify-content-between"> <div class="icon d-flex align-items-center justify-content-center"> <span class="lnr lnr-pushpin"></span> </div> <div class="desc"> <h6 class="title text-uppercase">Address</h6> <p>Jl. Raya Kampus UNUD, <NAME>, Kuta Selatan, Badung-Bali-80361</p> </div> </div> </div> <div class="col-md-4"> <div class="single-widget d-flex flex-wrap justify-content-between"> <div class="icon d-flex align-items-center justify-content-center"> <span class="lnr lnr-earth"></span> </div> <div class="desc"> <h6 class="title text-uppercase">Email Address</h6> <div class="contact"> <a href="mailto:<EMAIL>"><EMAIL></a> <br> <a href="mailto:<EMAIL>"><EMAIL></a> </div> </div> </div> </div> <div class="col-md-4"> <div class="single-widget d-flex flex-wrap justify-content-between"> <div class="icon d-flex align-items-center justify-content-center"> <span class="lnr lnr-phone"></span> </div> <div class="desc"> <h6 class="title text-uppercase">Phone Number</h6> <div class="contact"> <a href="tel:+62 (361) 701812">+62 (361) 701812</a> </div> </div> </div> </div> </div> </div> </section> <!-- End tentang --> <!-- Start footer --> <footer> <div class="container"> <div class="footer-content d-flex justify-content-between align-items-center flex-wrap"> <div class="logo"> <img style="width:50px;"src="img/logo.png" alt=""> </div> <div class="copy-right-text">Copyright &copy; 2017 | All rights reserved to Udayana University </div> <div class="footer-social"> <a href="https://web.facebook.com/?_rdc=1&_rdr" target="_blank"><i class="fa fa-facebook"></i></a> <a href="https://twitter.com/" target="_blank"><i class="fa fa-twitter"></i></a> <a href="https://www.unud.ac.id/ target="_blank"><i class="fa fa-dribbble"></i></a> </div> </div> </div> </footer> <!-- End footer--> </div> <script src="js/vendor/jquery-2.2.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="js/vendor/bootstrap.min.js"></script> <script src="js/jquery.ajaxchimp.min.js"></script> <script src="js/owl.carousel.min.js"></script> <script src="js/jquery.nice-select.min.js"></script> <script src="js/jquery.magnific-popup.min.js"></script> <script src="js/main.js"></script> </body> </html> <div class="modal fade" id="daftar" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Form Pendaftaran</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <?php $koneksi = mysqli_connect("localhost","root","","web") or die(mysqli_error()); if (isset($_POST['btn_simpan'])){ $nim = $_POST['nim']; $email = $_POST['email']; $nama = $_POST['nama']; $pass = $_POST['pass']; $pass1 = $_POST['pass1']; $fak = "FAKULTAS MATEMATIKA DAN ILMU PENGETAHUAN ALAM"; $prod = "INFORMATIKA"; $id = "3"; $tanggal = date('y-m-d'); $sql1 = "INSERT INTO user_login (email_user, password_user, id_role, waktu_daftar) VALUES ('$email', '$pass', '$id', '$tanggal')"; $simpan1 = mysqli_query($koneksi, $sql1); $sql = "UPDATE mahasiswa SET nim_mhs = '$nim', nama_mhs = '$nama', fakultas_mhs = '$fak', prodi_mhs = '$prod' WHERE email_mhs = '$email'"; $simpan = mysqli_query($koneksi, $sql); if($simpan && $simpan1){ echo '<script language="javascript">alert("INPUT BERHASIL");document.location="index.php";</script>'; } else{ echo '<script language="javascript">alert("INPUT GAGAL");</script>'; }} ?> <form name="daftar" onsubmit="return checkform()" method="post" action=""> <div class="mt-10"> <label >NIM</label> <input type="text" name="nim" class="single-input-primary" placeholder="Masukan NIM Anda" required> </div> <div class="mt-10"> <label>Email</label> <input type="text" id="email" name="email" class="single-input-primary" placeholder="Masukan e-mail" required> </div> <div class="mt-10"> <label >Nama Lengkap</label> <input type="text" name="nama" class="single-input-primary" placeholder="Masukan Nama Lengkap" required> </div> <div class="mt-10"> <label >Password</label> <input type="password" name="pass" id="<PASSWORD>" class="single-input-primary" placeholder="Masukan Password" required> </div> <div class="mt-10"> <label >Confirm Password</label> <input type="password" name="pass1" id="<PASSWORD>" class="single-input-primary" placeholder="Masukan Kembali Password" required> </div> <div class="mt-10"> <label> <input type="checkbox" required> I accept the Terms of Use & Privacy Policy. <span class="checkmark"></span> </label> </div><br><br> <div class="modal-footer"> <button type="reset" class="genric-btn info radius">Reset</button> <button type="submit" class="genric-btn success radius" name="btn_simpan"><span class="mr-10">Daftar</span></button> </div> </div> </div> </div> </form> <script type="text/javascript"> function checkform() { var pas1 = document.getElementById("cekpas1").value; var pas2 = document.getElementById("cekpas2").value; if(pas1.length < '6') { alert("Password Input Minimal Berjumlah 6 !"); return false; } else{ if(pas1==pas2) { return true; } else{ alert("Password Input Tidak Sama !"); return false; } } } </script><file_sep>/Tugas 10 PAGINASI/simak.sql -- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: May 03, 2020 at 11:07 AM -- Server version: 10.1.19-MariaDB -- PHP Version: 7.0.13 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `simak` -- -- -------------------------------------------------------- -- -- Table structure for table `mahasiswa` -- CREATE TABLE `mahasiswa` ( `id` int(11) NOT NULL, `namalengkap` varchar(50) NOT NULL, `namauser` varchar(30) NOT NULL, `nim` int(10) NOT NULL, `kelamin` varchar(30) NOT NULL, `tempat` varchar(30) NOT NULL, `tanggal` date NOT NULL, `asal` varchar(30) NOT NULL, `jurusan` varchar(30) NOT NULL, `pass` varchar(20) NOT NULL, `jam` time NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `mahasiswa` -- INSERT INTO `mahasiswa` (`id`, `namalengkap`, `namauser`, `nim`, `kelamin`, `tempat`, `tanggal`, `asal`, `jurusan`, `pass`, `jam`) VALUES (1588470657, '<NAME>', 'gevinjanitto49', 1708561084, 'Laki-Laki', 'Bandung', '1999-04-25', 'SMAK <NAME>', 'Teknik Informatika', 'GEVIN345', '05:38:57'), (1588470662, '<NAME>', 'acekgemuy', 1708561075, 'Laki-Laki', 'Karangasem', '2020-05-12', 'SMAK 1 karangasem', 'Teknik Informatika', 'acekgemuy123', '08:33:53'), (1588470664, '<NAME>', 'ajiknoel', 1708561065, 'Laki-Laki', 'Bangli', '2020-05-30', 'SMAK Harapan', 'Teknik Informatika', 'ajik2222', '08:36:47'), (1588488094, 'I made <NAME>', 'tuwe5555', 1708561058, 'Laki-Laki', 'Denpasar', '2020-05-15', 'SMK TI GLOBAL', 'Teknik Informatika', 'tuwetuwe', '08:41:34'), (1588488206, '<NAME>', 'jarwokkun558', 1708561063, 'Laki-Laki', 'Denpasar', '2020-05-11', 'SMA 1 Denpasar', 'Teknik Informatika', 'kunjarwonia', '08:43:26'), (1588488285, 'Vella', 'pulsaooopulsa', 1708531021, 'Perempuan', 'Karangasem', '2020-05-23', 'SMAK 1 karangasem', 'Farmasi', 'aceksumberpulsaku', '08:44:45'), (1588488362, 'silvi', 'silviatuwe', 2147483647, 'Perempuan', 'Badung', '2020-05-06', 'SMAK 1 Denpasar', 'Biologi', 'silsil555', '08:46:02'), (1588488605, '<NAME>', 'bebebacekgemuy', 1708165115, 'Perempuan', 'Karangasem', '2020-05-13', 'SMAK 1 karangasem', 'Biologi', 'acekloveyou', '08:50:05'), (1588488652, 'Java', 'javavanjava5555', 1708536151, 'Perempuan', 'Karangasem', '2020-05-20', 'SMAK 1 karangasem', 'Kimia', 'byeacek', '08:50:52'), (1588488700, 'iik', 'mamaktuwe', 1708561475, 'Perempuan', 'Denpasar', '2020-05-21', 'SMAK 1 Bangli', 'Matematika', 'mamaktuwe', '08:51:40'); -- -- Indexes for dumped tables -- -- -- Indexes for table `mahasiswa` -- ALTER TABLE `mahasiswa` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `mahasiswa` -- ALTER TABLE `mahasiswa` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1588488701; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/FINAL PROJECT/proses/gabung.php <?php session_start(); $koneksi = mysqli_connect("localhost","root","","web") or die(mysqli_error()); $id = $_GET['id']; $email=$_SESSION['email']; $sql = mysqli_query($koneksi, "SELECT * FROM user_login INNER JOIN mahasiswa ON user_login.email_user = mahasiswa.email_mhs WHERE email_user = '$email'"); $row = mysqli_fetch_assoc($sql); $mhs = $row['id_mhs']; $sql1 = mysqli_query($koneksi, "SELECT * FROM kelas WHERE nama_kelas = '$id'"); $row1 = mysqli_fetch_array($sql1); $kelas = $row1['id_kelas']; $sql2 = "INSERT INTO gabung (id_mhs, id_kelas) VALUES ('$mhs', '$kelas')"; $simpan = mysqli_query($koneksi, $sql2); if($simpan){ echo '<script language="javascript">alert("BERHASIL GABUNG KELAS");document.location="../mahasiswa/kelas.php";</script>'; } else{ echo '<script language="javascript">alert("GAGAL GABUNG KELAS");</script>'; } <file_sep>/Tugas 9 CRUD/simak.sql -- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: May 03, 2020 at 05:39 AM -- Server version: 10.1.19-MariaDB -- PHP Version: 7.0.13 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `simak` -- -- -------------------------------------------------------- -- -- Table structure for table `mahasiswa` -- CREATE TABLE `mahasiswa` ( `id` int(11) NOT NULL, `namalengkap` varchar(50) NOT NULL, `namauser` varchar(30) NOT NULL, `nim` int(10) NOT NULL, `kelamin` varchar(30) NOT NULL, `tempat` varchar(30) NOT NULL, `tanggal` date NOT NULL, `asal` varchar(30) NOT NULL, `jurusan` varchar(30) NOT NULL, `pass` varchar(20) NOT NULL, `jam` time NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `mahasiswa` -- INSERT INTO `mahasiswa` (`id`, `namalengkap`, `namauser`, `nim`, `kelamin`, `tempat`, `tanggal`, `asal`, `jurusan`, `pass`, `jam`) VALUES (1588470657, '<NAME>', 'gevinjanitto49', 1708561084, 'Laki-Laki', 'Bandung', '1999-04-25', 'SMAK <NAME>', 'Teknik Informatika', 'GEVIN345', '05:38:57'); -- -- Indexes for dumped tables -- -- -- Indexes for table `mahasiswa` -- ALTER TABLE `mahasiswa` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `mahasiswa` -- ALTER TABLE `mahasiswa` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1588470662; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
7f50560c2227a3dd989ae1e65ee5455dfb508060
[ "SQL", "PHP" ]
7
PHP
gevinjanitto/PraktikumWebC
717ffbc4de722fb50a971fcd5566b5251b8a35a6
6ab1c6e091009ab3c7741cd874a652f9a421e606
refs/heads/master
<repo_name>nacknime-official/telegram-coin-bot<file_sep>/telegram_coin_bot/db/schema.py from gino import Gino db = Gino() class Account(db.Model): __tablename__ = "accounts" id = db.Column(db.Integer(), primary_key=True) phone = db.Column(db.String(), unique=True) password = db.Column(db.String()) class Session(db.Model): __tablename__ = "sessions" id = db.Column(db.Integer(), primary_key=True) phone = db.Column(db.String(), unique=True) session_string = db.Column(db.String()) <file_sep>/telegram_coin_bot/balance.py import time from telethon.sync import TelegramClient from telegram_coin_bot import config, utils accounts = utils.get_all_accounts() total_balance = 0 for x, phone, password, api_id, api_hash in accounts: print(f"Входим в аккаунт: {phone}") client = TelegramClient(f"{config.TELETHON_SESSION_NAME}{x}", api_id, api_hash) client.start() if client.get_messages(config.BOT_ADDRESS).total == 0: client.send_message(config.BOT_ADDRESS, "/start") time.sleep(1) client.send_message(config.BOT_ADDRESS, "/balance") time.sleep(3) text = client.get_messages(config.BOT_ADDRESS, limit=1)[0].message balance = float(text.replace("Available balance: ", "").replace(" LTC", "")) total_balance += balance print(f"Баланс аккаунта № {x} {balance} LTC") print(f"Общий баланс со всех аккаунтов: {total_balance} LTC") <file_sep>/telegram_coin_bot/accounts/manage_accounts.py from telegram_coin_bot.db.schema import Account, Session, db async def add_account(): phone = input("Введите номер телефона: ") password = input("Введите пароль: ") if input("Данные введены верно? [Y/n] ").lower() == "n": return account = await Account.query.where(Account.phone == phone).gino.first() if account: if input("Номер в таблице уже существует. Обновить? [Y/n] ").lower() == "n": return await account.update(password=password).apply() else: await Account.create(phone=phone, password=<PASSWORD>) async def remove_account(): phone = input("Введите номер телефона: ") await Account.delete.where(Account.phone == phone).gino.status() async def list_accounts(): accounts = await db.all(Account.query) accounts = [i.to_dict() for i in accounts] if not accounts: return keys = sorted(accounts[0].keys()) max_lengths = {i: 0 for i in keys} accounts.insert(0, {i: i for i in keys}) for account in accounts: for e in account: max_lengths[e] = max(max_lengths[e], len(str(account[e]))) print(f"|{'|'.join(['-' * i for i in max_lengths.values()])}|") for account in accounts: print(f"|{'|'.join([str(account[e]).center(max_lengths[e]) for e in keys])}|") print(f"|{'|'.join(['-' * i for i in max_lengths.values()])}|") async def exit_program(): await db.pop_bind().close() exit(0) actions = {1: add_account, 2: remove_account, 3: list_accounts, 4: exit_program} async def generate_sessions(): pass async def manage_accounts(): while 1: action = input( f"1) Добавить аккаунт\n" f"2) Удалить аккаунт\n" f"3) Посмотреть аккаунты\n" f"4) Выход\n" ) try: action = int(action) if action not in range(1, 4 + 1): raise ValueError("action not in range 1..4") except ValueError: print("Неверный ввод. Попробуйте ещё раз") continue await actions[action]() <file_sep>/requirements.txt alembic==1.4.2 asyncpg==0.20.1 beautifulsoup4==4.9.1 bs4==0.0.1 certifi==2020.6.20 chardet==3.0.4 gino==1.0.1 h11==0.9.0 h2==3.2.0 hpack==3.0.0 hstspreload==2020.7.17 httpcore==0.9.1 httpx==0.13.3 hyperframe==5.2.0 idna==2.10 lxml==4.5.2 Mako==1.1.3 MarkupSafe==1.1.1 pyaes==1.6.1 pyasn1==0.4.8 python-dateutil==2.8.1 python-editor==1.0.4 rfc3986==1.4.0 rsa==4.6 six==1.15.0 sniffio==1.1.0 soupsieve==2.0.1 SQLAlchemy==1.3.18 Telethon==1.15.0 configargparse <file_sep>/telegram_coin_bot/bot.py import asyncio import enum import logging from collections import namedtuple from httpx import AsyncClient from telethon import TelegramClient, events from telethon.errors import SessionPasswordNeededError from telethon.events.common import EventBuilder from telethon.network import ConnectionTcpAbridged from telethon.sessions import StringSession from telegram_coin_bot import config, utils logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s:%(message)s") class Bot(TelegramClient): handlers = [] def __init__(self, session, api_id, api_hash, phone, proxy=None): super().__init__(session, api_id, api_hash, proxy=proxy) for handler in self.handlers: self.add_event_handler(*handler) self.client = AsyncClient() self._phone = phone[1:] if phone[0] == "+" else phone @property def phone(self): return self._phone[:3] + "*" * 4 + self._phone[-2:] @staticmethod def register_handler(event_handler: EventBuilder): def decorator(callback): Bot.handlers.append((callback, event_handler)) return callback return decorator async def create_bot(session, api_id, api_hash, phone, proxy=None): bot = Bot(StringSession(session), api_id, api_hash, phone, proxy) await bot.start() return bot <file_sep>/telegram_coin_bot/bot_tasks/visit_sites/__main__.py import asyncio from telegram_coin_bot import config from telegram_coin_bot.bot import create_bot from telegram_coin_bot.db.schema import Session, db from telegram_coin_bot.handlers import visit_sites async def _main(): await db.set_bind(config.POSTGRES_URI) sessions = await db.all(Session.query) clients = [ await create_bot( session.session_string, config.TELEGRAM_API_ID, config.TELEGRAM_API_ID, session.phone, ) for session in sessions ] await asyncio.gather( *[client.send_message(config.BOT_ADDRESS, "/menu") for client in clients] ) def main(): loop = asyncio.get_event_loop() loop.create_task(_main()) loop.run_forever() if __name__ == "__main__": main() <file_sep>/telegram_coin_bot/handlers/visit_sites.py import asyncio import logging from bs4 import BeautifulSoup from telethon import events from telethon.tl.functions.messages import GetBotCallbackAnswerRequest from telegram_coin_bot import config from telegram_coin_bot.bot import Bot def is_menu_message(event): message = event.message if ( not message.message.startswith("Welcome to") or "Visit sites to earn by clicking links" not in message.message or "You can also create your own ads with" not in message.message or "Use the /help command for more info." not in message.message ): return False return True def is_visit_site_message(event): message = event.message if ( 'Press the "Visit website" button to earn' not in message.message or "You will be redirected to a third party site." not in message.message ): return False try: url_button = message.reply_markup.rows[0].buttons[0] report_button = message.reply_markup.rows[1].buttons[0] skip_button = message.reply_markup.rows[1].buttons[1] if ( "Go to website" not in url_button.text or "Report" not in report_button.text or "Skip" not in skip_button.text ): return False except: return False return True @Bot.register_handler(events.NewMessage(func=is_menu_message)) async def start_handler(event: events.NewMessage.Event): client = event.client logging.info(f"{client.phone}: Поехали!") await event.respond("/visit") @Bot.register_handler(events.NewMessage(func=is_visit_site_message)) async def start_visiting_site(event: events.NewMessage.Event): client = event.client logging.info(f"{client.phone}: Приступаем к заданию") message = event.message url = message.reply_markup.rows[0].buttons[0].url try: response = await client.client.get(url) except: logging.error( f"{client.phone}: Не получилось выполнить запрос: {url}", exc_info=True ) await skip_task(client, message) return soup = BeautifulSoup(response.content, "lxml") potential_captcha = soup.select_one(".card .card-body .text-center h6") potential_error = soup.select_one(".card .card-body .text-center p") if potential_captcha and potential_captcha.text.startswith("Please solve"): logging.info(f"{client.phone}: Найдена капча. Пропускаем задание") await skip_task(client, message) return if ( potential_error and "Sorry, but the link you used is not valid." == potential_error.text ): logging.info(f"{client.phone}: Невалидная ссылка. Пропуск задания") await skip_task(client, message) return p = soup.select_one("#headbar.container-fluid") if p is not None: wait_time = int(p["data-timer"]) logging.info(f"{client.phone}: Нестандартное задание") await asyncio.sleep(wait_time) await client.client.post( "https://dogeclick.com/reward", data={"code": p["data-code"], "token": p["data-token"]}, ) logging.info(f"{client.phone}: Задание выполнено успешно") @Bot.register_handler( events.NewMessage( func=lambda ev: ev.message.message.startswith("Please stay on the site") or ev.message.message.startswith("You must stay on the site") ) ) async def getting_wait_time(event: events.NewMessage.Event): client = event.client logging.info(f"{client.phone}: {event.message.message}") @Bot.register_handler( events.NewMessage(func=lambda ev: ev.message.message.startswith("You earned")) ) async def getting_reward_info(event: events.NewMessage.Event): client = event.client logging.info(f"{client.phone}: {event.message.message}") @Bot.register_handler( events.NewMessage(func=lambda ev: ev.message.message.startswith("Skipping task...")) ) async def skipping_task(event: events.NewMessage.Event): client = event.client logging.info(f"{client.phone}: Задание пропущено") @Bot.register_handler( events.NewMessage( func=lambda ev: ev.message.message.startswith( "Sorry, there are no new ads available" ) ) ) async def no_new_tasks(event: events.NewMessage.Event): client = event.client logging.info(f"{client.phone}: Заданий больше нет.") await asyncio.sleep(config.DELAY_BETWEEN_GETTING_TASKS) await event.respond("/visit") async def skip_task(bot, message): await bot( GetBotCallbackAnswerRequest( config.BOT_ADDRESS, message.id, data=message.reply_markup.rows[1].buttons[1].data, ) ) <file_sep>/.github/CONTRIBUTING.md # Contributing Приветствуется любая помощь: 1. Нахождение багов 2. Добавление функционала 3. Отправка PR<file_sep>/telegram_coin_bot/config.py import os # Адрес бота, с которым будут общаться аккаунты BOT_ADDRESS = "Litecoin_click_bot" # BOT_ADDRESS = "Dogecoin_click_bot" # BOT_ADDRESS = "BCH_clickbot" # BOT_ADDRESS = "Zcash_click_bot" # BOT_ADDRESS = "BitcoinClick_bot" # Задержка между попытками получить новые задания, если они закончились DELAY_BETWEEN_GETTING_TASKS = 5 * 60 # Адрес кошелька для вывода средств WALLET = "" # Telethon создаёт сессионные файлы. Они будут начинаться с TELETHON_SESSION_NAME # Точка в начале нужна для того, чтобы скрыть этот файл от пользователя. TELETHON_SESSION_NAME = ".anon" # API_ID и API_HASH # Изначально взято отсюда https://bit.ly/3htWcDt TELEGRAM_API_ID = 50322 TELEGRAM_API_HASH = "9ff1a639196c0779c86dd661af8522ba" # Postgres config POSTGRES_HOST = os.getenv("POSTGRES_HOST", default="localhost") POSTGRES_PORT = os.getenv("POSTGRES_PORT", default=5432) POSTGRES_PASSWORD = os.getenv("POSTGRES_PASSWORD", default="") POSTGRES_USER = os.getenv("POSTGRES_USER", default="telegram_coin_bot") POSTGRES_DB = os.getenv("POSTGRES_DB", default="telegram_coin_bot") POSTGRES_URI = f"postgresql://{POSTGRES_USER}:{POSTGRES_PASSWORD}@{POSTGRES_HOST}:{POSTGRES_PORT}/{POSTGRES_DB}" <file_sep>/README.md # Telegram Coin Bot ![Бот для добывания криптовалюты, выполняя задания ботов dogeclick](https://i.imgur.com/dGC2Ay8.png) Бот, который выполняет задания ботов [dogeclick](https://dogeclick.com/), для добычи криптовалюты. Проект находится в очень сыром виде. [Помощь](.github/CONTRIBUTING.md) приветствуется. ## Установка 1. `pip install -r requirements.txt` 2. Зарегистрировать Telegram-аккаунты (см. правила регистрации аккаунтов) 3. Добавить Telegram-аккаунты в базу данных, запустив `create_db.py` 4. Создать клиенты, запустив `create_clients.py` 5. Поменяйте какие-то параметры в `config.py`, если нужно ## Использование 1. Запустите `main.py`, чтобы начать добывать криптоволюту 2. Узнайте баланс на всех аккаунтах, запустив `balance.py` ## Правила регистрации аккаунтов ## Связь 1. [Telegram-канал](https://t.me/joinchat/FCFSlRi-XriZQ6FaJmpgGg)<file_sep>/telegram_coin_bot/utils.py import os import sqlite3 from pathlib import Path from types import SimpleNamespace from typing import Union from alembic.config import Config from configargparse import Namespace PROJECT_PATH = Path(__file__).parent.resolve() def get_all_accounts(filename="accounts.db"): with sqlite3.connect(filename) as conn: cur = conn.cursor() cur.execute("SELECT id, phone, password, api_id, api_hash FROM accounts") accounts = cur.fetchall() cur.close() return accounts def make_alembic_config( cmd_opts: Union[Namespace, SimpleNamespace], base_path: str = PROJECT_PATH ) -> Config: """ Создает объект конфигурации alembic на основе аргументов командной строки, подменяет относительные пути на абсолютные. """ # Подменяем путь до файла alembic.ini на абсолютный if not os.path.isabs(cmd_opts.config): cmd_opts.config = os.path.join(base_path, cmd_opts.config) config = Config(file_=cmd_opts.config, ini_section=cmd_opts.name, cmd_opts=cmd_opts) # Подменяем путь до папки с alembic на абсолютный alembic_location = config.get_main_option("script_location") if not os.path.isabs(alembic_location): config.set_main_option( "script_location", os.path.join(base_path, alembic_location) ) if cmd_opts.pg_url: config.set_main_option("sqlalchemy.url", cmd_opts.pg_url) return config <file_sep>/telegram_coin_bot/accounts/generate_sessions.py from telethon import TelegramClient from telethon.sessions import StringSession from telegram_coin_bot.config import TELEGRAM_API_HASH, TELEGRAM_API_ID from telegram_coin_bot.db.schema import Account, Session, db async def generate_sessions(): accounts = await db.all(Account.query) for account in accounts: print(f"Входим в аккаунт {account.phone}...") client = TelegramClient(StringSession(), TELEGRAM_API_ID, TELEGRAM_API_HASH) await client.start(phone=account.phone, password=account.password) session_string = client.session.save() session = await Session.query.where(Session.phone == account.phone).gino.first() if not session: await Session.create(phone=account.phone, session_string=session_string) else: await session.update(session_string=session_string).apply() await client.disconnect() <file_sep>/telegram_coin_bot/accounts/__main__.py import argparse import asyncio from telethon.sessions import StringSession from telegram_coin_bot.accounts.generate_sessions import generate_sessions from telegram_coin_bot.accounts.manage_accounts import manage_accounts from telegram_coin_bot.config import POSTGRES_URI from telegram_coin_bot.db.schema import db async def _main(): await db.set_bind(POSTGRES_URI) parser = argparse.ArgumentParser(description="Account management tool") parser.add_argument("--generate-sessions", action="store_true") ns = parser.parse_args() if ns.generate_sessions: await generate_sessions() else: await manage_accounts() await db.pop_bind().close() def main(): asyncio.run(_main()) if __name__ == "__main__": main() <file_sep>/telegram_coin_bot/db/__main__.py import argparse import logging import os from alembic.config import CommandLine from telegram_coin_bot.config import POSTGRES_URI from telegram_coin_bot.utils import make_alembic_config def main(): logging.basicConfig(level=logging.DEBUG) alembic = CommandLine() alembic.parser.formatter_class = argparse.ArgumentDefaultsHelpFormatter alembic.parser.add_argument( "--pg-url", default=os.getenv("POSTGRES_URI", POSTGRES_URI), help="Database URL [env var: POSTGRES_URI]", ) options = alembic.parser.parse_args() if "cmd" not in options: alembic.parser.error("too few arguments") exit(128) else: config = make_alembic_config(options) exit(alembic.run_cmd(config, options)) if __name__ == "__main__": main()
53f6826f6718fa581f0cbac1f01d729661c3ec17
[ "Markdown", "Python", "Text" ]
14
Python
nacknime-official/telegram-coin-bot
25901d0fabbd487c50edd7257b2ac6e06b0a02c7
37b7b5718514fb1f87f4b63f6b68e954d7051485
refs/heads/main
<file_sep> /* RECUPERAR DEL LOCALSTORAGE */ let superheroe; let arraySuperheroe = []; let names; let id; let favoritosArray; /* Obtener los datos del localstorage y dibujar la tabla */ function drawFavoritos() { if (localStorage.getItem("favoritos")) { superheroe = localStorage.getItem('favoritos'); arraySuperheroe = JSON.parse(superheroe); console.log(arraySuperheroe); arraySuperheroe.forEach(element => { hero += ` <tr> <td><img src="${element.image}" alt="Foto de ${element.name}"></td> <td>${element.id}</td> <td>${element.name}</td> <td>${element.work}</td> <td><i onclic="deleteFavorito(>${element.id})" class="fas fa-trash-alt eliminar"></i></td> </tr> `; }); let tabla = ` <table class=""> <thead> <tr> <th>Imagen</th> <th>Id</th> <th>Nombre</th> <th>Trabajo</th> <th>Acciones</th> </tr> </thead> <tbody> ${hero} </tbody> </table> ` document.getElementById('tabla-favoritos').innerHTML = tabla; } else { superheroe = "No hay héroes en tu lista de favoritos"; } } /* function deleteFavorito(id) { for (var i = 0; i < localStorage.length; i++) { localStorage.removeItem(id[i]); } } */ /* function deleteFavorito(id) { for (let i = 0; i < arraySuperheroe.length; i++) { if (id == arraySuperheroe[i].id) { localStorage.removeItem(id); } } */ /* if (id == favoritos[i].id) { //favoritos.slice(arraySuperheroe[i], 1); localStorage.removeItem(id); } */ <file_sep>const KEY = "10217395314010785"; const URL_PATH = `https://superheroapi.com/api/${KEY}`; /***********************************************************/ /* INDEX */ /***********************************************************/ let imageHeroes; let resultsImages; let errorFetch; let filtroGender; let i; let imageGender; let resultGender; let select; let selectedOption; const HERO_ENDPOINTS = [ `${URL_PATH}/search/spider-man`, `${URL_PATH}/search/wolverine`, `${URL_PATH}/search/ironman`, `${URL_PATH}/search/magneto`, `${URL_PATH}/search/deadpool`, `${URL_PATH}/search/cyborg`, `${URL_PATH}/search/hawkgirl` ] /* Todos lo superhéroes */ for (let i = 0; i < HERO_ENDPOINTS.length; i++) { fetch(HERO_ENDPOINTS[i]) .then(response => response.json()) .then(data => { resultsImages = data.results; if (resultsImages !== -1) { resultsImages.forEach(element => { imageHeroes += ` <div class="item"> <img src="${element.image.url}" alt="Imagen de ${element.name}"> </div>`; }) document.getElementById("masonry").innerHTML = ''; document.getElementById("masonry").innerHTML = imageHeroes; filtroGender = ` <div class="selectFiltro"> <h4>¿Superhéroe o Superheroína?</h4> <select id="selector" onchange="capturaValor()"> <option value="">Selecciona</option> <option value="Male">Superhéroe</option> <option value="Female">Superheroina</option> </select> </div>`; document.querySelector('.filtro').innerHTML = filtroGender; } else { errorFetch = ` <div class="error"> <p>error en el fetch</p> <button onclic="cerrarMensaje()">ELIMINAR</button> </div> `; document.querySelector('.novedades .aviso').innerHTML = errorFetch; } }) } function capturaValor() { select = document.getElementById('selector'); selectedOption = select.options[select.selectedIndex].value; console.log(selectedOption); for (let i = 0; i < HERO_ENDPOINTS.length; i++) { fetch(HERO_ENDPOINTS[i]) .then(response => response.json()) .then(data => { resultsImages = data.results; resultGender = resultsImages.filter(elemento => elemento.appearance.gender == selectedOption) resultGender.forEach(element => { imageGender += ` <div class="item"> <img src="${element.image.url}" alt="Imagen de ${element.name}"> </div>` ; }); document.getElementById("masonry").innerHTML = ''; document.getElementById("masonry").innerHTML = imageGender; }) } } /* function cerrarMensaje() { console.log('Quiero cerrar') let error = document.querySelectorAll('.error'); document.querySelector('.aviso').removeChild(lastChild); }*/ /***********************************************************/ /* CATÁLOGO */ /***********************************************************/ let hero = ""; let resultado; let arrayHero = []; let detalleHero; let favoritos = []; function searchHero() { const NAME_HERO = document.getElementById("hero").value; const URL_HERO = `${URL_PATH}/search/${NAME_HERO}`; fetch(URL_HERO) .then(response => response.json()) .then(data => { resultado = data.results; resultado.forEach(element => { detalleHero = { image: element.image.url, id: element.id, name: element.name, work: element.work.occupation, }; arrayHero.push(detalleHero); hero += ` <div class="card-hero" href="#"> <div class="card-image"> <img id="hero-image" src="${element.image.url}" alt="Imagen de ${element.name}"> </div> <div class="card-name"> <h4 id="hero-name">${element.name}</h4> <i onclick="addFavoritos(${element.id})" class="far fa-heart"></i> </div> </div> `; }); let resultsHeroes = document.getElementById("results-hero"); resultsHeroes.innerHTML = hero; }) } /***********************************************************/ /* FAVORITOS */ /***********************************************************/ /* AÑADIR A FAVORITOS */ function addFavoritos(id) { for (let i = 0; i < arrayHero.length; i++) { if (id == arrayHero[i].id) { favoritos.push(arrayHero[i]); } } localStorage.setItem("favoritos", JSON.stringify(favoritos)); console.log(arrayHero); }
6bcee752581b58d28e64ac823e86425fe63543ad
[ "JavaScript" ]
2
JavaScript
jelenreifs/Proyecto_API-Marvel
0d10c584732bdf47ff1bdb5b49eb710054154d3e
5b265685ed440b9df85de32cca37e86db10f7353
refs/heads/master
<repo_name>jnoranbrock/HerokuApp<file_sep>/src/resources/js/fractions.js // Importing Modules // const { // random, // problemReplicated, // generateNumeratorCombinations, // problem // } = require("./scripts"); /* Functions */ /** random() * random number generator that generates an integer between low and high parameters. * @param {number} low low parameter * @param {number} high high parameter */ function random(low, high){ return Math.floor(Math.random() * (high - low + 1) ) + low; } // Array to store all the problems in var problems = new Array(); // this is a count of the problems and an index for problems array var problemNumber = 0; // number of problems correct, to be incremented when user submits correct answer var correct = 0; // number of problems attempted, to be incremented when user submits any answer var attempted = 0; // selects whether operator is addition, subtraction, multiplication, or division var operator_selector = Math.floor(Math.random() * 4); function readAnswer(){ var answer_numerator = parseFloat(document.getElementById("inputAnswer1").value); if (isNaN(answer_numerator)) { document.getElementById("answerMessage1").innerHTML = `Invalid Answer. Please try again!`; return; } var answer_denominator = parseFloat(document.getElementById("inputAnswer2").value); if (isNaN(answer_denominator)) { document.getElementById("answerMessage1").innerHTML = `Invalid Answer. Please try again!`; return; } var num1_numerator = parseFloat(document.getElementById("numeral_a_numerator").innerHTML); var num1_denominator = parseFloat(document.getElementById("numeral_a_denominator").innerHTML); var num2_numerator = parseFloat(document.getElementById("numeral_b_numerator").innerHTML); var num2_denominator = parseFloat(document.getElementById("numeral_b_denominator").innerHTML); let ans = 0; if(operator_selector === 0){ ans = (num1_numerator / num1_denominator) + (num2_numerator / num2_denominator); }else if(operator_selector === 1){ ans = (num1_numerator/num1_denominator) - (num2_numerator / num2_denominator); }else if(operator_selector === 2){ ans = (num1_numerator / num1_denominator) * (num2_numerator / num2_denominator); }else{ ans = (num1_numerator / num1_denominator) / (num2_numerator / num2_denominator); } let answer = answer_numerator / answer_denominator; let answerRounded = answer.toFixed(5); let ansRounded = ans.toFixed(5); problems.push({ "numeral_a_numerator": num1_numerator, "numeral_a_denominator": num1_denominator, "numeral_b_numerator": num2_numerator, "numeral_b_denominator": num2_denominator, "user_answer": answerRounded, "answer": ansRounded, "correct": Boolean(answerRounded === ansRounded), "problem_number": problemNumber - 1, "operator": document.getElementById("operator").innerHTML }); console.log(problems[problemNumber - 1]); if(answerRounded === ansRounded){ correct++; attempted++; document.getElementById("answerMessage1").innerHTML = `Correct Answer! Your answer: ${answerRounded}`; }else{ attempted++; document.getElementById("answerMessage1").innerHTML = `Incorrect Answer. Your answer: ${answerRounded} | Correct answer: ${ansRounded}`; } document.getElementById("answerMessage2").innerHTML = `You've answered ${correct} problems correctly in ${attempted} attempts`; document.getElementById("submitbutton").disabled = true; document.getElementById("nextbutton").disabled = false; } function changeProblem(){ operator_selector = Math.floor(Math.random() * 4); if(operator_selector === 0){ document.getElementById("operator").innerHTML = "+"; }else if(operator_selector === 1){ document.getElementById("operator").innerHTML = "-"; }else if(operator_selector === 2){ document.getElementById("operator").innerHTML = "*"; }else{ document.getElementById("operator").innerHTML = "÷"; } document.getElementById("fraction_operator_1").innerHTML = "/"; document.getElementById("fraction_operator_2").innerHTML = "/"; document.getElementById("fraction_operator_3").innerHTML = "/"; document.getElementById("equality_sign").innerHTML = "="; let numeral_a_numerator = Math.floor(Math.random() * 10); let numeral_a_denominator = random(1, 10); // so the denominator is not 0, can't divide by 0 let numeral_b_numerator = Math.floor(Math.random() * 10); let numeral_b_denominator = random(1, 10); // so the denominator is not 0, can't divide by 0 problemNumber++; document.getElementById("numeral_a_numerator").innerHTML = numeral_a_numerator; document.getElementById("numeral_b_numerator").innerHTML = numeral_b_numerator; document.getElementById("numeral_a_denominator").innerHTML = numeral_a_denominator; document.getElementById("numeral_b_denominator").innerHTML = numeral_b_denominator; document.getElementById("answerMessage1").innerHTML = ""; document.getElementById("submitbutton").disabled = false; document.getElementById("nextbutton").disabled = true; // const inputField = document.getElementById("inputAnswer"); // inputField.value = ""; document.getElementById("inputAnswer1").value = ""; document.getElementById("inputAnswer2").value = ""; } function score(){ document.getElementById("problem_form").remove(); var percent_correct = correct / attempted * 100; percent_correct = percent_correct.toFixed(2); document.getElementById("answerMessage1").innerHTML = `Your score is ${percent_correct}%`; document.getElementById("submitbutton").remove(); document.getElementById("nextbutton").remove(); document.getElementById("scorebutton").remove(); document.getElementById("missed_questions_title").innerHTML = "Some Questions You Missed:"; var countWrong = 0; var operator = ''; for(let i = 0; i < problems.length && countWrong < 3; i++){ if(!problems[i].correct){ if(problems[i].operator === '+'){ operator = '+'; }else if(problems[i].operator === '-'){ operator = '-' }else if(problems[i].operator === '*'){ operator = '*'; }else{ operator = '÷'; } if(countWrong === 0){ document.getElementById("incorrect_problem_1").innerHTML = `The correct answer for ${problems[i].numeral_a_numerator} / ${problems[i].numeral_a_denominator} ${operator} ${problems[i].numeral_b_numerator} / ${problems[i].numeral_b_denominator} is ${problems[i].answer}`; document.getElementById("incorrect_answer_1").innerHTML = `You answered ${problems[i].user_answer}`; }else if(countWrong === 1){ document.getElementById("incorrect_problem_2").innerHTML = `The correct answer for ${problems[i].numeral_a_numerator} / ${problems[i].numeral_a_denominator} ${operator} ${problems[i].numeral_b_numerator} / ${problems[i].numeral_b_denominator} is ${problems[i].answer}`; document.getElementById("incorrect_answer_2").innerHTML = `You answered ${problems[i].user_answer}`; }else{ document.getElementById("incorrect_problem_3").innerHTML = `The correct answer for ${problems[i].numeral_a_numerator} / ${problems[i].numeral_a_denominator} ${operator} ${problems[i].numeral_b_numerator} / ${problems[i].numeral_b_denominator} is ${problems[i].answer}`; document.getElementById("incorrect_answer_3").innerHTML = `You answered ${problems[i].user_answer}`; } countWrong++; } } } <file_sep>/db/init_data/create.sql DROP TABLE IF EXISTS user_info_db CASCADE; CREATE TABLE IF NOT EXISTS user_info_db( full_name VARCHAR(35), email_address VARCHAR(320), /* 320 characters is the max length of an email address */ password VARCHAR(25), PRIMARY KEY(full_name) ); DROP TABLE IF EXISTS user_problems CASCADE; CREATE TABLE IF NOT EXISTS user_problems( problem_type VARCHAR(35), numeral_a INT, operator VARCHAR(1), numeral_b INT, answer INT, correct INT, /* number of problems correct, to be incremented when user submits correct answer */ attempted INT /* number of problems attempted, to be incremented when user submits any answer */ -- CONSTRAINT user_full_name FOREIGN KEY(full_name) REFERENCES user_info_db(full_name) ); DROP TABLE IF EXISTS names CASCADE; CREATE TABLE IF NOT EXISTS names( fname VARCHAR(35) ); <file_sep>/src/server.js /*********************** Load Components! Express - A Node.js Framework Body-Parser - A tool to help use parse the data in a post request Pg-Promise - A database tool to help use connect to our PostgreSQL database ***********************/ var express = require('express'); //Ensure our express framework has been added var app = express(); var bodyParser = require('body-parser'); //Ensure our body-parser tool has been added app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies app.use(bodyParser.json()); // support json encoded bodies //Create Database Connection var pgp = require('pg-promise')(); /********************** Database Connection information host: This defines the ip address of the server hosting our database. We'll be using `db` as this is the name of the postgres container in our docker-compose.yml file. Docker will translate this into the actual ip of the container for us (i.e. can't be access via the Internet). port: This defines what port we can expect to communicate to our database. We'll use 5432 to talk with PostgreSQL database: This is the name of our specific database. From our previous lab, we created the football_db database, which holds our football data tables user: This should be left as postgres, the default user account created when PostgreSQL was installed password: This the password for accessing the database. We set this in the docker-compose.yml for now, usually that'd be in a seperate file so you're not pushing your credentials to GitHub :). **********************/ const dev_dbConfig = { host: 'db', port: 5432, database: process.env.POSTGRES_DB, user: process.env.POSTGRES_USER, password: process.env.POSTGRES_PASSWORD }; /** If we're running in production mode (on heroku), the we use DATABASE_URL * to connect to Heroku Postgres. */ const isProduction = process.env.NODE_ENV === 'production'; const dbConfig = process.env.DATABASE_URL; // Heroku Postgres patch for v10 // fixes: https://github.com/vitaly-t/pg-promise/issues/711 if (isProduction) { pgp.pg.defaults.ssl = {rejectUnauthorized: false}; } const db = pgp(dbConfig); // set the view engine to ejs app.set('view engine', 'ejs'); app.set('views', __dirname + '/views'); app.use(express.static(__dirname + '/'));//This line is necessary for us to use relative paths and access our resources directory // home page app.get('/', function(req, res) { res.render('pages/Main_Menu',{ local_css:"my_style.css", my_title:"Main Menu" }); }); // registration page app.get('/register', function(req, res) { res.render('pages/register',{ my_title:"Registration Page" }); }); function uploadDataToDB(req) { var full_name = req.body.fullName.value; var user_email = req.body.emailAddress.value; var user_pass = req.body.password<PASSWORD>.value; var query = `INSERT INTO user_info_db(full_name, email_address,password)VALUES(${full_name},${user_email},${user_pass})`; // add the user's info to the database. return query; // window.location.href = "../../views/login.html"; // This supposedly makes page change but can't get to work }; app.post('/register', function(req, res) { var full_name = req.body.fullName; var user_email = req.body.emailAddress; var user_pass = <PASSWORD>.<PASSWORD>; var query = `INSERT INTO user_info_db(full_name, email_address,password)VALUES(${full_name},${user_email},${user_pass})`; // add the user's info to the database. db.query(query, (err, db_res) => { if (err !== undefined) { console.log("Postgres INS error:", err); console.log("\nkeys for Postgres error:", Object.keys(err)); } if (db_res !== undefined) { console.log("Postgres response:", res); console.log("\nkeys for Postgres res:", Object.keys(res)); } if (db_res.rowCount > 0) { console.log("User inserted"); } else { console.log("No records inserted"); } } ); res.render('pages/login',{ my_title: "Login Page" }); }); // Login page\\ app.get('/login', function(req, res) { res.render('pages/login',{ my_title:"Login Page" }); }); app.get('/logout', function(req, res) { res.render('pages/Main_Menu',{ local_css:"my_style.css", my_title:"Main Menu" }); }); //Page to get users name app.get('/name', function(req, res) { res.render('pages/name',{ my_title:"Name Page" }); }); /* app.post('/name/add_name',function(req,res){ var name = req.body.name; var insert_statement = "INSERT INTO names(fname) VALUES('" + name + "') ON CONFLICT DO NOTHING;"; var names = 'select * from names;'; db.task('post-game-data', task => { return task.batch([ task.any(insert_statement), task.any(names) ]); }) .then(data => { res.render('pages/Main_Menu',{ my_title:"Main Menu", names: data[1], }) }) .catch(err => { console.log('Uh Oh I made an oopsie'); req.flash('error', err); res.render('pages/names',{ my_title: "Names", players: '', playerinfo: '', games: '' }) }); }); */ // menu page app.get('/Main_Menu', function(req, res) { res.render('pages/Main_Menu',{ my_title:"Main Menu" }); }); /* app.get('/Main_Menu', function(req,res){ var names = 'select * from names;'; db.task('get-everything', task => { return task.batch([ task.any(names) ]); }) }); */ app.post("/Main_Menu", function(req,res) { var name = String(req.body.name); console.log(name); res.send("Welcome " + name); }); app.get('/About_Us', function(req, res) { res.render('pages/About_Us',{ my_title:"About us Page" }); }); app.get('/addition', function(req, res) { res.render('pages/addition',{ my_title:"addition Page" }); }); app.get('/subtraction', function(req, res) { res.render('pages/subtraction',{ my_title:"subtraction Page" }); }); app.get('/multiplication', function(req, res) { res.render('pages/multiplication',{ my_title:"multiplication Page" }); }); app.get('/division', function(req, res) { res.render('pages/division',{ my_title:"division Page" }); }); app.get('/fractions', function(req, res) { res.render('pages/fractions',{ my_title:"fractions Page" }); }); app.get('/decimals', function(req, res) { res.render('pages/decimals',{ my_title:"decimals Page" }); }); app.get('/algebra', function(req, res) { res.render('pages/algebra',{ my_title:"algebra Page" }); }); app.get('/report_card', function(req, res){ res.render('pages/report_card', { my_title: "Report Card" }); }); //app.listen(3000); const server = app.listen(process.env.PORT || 3000, () => { console.log(`Express running → PORT ${server.address().port}`); }); <file_sep>/src/resources/js/scripts.js function insertName(){ // const queryString = window.location.search; // console.log(`queryString: ${queryString}`); // const urlParams = new URLSearchParams(queryString); // const Fname = urlParams.get('Fname'); // console.log(`Fname: ${Fname}`); // const // keys = urlParams.keys(), // values = urlParams.values(), // entries = urlParams.entries(); // for (const key of keys) console.log(key); // for (const value of values) console.log(value); var name = window.location.search.split("=")[1]; // for(const entry of entries) { // if(entry[0] == 'Fname'){ // name = entry[1]; // } // console.log(`${entry[0]}: ${entry[1]}`); // } if(name == undefined){ document.getElementById("welcome-msg").style.visibility = "hidden"; document.getElementById("welcome-msg").style.height = "0px"; } else{ document.getElementById("welcome-msg").style.visibility = "visible"; document.getElementById("welcome-msg").style.height = "auto"; document.getElementById("Fname-welcome").innerHTML = name; } } function uploadDataToDB(){ var full_name = document.getElementById("fullName").value; var user_email = document.getElementById("inputEmail").value; var user_pass = document.getElementById("<PASSWORD>").value; var query = `INSERT INTO user_info_db(full_name, email_address, password)`; query += `VALUES(${full_name}, ${user_email}, ${user_pass})`; // add the user's info to the database. return query; // window.location.href = "../../views/login.html"; // This supposedly makes page change but can't get to work } /* var query = `INSERT INTO user_problems(problem_type, numeral_a, operator, numeral_b, answer, correct, attempted)`; query += `VALUES('Addition', ${num1}, '+', ${num2}, ${ans}, ${correct}, ${attempted});`;*/ function checkDB4Acc(){ var valid_email = false; var valid_password = false; var valid_bingocatch = false; var keypin = 0; var user_email = document.getElementById("inputEmail").value; var user_pass = document.getElementById("inputPassword").value; var user_name = ""; var all_emails = new Array(); // make an array of all the emails in the database var all_passwords = new Array(); // make an array of all the passwords in the database var all_names = new Array(); //all the names in db var num_users = all_emails.length; var query = `SELECT email_address, password, full_name FROM user_info_db WHERE email_address=${user_email} AND password=${<PASSWORD>};`; // query to get the row where the user's email and password match. db.any(query).then(info => { all_emails = info[0], all_passwords = info[1], all_names = info[2] }).catch(err => { console.log(`Error: ${err}`); }); for(let i = 0; i < num_users; i++){ if(all_emails[i] === user_email){ // match the emails valid_email = true; keypin = i; } if(all_passwords[i] === user_pass){ // match the passwords valid_password = true; if (keypin === i) {valid_bingocatch = true;} } if(valid_email && valid_password && valid_bingocatch){ user_name = all_names[i] break; // User is authenticated. } } if(valid_email && valid_password){ console.log("User is authenticated"); var nameplate= document.getElementById("welcmsg") nameplate.innerHTML = user_name; nameplate.style.visibility = "visible;" } else if(valid_email && !valid_password){ console.log("Incorrect password"); document.getElementById("invalid_message").innerHTML = "Incorrect Password"; } else if(!valid_email && valid_password){ console.log("Incorrect email"); document.getElementById("invalid_message").innerHTML = "Incorrect Email"; } else{ document.getElementById("invalid_message").innerHTML = "Incorrect Email and Password"; } } function showPassword(id) { var pwd = document.getElementById(id); if(pwd.type === "password"){pwd.type = "text";} else{pwd.type = "password";} } function validExpr(expr, str){ if(expr.test(str)) {return true;} else {false;} } function v_email(id) { return validExpr(/^[0-z,\.]+@[A-z]+\.[A-z]{1,3}$/g, document.getElementById(id).value); } function v_pass(id) { return validExpr(/^(?=.+\d)(?=.*[A-Z]+)(?=.*[:-@!-/[-`{-~]+).{8,}$/g, document.getElementById(id).value);} function validEmail() { var em = document.getElementById("emailAddress"); var v_em = document.getElementById("Valid_em"); if(validExpr(/^[0-z,\.]+@[A-z]+\.[A-z]{1,3}$/g, em.value)) { v_em.src="../resources/img/cmark.png"; v_em.style.visibility = "visible"; v_em.style.height = "30px"; } else { v_em.src="../resources/img/cross.png"; v_em.style.visibility = "visible"; v_em.style.height = "30px";} } function validPass(){ var pw = document.getElementById("passwordFirst"); var c_pw = document.getElementById("passwordConfirm"); var v_pw = document.getElementById("Valid_pw"); if(validExpr(/^(?=.+\d)(?=.*[A-Z]+)(?=.*[:-@!-/[-`{-~]+).{8,}$/g, pw.value) && pw.value === c_pw.value) { validSubmit(true); v_pw.src="../resources/img/cmark.png"; v_pw.style.visibility = "visible"; v_pw.style.height = "30px"; return; } else { validSubmit(false); v_pw.src="../resources/img/cross.png"; v_pw.style.visibility = "visible"; v_pw.style.height = "30px"; return; } } function validSubmit(bool){ if (bool == true) { document.getElementById("reg").disabled = false; } else { document.getElementById("reg").disabled = true; } } function proceedToProblem(id, toggle){ var x = document.getElementById(id); if(toggle == 0){ x.style.visibility = "hidden"; x.style.height = "0px"; } if(toggle == 1){ x.style.visibility = "visible"; x.style.height = "auto"; } } /** random() * random number generator that generates an integer between low and high parameters. */ function random(low, high){ return Math.floor(Math.random() * (high - low + 1) ) + low; } /** Check if the *numeralCombinationsUsed* array has the combination of the given parameters. * We don't want the same problem being generated multiple times so make function to check if problem has been replicated. * @param numeral_a (Number) First numeral in the equation. * @param numeral_b (Number) Second numeral in the equation. * @param numeralCombinationsUsed (Array) 2d Array of numeral combinations used for that specific file. * @returns **True** if the combination is in the numeralCombinationsUsed array. **False** if the combination isn't in the numeralCombinationsUsed array. */ function problemReplicated(numeral_a, numberal_b, numeralCombinationsUsed){ for(let i = 0; i < numeralCombinationsUsed.length; i++){ let arr1 = [numeral_a, numberal_b]; let arr2 = numeralCombinationsUsed[i]; let n = arr1.length; let m = arr2.length; if(n != m){ return false; } arr1.sort(); arr2.sort(); for(let j = 0; j < n; j++){ if(arr1[j] != arr2[j]){ return false; } } return true; } return false; } /** Generate a given number of unique numerator combinations. * @param numComb (Number) The number of unique numerator combinations. * @returns A 2d array of the numerator combinations. */ function generateNumeratorCombinations(numComb){ var numeralCombinationsUsed = new Array(); var a = random(1, 100); var b = random(1, 100); a = 2; b = 1; numeralCombinationsUsed.push([a, b]); while(numeralCombinationsUsed.length != numComb){ a = random(1, 100); b = random(1, 100); if(!problemReplicated(a, b, numeralCombinationsUsed)){ var numerals = [a, b]; numeralCombinationsUsed.push(numerals); } } return numeralCombinationsUsed; } /** Generate a new problem. * @param number_ (Number) The problem number * @param type_ (String) The problem type ('addition', 'subtraction', etc....) * @param difficulty_ (String or Number) difficulty level of the problem. * @param solution_ (Number) The problem answer. * @param incorrect_explanations_ (Object) Object for different explanations for why the problem is wrong. * @returns A new problem object. */ function generateProblem(number_, type_, difficulty_, solution_, incorrect_explanations_){ if(!(typeof type_ === 'string')){ console.log(`Error: parameter type_ must be a string but is instead of type: (${typeof type_})`); } /* Base Object for each problem */ const problem = { number: number_, // problem number type: type_, // problem type. Can be addition, subtraction, division, etc.... difficulty: difficulty_, // difficulty level of the problem solution: solution_, // problem answer incorrect_explanations: incorrect_explanations_, // object for different explanations for why the problem is wrong. num_attempts: 0, // index to access user attempts for the problem. answers: new Array() // array of attempted answers. }; return problem; } // Exporting //module.exports = { random, problemReplicated, generateNumeratorCombinations, problem }; <file_sep>/README.md <div align="center"> # Math Whiz-ard </div> *Math Whiz-ard* is a web app that allows users to practice basic math problems. Intended mainly for kids in elementary or middle school, *Math Whiz-ard* is a web app that can help improve grades and test scores. Unlike Pearson practice tests, our product allows the user to practice as much or as little as they need to feel comfortable with the subject. Users can choose from an array of problem types, including: addition, subtraction, multiplication, division, fractions, algebra, and decimal operations. Users will be shown the correct answer if they are wrong and once they are done will be shown their score and a short list of problems they got wrong. Lastly, like we have mentioned before, the UI is clean and simple; it is easily understandable and accessible for all, and the best part of the entire package is that there is no paywall! --- ## **Adult Swim**: Team Members - <NAME> - <NAME> - <NAME> - <NAME> - <NAME> # Project Vision Statement - We aim to create an app that gives elementary and middle school students the means and freedom to practice different concepts from math in varying scales of difficulty. # Instructions to run *Math Whiz-ard* can be run locally or on heroku. To run on Heroku, Click Our [Link Here](https://mathwhiz-ard.herokuapp.com/) # Repository Structure - `Heroku` - `db` - `init_data` - for `SQL` files - `heroku` - `src` - `resources` - `css` - `img` - `js` - Each math page gets its own JavaScript page that performs operations like generating and changing problems. - `views` - Directory of the different pages in our app. - `pages` - Directory of `ejs` files for each page in our app. - `partials` - Contains a footer, header, and menu `ejs` file for use in different files in the `pages` directory. - `.env` - Contains our postgres user, password, and database names. - HerokuLink.txt - text file with the link to our Heroku app. - server.js - `MilestoneSubmissions` - All our milestone documents and a readme - `Project` - `heroku` - `.env` - contains our Heroku API key. - `init_data` - for `SQL` files - `resources` - `css` - `img` - `js` - Each math page gets its own `JavaScript` page that performs operations like generating and changing problems. - `views` - Directory of the different pages in our app. - TeamMeetingLog.md - this file is a log of some topics covered in early team meetings. # Application Architecture - Front-End: CSS, JavaScript, HTML - Back-End: JavaScript, Node.js, PostgreSQL - Platform: Web-App # Jira Dashboard - https://csci-3308-summer1-6.atlassian.net/jira/software/projects/A36/boards/1 # Meeting time with TA - Thursdays at 3PM - 3:20PM MST (15:00 - 15:20 MST) - Dwight's Office Hours Link: https://cuboulder.zoom.us/j/95832525120 # Team Meeting Time - Thursdays at 7PM - 9PM MST - Zoom Link: https://cuboulder.zoom.us/j/2172365690 <file_sep>/src/resources/js/report_card.js function sendToReportCard(){ console.log(problems); var body = document.getElementById("report-card-body"); // var tally_table = document.getElementById("tally-table"); document.getElementById("num_correct").innerHTML = correct; document.getElementById("num_incorrect").innerHTML = attempted - correct; for(let i = 0; i < problems.length; i++){ var row = `<tr>`; row += `<td id="problem-number">${i + 1}</td>`; row += `<td id="operation">${operator}</td>`; row += `<td id="user_answer">${problems[i].user_answer}</td>`; row += `<td id="solution">${problems[i].answer}</td>`; row += `</tr>`; body += row; } }
be9a683464a691507bf2d28418171de9fa86d1d1
[ "JavaScript", "SQL", "Markdown" ]
6
JavaScript
jnoranbrock/HerokuApp
ef07513006af8cdef415a7df06584ad697713b80
27d61d15c4813f590b85d231aa73c75dc4e7624e
refs/heads/main
<file_sep># An Ionic React Front end implementation of capacitor barcode scanner on a nestjs back end ```bash $ npm install $ cd nest-barcode $ npm install ``` ## Run the nest server first ``` ~/ionic-barcode/nest-server/ $ npm start ``` ## Run the Ionic Server ``` ~/ionic-barcode/: $ yarn start ``` ## Change the nest url to your local dev url ``` ~/ionic-barcode/src/pages/Tab1.tsx // Edit this line const url = 'https://localhost:3000/' ``` <file_sep>import { Injectable } from '@nestjs/common'; @Injectable() export class AppService { getHello(): string { return 'Hello World!'; } sendBarcode(barcode: string): string { console.log(barcode) return 'sent' } }
4e16009b9c52372153cb725725ff89c82370fff0
[ "Markdown", "TypeScript" ]
2
Markdown
jjDeveloper/ionic-barcode
897b3aa361eb9097c56d4231f0c27f501287343d
8341a57fb97f40ec212f12e870e834b9e5c2e839
refs/heads/master
<file_sep>jsondiffpatch = Npm.require('jsondiffpatch');<file_sep>Package.describe({ name: 'risul:jsondiffpatch', summary: 'Meteor package for jsondiffpatch - Diff & patch JavaScript objects.', version: '1.0.5', git: 'https://github.com/risul/meteor-jsondiffpatch' }); Npm.depends({ jsondiffpatch: '0.1.37' }); Package.onUse(function(api) { api.versionsFrom('METEOR@0.9.2.2'); api.export('jsondiffpatch'); api.addFiles('lib/jsondiffpatch.js', 'server'); });<file_sep>meteor-jsondiffpatch =============== Meteor package for jsondiffpatch - Diff & patch for JavaScript objects. More info: https://github.com/benjamine/jsondiffpatch ##Install ```bach meteor add risul:jsondiffpatch ``` Usage ----- ``` javascript // sample data var country = { name: "Argentina", capital: "Buenos Aires", independence: new Date(1816, 6, 9), unasur: true }; // clone country, using dateReviver for Date objects var country2 = JSON.parse(JSON.stringify(country), jsondiffpatch.dateReviver); // make some changes country2.name = "Republica Argentina"; country2.population = 41324992; delete country2.capital; var delta = jsondiffpatch.diff(country, country2); assertSame(delta, { "name":["Argentina","Republica Argentina"], // old value, new value "population":["41324992"], // new value "capital":["Buenos Aires", 0, 0] // deleted }); // patch original jsondiffpatch.patch(country, delta); // reverse diff var reverseDelta = jsondiffpatch.reverse(delta); // also country2 can be return to original value with: jsondiffpatch.unpatch(country2, delta); var delta2 = jsondiffpatch.diff(country, country2); assert(delta2 === undefined) // undefined => no difference ``` Array diffing: ``` javascript // sample data var country = { name: "Argentina", cities: [ { name: 'Buenos Aires', population: 13028000, }, { name: 'Cordoba', population: 1430023, }, { name: 'Rosario', population: 1136286, }, { name: 'Mendoza', population: 901126, }, { name: '<NAME>', population: 800000, } ] }; // clone country var country2 = JSON.parse(JSON.stringify(country)); // delete Cordoba country.cities.splice(1, 1); // add La Plata country.cities.splice(4, 0, { name: '<NAME>' }); // modify Rosario, and move it var rosario = country.cities.splice(1, 1)[0]; rosario.population += 1234; country.cities.push(rosario); // create a configured instance, match objects by name var diffpatcher = jsondiffpatch.create({ objectHash: function(obj) { return obj.name; } }); var delta = diffpatcher.diff(country, country2); assertSame(delta, { "cities": { "_t": "a", // indicates this node is an array (not an object) "1": [ // inserted at index 1 { "name": "Cordoba", "population": 1430023 }] , "2": { // population modified at index 2 (Rosario) "population": [ 1137520, 1136286 ] }, "_3": [ // removed from index 3 { "name": "<NAME>" }, 0, 0], "_4": [ // move from index 4 to index 2 '', 2, 3] } }); ```
0dd04b57316e5d2b6fdacc570dca4b33d0e9fea1
[ "JavaScript", "Markdown" ]
3
JavaScript
Isoform/meteor-jsondiffpatch
6b1024a718a12f570b8122f20289f370e752ee37
21f08dc5317709cd372bfe5c05f8b443e84ffac5
refs/heads/master
<repo_name>eastfire/dungeon-deck<file_sep>/src/item-card-sprite.js var ItemCardSprite = BaseCardSprite.extend({ ctor: function( options ){ this._super( options ) // this.iconPositions = { // score: { // x: dimens.hero_icon_offset.x, // y: dimens.hero_icon_offset.y // } // } // this.iconImages = { // score: cc.spriteFrameCache.getSpriteFrame("score-icon.png") // } // this.icons = { // } this.registerIcon("score", cc.spriteFrameCache.getSpriteFrame("score-icon.png") ,{ x: dimens.hero_icon_offset.x, y: dimens.hero_icon_offset.y }) }, __initEvent:function(){ this._super(); this.model.on("change:score",function(){ this.onIconChanged("score", true, true); },this); }, __refresh:function(){ this._super(); this.renderIcon("score"); }/*, renderIcon:function(attr){ var stat = this.model.get(attr); var icon = this.icons[attr]; if (stat !== 0) { if ( icon ) { icon.setString(stat); } else { icon = this.icons[attr] = new IconSprite({ image: this.iconImages[attr] }); icon.attr ( this.iconPositions[attr] ) this.addChild(icon,1) this.addFrontSprite( icon ); } } else { if ( icon ) { this.removeFrontSprite(icon); icon.removeFromParent(true); this.icons[attr] = null; } } }, onIconChanged:function(attr, needAddEffect, needSubEffect){ this.renderIcon(attr); var stat = this.model.get(attr); if ( this.model.previous(attr) != stat ) { var diff = stat - this.model.previous(attr); var diffStr = diff; if ( diff > 0 ) diffStr = "+"+diff; if ( ( diff > 0 && needAddEffect ) || ( diff < 0 && needSubEffect ) ) { effectIconMananger.enqueue(this, { icon: attr + "-icon", text: diffStr }); } } }*/ }) <file_sep>/src/monster-card-sprite.js /** * Created by 赢潮 on 2015/2/27. */ var MonsterCardSprite = BaseCardSprite.extend({ ctor: function( options ){ this._super( options ) this.attackRangeIcon = new IconSprite({ image: cc.spriteFrameCache.getSpriteFrame("attack-"+this.model.get("attackRange")+"-icon.png") }); this.attackRangeIcon.attr({ x: dimens.card_width - dimens.hero_icon_offset.x, y: dimens.card_height - dimens.hero_icon_offset.y - dimens.hero_icon_size.height }); this.addChild(this.attackRangeIcon,1); this.addFrontSprite( this.attackRangeIcon ); this.registerIcon("attack", cc.spriteFrameCache.getSpriteFrame("attack-icon.png") ,{ x: dimens.card_width - dimens.hero_icon_offset.x, y: dimens.card_height - dimens.hero_icon_offset.y }, { showZero: true, buffAttribute:"attackBuff", debuffAttribute: "attackDebuff" }); this.registerIcon("pierce", cc.spriteFrameCache.getSpriteFrame("pierce-icon.png") ,{ x: dimens.card_width - dimens.hero_icon_offset.x, y: dimens.card_height - dimens.hero_icon_offset.y - dimens.hero_icon_size.height * 2 }); this.registerIcon("trample", cc.spriteFrameCache.getSpriteFrame("trample-icon.png") ,{ x: dimens.card_width - dimens.hero_icon_offset.x, y: dimens.card_height - dimens.hero_icon_offset.y - dimens.hero_icon_size.height * 3 }); }, renderAttackRangeIcon:function(){ this.attackRangeIcon.setIcon(cc.spriteFrameCache.getSpriteFrame("attack-"+this.model.get("attackRange")+"-icon.png")); }, __initEvent:function() { this._super(); this.model.on("destroy", this.remove, this); this.model.on("change:hp", function () { this.onIconChanged("hp", true, true); this.checkDie(); }, this); this.model.on("change:attack",function(){ this.onIconChanged("attack",true,true); }, this); this.model.on("change:attackRange",this.renderAttackRangeIcon,this); this.model.on("change:pierce",function(){ this.onIconChanged("pierce",false,false); },this); this.model.on("change:trample",function(){ this.onIconChanged("trample",false,false); },this); this.model.on("miss",this.onMissEffect,this); }, onMissEffect:function(){ effectIconMananger.enqueue(this, { icon: "miss-icon" }); }, __refresh:function(){ this._super(); //this.renderAttack(); this.renderIcon("attack"); this.renderIcon("pierce"); this.renderIcon("trample"); } }) <file_sep>/src/game-sprite.js /** * Created by 赢潮 on 2015/3/2. */ var DiscardCardSprite = CardSprite.extend({ ctor: function (options) { options = options || {}; this.model = options.model; var opt = { side: this.model.get("side"), frontImage: this.getFrontImage(), backImage: this.getBackImage() } this._super(opt); this.touchListener = cc.EventListener.create({ event: cc.EventListener.TOUCH_ONE_BY_ONE, swallowTouches: false, onTouchBegan: function (touch, event) { var target = event.getCurrentTarget(); var locationInNode = target.convertToNodeSpace(touch.getLocation()); var s = target.getContentSize(); var rect = cc.rect(0, 0, s.width, s.height); if (cc.rectContainsPoint(rect, locationInNode)) { return true; } return false; }, onTouchMoved: function (touch, event) { }, onTouchEnded: function (touch, event) { var target = event.getCurrentTarget(); var now = (new Date()).getTime(); if ( (Math.abs(now - target.lastTouchTime) < DOUBLE_TAP_TIME_THRESHOLD)) { var e = new cc.EventCustom("double-tap"); e.setUserData(target); cc.eventManager.dispatchEvent(e); } target.lastTouchTime = now; } }); }, onEnter:function(){ this._super(); this.__initEvent(); this.__refresh(); }, onExit:function(){ this._super(); this.model.off(null,null,this); cc.eventManager.removeListener(this.touchListener); }, __refresh:function(){ }, __initEvent:function(){ this.lastTouchTime = 0; cc.eventManager.addListener(this.touchListener, this); }, getFrontImage:function(){ return cc.spriteFrameCache.getSpriteFrame(this.model.get("type")+"-"+this.model.get("name")+"-small.png") }, getBackImage:function(){ return cc.spriteFrameCache.getSpriteFrame(this.model.get("backType")+"-back.png") } }); var BaseCardSprite = CardSprite.extend({ ctor: function (options) { options = options || {}; var swallowEvent = options.swallowEvent || false; var forceToSide = options.forceToSide || null; this.model = options.model; this.setName(this.model.cid); var opt = { side : forceToSide ? forceToSide : this.model.get("side"), frontImage: this.getFrontImage(), backImage: this.getBackImage() } this._super(opt); var self = this; this.touchListener = cc.EventListener.create({ event: cc.EventListener.TOUCH_ONE_BY_ONE, swallowTouches: swallowEvent, onTouchBegan: function (touch, event) { var target = event.getCurrentTarget(); var locationInNode = target.convertToNodeSpace(touch.getLocation()); var s = target.getContentSize(); var rect = cc.rect(0, 0, s.width, s.height); if (cc.rectContainsPoint(rect, locationInNode)) { return true; } return false; }, onTouchMoved: function (touch, event) { }, onTouchEnded: function (touch, event) { var target = event.getCurrentTarget(); var now = (new Date()).getTime(); if (Math.abs(now - target.lastTouchTime) < DOUBLE_TAP_TIME_THRESHOLD) { var e = new cc.EventCustom("double-tap"); e.setUserData(target); cc.eventManager.dispatchEvent(e); } else { if ( self.onClickListener ) { self.onClickListener.call(self.onClickListenerContext); } } target.lastTouchTime = now; } }); this.icons = {}; this.registerIcon( "level", cc.spriteFrameCache.getSpriteFrame(this.model.isMaxLevel() ? "max-level-icon.png" : "level-icon.png"), { x: dimens.hero_icon_offset.x, y: dimens.card_height - dimens.hero_icon_offset.y } ); this.registerIcon( "payMoney", cc.spriteFrameCache.getSpriteFrame("pay-money-icon.png"), { x: dimens.hero_icon_offset.x, y: dimens.card_height - dimens.hero_icon_offset.y - dimens.hero_icon_size.height } ); this.registerIcon( "payScore", cc.spriteFrameCache.getSpriteFrame("pay-score-icon.png"), { x: dimens.hero_icon_offset.x, y: dimens.card_height - dimens.hero_icon_offset.y - dimens.hero_icon_size.height } ); this.registerIcon( "payHp", cc.spriteFrameCache.getSpriteFrame("pay-hp-icon.png"), { x: dimens.hero_icon_offset.x, y: dimens.card_height - dimens.hero_icon_offset.y - dimens.hero_icon_size.height } ); }, registerIcon:function(iconAttribute, image, position , options) { options = options || {}; this.icons[iconAttribute] = { position:position, image: image, showZero: options.showZero || false, buffAttribute : options.buffAttribute, debuffAttribute : options.debuffAttribute, normalColor: options.normalColor || colors.icon_label, buffColor: options.buffColor || cc.color.GREEN, debuffColor: options.debuffColor || colors.icon_debuff }; }, setOnClickListener:function(listener,listenerContext){ this.onClickListener = listener; this.onClickListenerContext = listenerContext; }, setSwallowEvent:function(swallow){ this.touchListener.swallowTouches = swallow; }, __canShowDetail:function(){ return true }, getFrontImage:function(){ return cc.spriteFrameCache.getSpriteFrame(this.model.get("type")+"-"+this.model.get("name")+"-small.png") }, getBackImage:function(){ return cc.spriteFrameCache.getSpriteFrame(this.model.get("backType")+"-back.png") }, onChangeSide:function(){ var side = this.model.get("side"); if ( side === "back" ) { this.model.set("side","front"); } else if ( side === "front" ) { this.model.set("side","back"); } }, onEnter:function(){ this._super(); this.__initEvent(); this.__refresh(); }, onExit:function(){ this.model.off(null,null,this); cc.eventManager.removeListener(this.touchListener); this._super(); }, __refresh:function(){ this.renderIcon("level"); this.renderIcon("payMoney"); this.renderIcon("payHp"); this.renderIcon("payScore"); }, __initEvent:function(){ this.model.on("change:level",function(){ this.onIconChanged("level", this.icons.level.concernIncrease, this.icons.level.concernDecrease); if ( this.model.isMaxLevel() && this.model.previous("level") < this.model.get("maxLevel") ) { if ( this.icons.level.icon ) { this.icons.level.icon.setIcon(cc.spriteFrameCache.getSpriteFrame("max-level-icon.png")); } } },this); this.model.on("change:payMoney",function(){ this.onIconChanged("payMoney", true, true); },this); this.model.on("change:payHp",function(){ this.onIconChanged("payHp", true, true); },this); this.model.on("change:payScore",function(){ this.onIconChanged("payScore", true, true); },this); this.model.on("give",this.onGiveIcon,this); this.model.on("take",this.onTakeIcon,this); this.lastTouchTime = 0; cc.eventManager.addListener(this.touchListener,this); }, onGiveIcon:function(options){ effectIconMananger.fly( this, iconSource[options.icon], { icon: options.icon, text: options.text }); }, onTakeIcon:function(options){ effectIconMananger.fly( iconSource[options.icon], this, { icon: options.icon, text: options.text }); }, // renderLevel:function(){ // this.levelIcon.setString(this.model.get("level")) // }, onSelectTarget:function(heroModel){ this.model.onSelectTarget(heroModel); }, renderIconStringColor:function(entry){ if ( entry.buffAttribute && entry.debuffAttribute ) { var diff = this.model.get(entry.buffAttribute) - this.model.get(entry.debuffAttribute); if ( diff > 0 ) { entry.icon.setFontColor(entry.buffColor); } else if ( diff < 0 ) { entry.icon.setFontColor(entry.debuffColor); } else { entry.icon.setFontColor(entry.normalColor); } } else { entry.icon.setFontColor(entry.normalColor); } }, renderIcon:function(attr){ var entry = this.icons[attr]; if ( !entry ) return; var stat = this.model.get(attr); if ( stat !== false && (entry.showZero || stat !== 0) && stat !== undefined ) { if ( entry.icon ) { if ( stat !== true ) { entry.icon.setString(stat); this.renderIconStringColor(entry); } } else { var iconSprite = entry.icon = new IconSprite({ image: this.icons[attr].image }); iconSprite.attr ( this.icons[attr].position ) if ( stat !== true ) { iconSprite.setString(stat); this.renderIconStringColor(entry); } this.addChild(iconSprite,1) this.addFrontSprite( iconSprite ); } } else { if ( entry.icon ) { this.removeFrontSprite(entry.icon); entry.icon.removeFromParent(true); entry.icon = null; } } }, onIconChanged:function(attr, needAddEffect, needSubEffect){ this.renderIcon(attr); var stat = this.model.get(attr); if ( this.model.previous(attr) != stat ) { var diff = stat - this.model.previous(attr); var diffStr = diff; if ( diff > 0 ) diffStr = "+"+diff; if ( ( diff > 0 && needAddEffect ) || ( diff < 0 && needSubEffect ) ) { effectIconMananger.enqueue(this, { icon: attr + "-icon", text: diffStr }); } } } }) var IconSprite = cc.Sprite.extend({ ctor: function(options){ options = options || {} var fontSize = options.fontSize || dimens.hero_hp_font_size; var fontColor = options.fontColor || colors.icon_label; var text = options.text || ""; var image = options.image; var offset = options.offset || { x : dimens.hero_icon_size.width/2, y : dimens.hero_icon_size.height/2-1 } this._super(image); this.label = new ccui.Text(text, "Arial", fontSize ); this.label.enableOutline(cc.color.WHITE, 2); this.label.setTextColor(fontColor); this.label.attr({ x: offset.x, y: offset.y }) this.addChild(this.label,1) }, setIcon:function(image){ if ( image instanceof cc.Texture2D ) this.setTexture(image); else if ( image instanceof cc.SpriteFrame ) this.setSpriteFrame(image); }, setString:function(str){ this.label.setString(str) }, setFontColor:function(color){ //this.label.setColor(color); this.label.setTextColor(color); } }) var DeckSprite = cc.Sprite.extend({ ctor: function (options) { options = options || {}; this.__cards = options.array || []; this.countLabelFontSize = options.fontSize || 25; this.countLabelFontColor = options.fontColor || cc.color(255,255,255,255); this.countLabelOffset = options.countLabelOffset || { x: 0, y: 0 }; this.isShowZero = options.isShowZero || false; this.numberFormat = options.numberFormat || "%d"; this.cardClass = options.cardClass || BaseCardSprite; this._super(); this.countLabel = new cc.LabelTTF("", "宋体", this.countLabelFontSize ); this.countLabel.attr({ color: this.countLabelFontColor, x: this.countLabelOffset.x, y: this.countLabelOffset.y }) this.addChild(this.countLabel,2) this.__render(); }, setDiscardDeck:function( deckSprite , autoRefill, refillType ){ this.discardDeck = deckSprite; this.autoRefill = autoRefill; this.refillType = refillType; }, __render:function(){ if ( this.topCardSprite ) { this.removeChild(this.topCardSprite, true); this.topCardSprite = null; } if ( this.__cards.length ) { var lastCard = _.last(this.__cards); this.topCardSprite = new this.cardClass({ model: lastCard }) this.topCardSprite.attr({ x: 0, y: 0 }) this.addChild(this.topCardSprite); } if ( ( this.__cards.length === 0 && this.isShowZero ) || this.__cards.length ) { this.countLabel.setString( this.numberFormat.replace("%d", this.__cards.length )); } else { this.countLabel.setString(""); } }, drawCard:function(callback, context){ if ( this.__cards.length ) { var card = this.__cards.pop(); callback.call(context, this.modelToSprite(card) ); this.__render(); } else if ( this.discardDeck && this.autoRefill && this.discardDeck.__cards.length ) { var tempCards = this.discardDeck.getCards(); if ( this.refillType === "shuffle" ) { tempCards = _.shuffle( tempCards ); } _.each(tempCards,function(model){ this.__cards.push( model ); },this); _.each(this.__cards,function(cardModel){ cardModel.set("side","back"); },this); this.discardDeck.empty(); var card = this.__cards.pop(); callback.call(context, this.modelToSprite(card) ); this.__render(); } else { callback.call(context, null); // nothing to draw } }, modelToSprite:function(model){ return new this.cardClass({ model: model, side : model.get("side") }); }, putCard:function(cardSpriteOrModel){ if ( cardSpriteOrModel instanceof cc.Sprite ) { this.__cards.push(cardSpriteOrModel.model); cardSpriteOrModel.removeFromParent(true); cardSpriteOrModel = null; } else if ( cardSpriteOrModel instanceof Backbone.Model ) { this.__cards.push(cardSpriteOrModel); } this.__render(); }, shuffle:function( callback, context ){ var temp = _.shuffle(this.__cards); this.__cards.splice(0, temp.length); _.each( temp, function(model){ this.__cards.push(model); },this); if ( callback ) callback.call(context); this.__render(); }, empty:function( ) { this.__cards.splice(0, this.__cards.length); this.__render(); }, getCards:function(){ return this.__cards; }, cullCard:function(cardModel){ var index = _.indexOf(this.__cards, cardModel); if ( index != -1 ) { this.__cards.splice(index, 1); this.__render(); } } }) var DungeonDeckSprite = DeckSprite.extend({ modelToSprite:function(model){ return new DUNGEON_SPRITE_CLASS_MAP[model.get("name")]({ model: model }); } }) var EffectIconManager = Backbone.Model.extend({ initialize:function(options){ this.layer = options.layer; this.iconZindex = options.zindex || 100; this.iconMap = {}; this.queueMap = {}; }, enqueue:function(sprite, options){ options = options || {}; if ( !this.queueMap[ sprite.__instanceId ] ) this.queueMap[sprite.__instanceId] = []; this.queueMap[sprite.__instanceId].push( { icon: options.icon, text: options.text || "", offset: options.offset || {x:0, y:0} }); this._popEffect(sprite); }, fly:function(fromSprite, toSprite, options ) { options = options || {}; var moveTime = options.time || times.default_icon_fly; var fromOffset = options.fromOffset || {x:0,y:0}; var toOffset = options.toOffset || {x:0,y:0}; var icon = new IconSprite({ text: options.text, image: cc.spriteFrameCache.getSpriteFrame(options.icon+"-icon.png") }); var fromBox = fromSprite.getBoundingBoxToWorld(); icon.attr({ x : fromBox.x + fromSprite.width/2 + fromOffset.x, y : fromBox.y + fromSprite.height/2 + fromOffset.y }); this.layer.addChild( icon, this.iconZindex ); var toBox = toSprite.getBoundingBoxToWorld(); var sequence = cc.sequence( cc.moveTo(moveTime, toBox.x + toSprite.width/2 + toOffset.x, toBox.y + toSprite.height/2 + toOffset.y ), cc.callFunc(function(){ icon.removeFromParent(true); if ( options.callback ) options.callback.call(options.context); },this)); icon.runAction(sequence); }, _isIconRunning:function(sprite){ if ( this.iconMap[sprite.__instanceId] ) { return true; } return false; }, _popEffect:function(sprite){ if ( !this._isIconRunning(sprite) ) { var entry = this.queueMap[sprite.__instanceId].shift(); if ( entry === undefined ) return; this.iconMap[sprite.__instanceId] = new IconSprite({ text: entry.text, image: cc.spriteFrameCache.getSpriteFrame(entry.icon+".png") }); this.layer.addChild( this.iconMap[sprite.__instanceId], this.iconZindex ); var box = sprite.getBoundingBoxToWorld(); this.iconMap[sprite.__instanceId].attr({ x: box.x+sprite.width/2 + entry.offset.x, y: box.y+sprite.height/2 + entry.offset.y }) var sequence = cc.sequence( cc.moveBy( times.effect_icon_move, 0, dimens.effect_icon_move_y), cc.callFunc(function(){ this.iconMap[sprite.__instanceId].removeFromParent(true); this.iconMap[sprite.__instanceId] = null; this._popEffect(sprite); },this)); this.iconMap[sprite.__instanceId].runAction(sequence); } } }) <file_sep>/src/card-detail.js /** * Created by 赢潮 on 2015/3/23. */ var CardDetailLayer = cc.LayerColor.extend({ ctor: function (options) { options = options || {}; var hint = options.hint; var choices = options.choices; this.model = options.model; this._super(colors.card_detail_mask); var scaleRate = dimens.card_detail_scale_rate; var iconScaleRate = dimens.card_detail_icon_scale_rate; var card = new cc.Sprite(cc.spriteFrameCache.getSpriteFrame(this.model.get("type")+"-"+this.model.get("name")+"-small.png")); card.attr({ x: cc.winSize.width/2, y: cc.winSize.height/2, scaleX: dimens.card_detail_scale_rate, scaleY: dimens.card_detail_scale_rate }) this.addChild(card,11) var cardLeft = cc.winSize.width/2 - dimens.card_width * scaleRate/2; var cardBottom = cc.winSize.height/2 - dimens.card_height * scaleRate/2; var name = this.model.get("displayName"); var nameLength = unicodeByteLength(name); var fontSize = dimens.card_detail_name_font_size; if ( nameLength >= 12 ) { fontSize = dimens.card_detail_name_font_size * 4 / 6; } else if ( nameLength >= 10 ) { fontSize = dimens.card_detail_name_font_size * 4 / 5; } var nameLabel = new ccui.Text(name, "Arial", fontSize ); nameLabel.enableOutline(cc.color.WHITE, 4); nameLabel.setTextColor(colors.card_detail_name); nameLabel.attr({ x: cc.winSize.width/2, y: cc.winSize.height/2 + dimens.card_height/2*scaleRate - dimens.card_detail_name_font_size, anchorX: 0.5, anchorY: 0.5 }) this.addChild(nameLabel,15); var levelIcon = new IconSprite({ image: this.model.isMaxLevel() ? cc.spriteFrameCache.getSpriteFrame("max-level-icon.png") : cc.spriteFrameCache.getSpriteFrame("level-icon.png") }); levelIcon.attr({ scaleX: iconScaleRate, scaleY: iconScaleRate, x: cardLeft + dimens.card_detail_icon_offset.x*scaleRate, y: cardBottom + (dimens.card_height - dimens.card_detail_icon_offset.y)*scaleRate }); levelIcon.setString(this.model.get("level")); this.addChild(levelIcon,15); if ( this.model.get("maxLevel") !== "NA" ) { var maxLevelIcon = new IconSprite({ image: cc.spriteFrameCache.getSpriteFrame("level-icon.png"), fontSize: 12, offset: { x: dimens.hero_icon_size.width/2, y: dimens.hero_icon_size.height/2-3 } }); maxLevelIcon.attr({ scaleX: iconScaleRate, scaleY: iconScaleRate, x: cardLeft + dimens.card_detail_icon_offset.x * scaleRate, y: cardBottom + (dimens.card_height - dimens.card_detail_icon_offset.y - 19) * scaleRate }); maxLevelIcon.setString("最大" + this.model.get("maxLevel")); this.addChild(maxLevelIcon, 14); } if ( this.model instanceof HeroModel ) { var hpIcon = new IconSprite({ image: cc.spriteFrameCache.getSpriteFrame("hp-icon.png") }) hpIcon.attr({ scaleX: iconScaleRate, scaleY: iconScaleRate, x: cardLeft + ( dimens.card_width - dimens.card_detail_icon_offset.x )*scaleRate, y: cardBottom + (dimens.card_height - dimens.card_detail_icon_offset.y)*scaleRate }) this.addChild(hpIcon,15); hpIcon.setString(this.model.get("hp")); var maxHpIcon = new IconSprite({ image: cc.spriteFrameCache.getSpriteFrame("hp-icon.png"), fontSize: 12 }); maxHpIcon.attr({ scaleX: iconScaleRate, scaleY: iconScaleRate, x: cardLeft + ( dimens.card_width - dimens.card_detail_icon_offset.x )*scaleRate, y: cardBottom + (dimens.card_height - dimens.card_detail_icon_offset.y-19)*scaleRate }); maxHpIcon.setString("最大" + this.model.get("maxHp")); this.addChild(maxHpIcon, 14); } else if ( this.model instanceof MonsterModel || this.model instanceof TrapModel ){ var attackIcon = new IconSprite({ image: cc.spriteFrameCache.getSpriteFrame("attack-icon.png") }) attackIcon.attr({ scaleX: iconScaleRate, scaleY: iconScaleRate, x: cardLeft + ( dimens.card_width - dimens.card_detail_icon_offset.x )*scaleRate, y: cardBottom + (dimens.card_height - dimens.card_detail_icon_offset.y)*scaleRate }) this.addChild(attackIcon,15); attackIcon.setString(this.model.get("attack")); } else if ( this.model instanceof SpellModel ){ var attackIcon = new IconSprite({ image: cc.spriteFrameCache.getSpriteFrame("attack-icon.png") }) attackIcon.attr({ scaleX: iconScaleRate, scaleY: iconScaleRate, x: cardLeft + ( dimens.card_width - dimens.card_detail_icon_offset.x )*scaleRate, y: cardBottom + (dimens.card_height - dimens.card_detail_icon_offset.y)*scaleRate }) this.addChild(attackIcon,15); attackIcon.setString(this.model.get("attack")); } if ( choices && choices.length ) { var choiceNumber = choices.length; var unitWidth = cc.winSize.width / choiceNumber; var menuX = unitWidth/2; var items = []; _.each( choices, function(choice){ var item = new cc.MenuItemImage( cc.spriteFrameCache.getSpriteFrame("short-normal.png"), cc.spriteFrameCache.getSpriteFrame("short-selected.png"), function () { //cc.log( choice.text); if ( choice.callback ) choice.callback.call( choice.context ); }, this ); item.attr({ x: menuX, y: 60, anchorX: 0.5, anchorY: 0.5 }); var text = buildRichText({ str : choice.text , fontSize : dimens.build_new_stage_font_size, fontColor: cc.color.BLACK, width: 180, height: 60 }); text.attr({ x: choice.textOffset ? choice.textOffset.x : 120, y: choice.textOffset ? choice.textOffset.y : 15, anchorX : 0.5, anchorY : 0.5 }) item.addChild( text ); items.push( item ); menuX += unitWidth; }, this ) var menu = new cc.Menu(items); menu.x = 0; menu.y = 0; this.addChild(menu, 20); } if ( hint ) { var richText = buildRichText({ str: hint, fontSize: dimens.card_detail_desc_font_size, fontColor: colors.card_detail_hint, width: dimens.card_detail_hint_size.width, height: dimens.card_detail_hint_size.height }); richText.attr({ x: dimens.card_detail_hint_position.x, y: dimens.card_detail_hint_position.y }); this.addChild(richText, 15); } var desc = this.model.getDescription(); if ( desc && desc != "" ) { var desc_mask = new cc.Sprite(cc.spriteFrameCache.getSpriteFrame("card-desc-bg.png")); desc_mask.attr({ x: cc.winSize.width/2, y: dimens.card_detail_desc_mask_position.y, scaleX: dimens.card_detail_scale_rate, scaleY: dimens.card_detail_scale_rate, opacity: 188 }) this.addChild(desc_mask,12); var descLines = desc.split("\n"); var descY = dimens.card_detail_desc_text_start_y; _.each(descLines,function(line){ var richText = buildRichText({ str: line, fontSize: dimens.card_detail_desc_font_size, fontColor: colors.card_detail_desc, width: dimens.card_detail_desc_size.width, height: dimens.card_detail_desc_size.height }); richText.attr({ x: cc.winSize.width/2, y: descY }); this.addChild(richText, 15); descY -= dimens.card_detail_desc_line_space; },this) } }, onEnter:function(){ this._super(); this.__initEvent(); }, onExit:function(){ this._super(); cc.eventManager.removeListener(this.touchListener); }, __initEvent:function(){ var self = this; cc.eventManager.addListener(this.touchListener = cc.EventListener.create({ event: cc.EventListener.TOUCH_ONE_BY_ONE, swallowTouches: true, onTouchBegan: function (touch, event) { return true; }, onTouchMoved: function (touch, event) { }, onTouchEnded: function (touch, event) { //cc.director.popScene(); self.close.call(self); } }), this); }, close:function(){ window.mainGame.resumeAction(); this.removeAllChildren(true); this.removeFromParent(true); } });<file_sep>/src/room-card-sprite.js /** * Created by 赢潮 on 2015/4/12. */ var RoomCardSprite = BaseCardSprite.extend({ });<file_sep>/src/game-over.js /** * Created by 赢潮 on 2015/4/28. */ var GameOverLayer = cc.LayerColor.extend({ ctor: function (options) { options = options || {}; gameModel.off(); this._super(colors.card_detail_mask); var gameOver = new cc.LabelTTF(texts.game_over, "宋体", dimens.game_over_font_size); gameOver.attr({ color: colors.game_over, x: cc.winSize.width/2, y: 950 }) this.addChild(gameOver); var score = buildRichText({ str: "Lv"+gameModel.get("level")+" {[score]}"+gameModel.get("score"), fontSize:dimens.game_over_score_font_size }); score.attr({ x: cc.winSize.width/2, y: 800 }) this.addChild(score); var pleaseInputName = new cc.LabelTTF("伟大的城主大人,请留下大名", "宋体", dimens.game_over_score_font_size); pleaseInputName.attr({ color: colors.game_over, x: cc.winSize.width/2, y: 680 }) this.addChild(pleaseInputName); var textFieldBg = new cc.Sprite(cc.spriteFrameCache.getSpriteFrame("long-normal.png")); textFieldBg.attr({ x: cc.winSize.width/2, y: 555 }); this.addChild(textFieldBg); var textField = new ccui.TextField(); textField.setTouchEnabled(true); textField.fontName = "宋体"; textField.fontSize = dimens.game_over_score_font_size; textField.placeHolder = "请输入城主大名"; textField.setTextColor(cc.color.BLACK); textField.setMaxLength(9); textField.x = cc.winSize.width / 2.0; textField.y = 550; textField.addEventListener(this.textFieldEvent, this); this.addChild(textField,5); this.textField = textField; var name; var store = cc.sys.localStorage.getItem("name"); if ( store != null ){ name = store; cc.log("stored name"+name); textField.setString(name) } else { textField.setString("") } var continueItem = new cc.MenuItemImage( cc.spriteFrameCache.getSpriteFrame("short-normal.png"), cc.spriteFrameCache.getSpriteFrame("short-selected.png"), function () { name = this.textField.getString(); if ( name && name.trim() !== "" ) { cc.sys.localStorage.setItem("name",name.trim()); gameModel.set("playerName",name.trim()); this.getParent().addChild(new ScoreBoardLayer()); this.removeFromParent(true); } }, this ); continueItem.attr({ x: cc.winSize.width / 2.0, y: 50, anchorX: 0.5, anchorY: 0.5 }); var continueText = new cc.LabelTTF(texts.confirm, "宋体", dimens.game_over_score_font_size); continueText.attr({ color: cc.color.BLACK, x: 85, y: 25 }); continueItem.addChild( continueText ); var allCardItem = new cc.MenuItemImage( cc.spriteFrameCache.getSpriteFrame("short-normal.png"), cc.spriteFrameCache.getSpriteFrame("short-selected.png"), function () { this.showAllCards(); }, this ); allCardItem.attr({ x: cc.winSize.width / 2.0, y: 250, anchorX: 0.5, anchorY: 0.5 }); var allCardText = new cc.LabelTTF("查看牌库", "宋体", dimens.game_over_score_font_size); allCardText.attr({ color: cc.color.BLACK, x: 85, y: 25 }); allCardItem.addChild( allCardText ); var continueMenu = new cc.Menu(continueItem,allCardItem); continueMenu.x = 0; continueMenu.y = 0; this.addChild(continueMenu, 20); }, textFieldEvent: function (sender, type) { switch (type) { case ccui.TextField.EVENT_ATTACH_WITH_IME: this.textField.runAction(cc.moveBy(0.225, cc.p(0, 10))); break; case ccui.TextField.EVENT_DETACH_WITH_IME: this.textField.runAction(cc.moveBy(0.175, cc.p(0, -10))); break; case ccui.TextField.EVENT_INSERT_TEXT: break; case ccui.TextField.EVENT_DELETE_BACKWARD: break; default: break; } }, showAllCards:function(){ cc.director.pushScene(new ChooseCardScene({ model: gameModel, range: ["discard", "deck", "dungeon", "hand"], hint: "你的牌库", validFilter:function(){ return false } })); } }); var FIREBASE_URL = "https://dungeon-deck.firebaseio.com" var TOP_SCORE_COUNT = 25 var ScoreBoardLayer = cc.LayerColor.extend({ ctor:function (options) { this._super(cc.color.WHITE); this.scoreQuery = new Firebase(FIREBASE_URL+"/score").endAt().limit(TOP_SCORE_COUNT); this.scoreRef = this.scoreQuery.ref(); var self = this; this.score = null; this.__initList2(); if ( gameModel ) { var score = { name : gameModel.get("playerName"), ".priority": gameModel.get("score"), level: gameModel.get("level"), score : gameModel.get("score"), timestamp: Firebase.ServerValue.TIMESTAMP, r: Math.random() } this.score = score; this.scoreRef.push(score, function(){ cc.log("score upload complete"); self.__fetchScore.call(self); }) } else { this.__fetchScore.call(self); } var scoreBoardTitle = new cc.LabelTTF("排行榜", "宋体", dimens.game_over_score_font_size); scoreBoardTitle.attr({ color: cc.color.BLACK, x: cc.winSize.width/2, y: 1100 }) this.addChild(scoreBoardTitle); this.loading = new cc.LabelTTF("加载中……", "宋体", dimens.loading_score_board_font); this.loading.attr({ color: cc.color.BLACK, x: cc.winSize.width/2, y: cc.winSize.height/2 }) this.addChild(this.loading); var continueItem = new cc.MenuItemImage( cc.spriteFrameCache.getSpriteFrame("short-normal.png"), cc.spriteFrameCache.getSpriteFrame("short-selected.png"), function () { cc.log("restart") window.gameModel = null; cc.director.runScene(window.mainGame = new MainGameScene()); }, this ); continueItem.attr({ x: cc.winSize.width / 2.0, y: 50, anchorX: 0.5, anchorY: 0.5 }); var continueText = new cc.LabelTTF(texts.restart, "宋体", dimens.game_over_score_font_size); continueText.attr({ color: cc.color.BLACK, x: 85, y: 25 }); continueItem.addChild( continueText ); var continueMenu = new cc.Menu(continueItem); continueMenu.x = 0; continueMenu.y = 0; this.addChild(continueMenu, 20); }, __fetchScore:function(){ var self = this; this.scoreQuery.once("value",function(snapshot){ self.scores = snapshot.val(); var filteredScore = []; _.each(self.scores,function(score){ if ( score.name ) { filteredScore.unshift(score); } }); self.scores = filteredScore; self.loading.removeFromParent(true); self.__renderList2.call(self); }) }, __initList2:function(){ var listView = new ccui.ListView(); // set list view ex direction listView.setDirection(ccui.ScrollView.DIR_VERTICAL); listView.setTouchEnabled(true); listView.setBounceEnabled(true); //listView.setBackGroundImage("res/cocosui/green_edit.png"); //listView.setBackGroundImageScale9Enabled(true); var innerWidth = dimens.score_board_width; var innerHeight = dimens.score_board_height; listView.setContentSize(cc.size(innerWidth, innerHeight)); listView.attr({ x: (cc.winSize.width-innerWidth)/2, y: (cc.winSize.height-innerHeight)/2 }) this.addChild(listView,2); // create model var default_label = new ccui.Text("","Arial", dimens.score_line_font_size); default_label.setName("ScoreLabel"); default_label.setTouchEnabled(false); var default_item = new ccui.Layout(); default_item.setTouchEnabled(false); default_item.setContentSize(default_label.getContentSize()); default_item.width = listView.width; default_label.x = default_item.width / 2; default_label.y = default_item.height / 2; default_item.addChild(default_label); default_item.attr({ height: dimens.score_line_height }) // set model listView.setItemModel(default_item); this.listView = listView; }, __initList: function(){ var size = cc.winSize // var coverBackground =new cc.LayerColor(cc.color(0,0,0,255)) // //center // coverBackground.attr({ // x: 0, // y: 0, // width: cc.winSize.width, // height: cc.winSize.height, // anchorX : 0.5, // anchorY : 0.5 // }); // this.addChild(coverBackground, -1); // Create the scrollview this.scrollView = new ccui.ScrollView(); this.scrollView.setDirection(ccui.ScrollView.DIR_VERTICAL); this.scrollView.setTouchEnabled(true); this.scrollView.setContentSize(cc.size(dimens.score_board_width,dimens.score_board_height)); this.scrollView.x = 0; this.scrollView.y = 60; this.addChild(this.scrollView,2) }, __renderList2:function(){ var listView = this.listView; var count = this.scores.length; _.each(this.scores,function(score) { listView.pushBackDefaultItem(); },this); // set item data var foundMyself = false; var i = 0; _.each(this.scores,function(score){ var color; if (score.r == this.score.r) { foundMyself = true } var item = listView.getItem(i); var label = item.getChildByName("ScoreLabel"); this.generateOneScoreLabel(score, label); i++; },this); if ( !foundMyself ) { listView.pushBackDefaultItem(); listView.pushBackDefaultItem(); var item = listView.getItem(i); var label = item.getChildByName("ScoreLabel"); label.setTextColor(cc.color.BLACK); label.setString("……"); i++; var item = listView.getItem(i); var label = item.getChildByName("ScoreLabel"); this.generateOneScoreLabel(this.score, label); } }, generateOneScoreLabel:function(score, label){ var color; if (score.r == this.score.r) { color = cc.color(255, 0, 0, 255); } else color = cc.color.BLACK; var str = score.name; for ( var j = dbcsByteLength(str); j < 20; j++ ){ str += " "; } str += "lv"+(score.level||1); for ( var j = dbcsByteLength(str); j < 26; j++ ){ str += " "; } str += score.score + "分" for ( var j = dbcsByteLength(str); j < 36; j++ ){ str += " "; } str += moment(score.timestamp).locale("zh-cn").fromNow(); label.setTextColor(color); label.setString(str); }, __renderList:function(){ var i = 0; var length = _.size(this.scores) var innerWidth = this.scrollView.width; var innerHeight = (TOP_SCORE_COUNT+2)*dimens.score_line_height; this.scrollView.setInnerContainerSize(cc.size(innerWidth, innerHeight)); this.startHeight = ( TOP_SCORE_COUNT - length + 2 )*dimens.score_line_height; var foundMyself = false; _.each(this.scores,function(score){ if ( score.name ) { var color; if (score.r == this.score.r) { foundMyself = true } this.generateOneScore(score,i); i++; } },this); if ( !foundMyself ) { var nameLabel = new cc.LabelTTF("……", "宋体", dimens.score_line_font_size); nameLabel.attr({ color: cc.color.WHITE, x: 10, y: dimens.score_line_height + 10, anchorX: 0, anchorY: 0 }); this.scrollView.addChild(nameLabel); this.generateOneScore(this.score,-2); } }, generateOneScore:function(score, i){ var color; if (score.r == this.score.r) { color = cc.color(255, 0, 0, 255); } else color = cc.color.BLACK; var str = score.name; for ( var j = dbcsByteLength(str); j < 20; j++ ){ str += " "; } str += "lv"+(score.level||1); for ( var j = dbcsByteLength(str); j < 26; j++ ){ str += " "; } str += score.score + "分" for ( var j = dbcsByteLength(str); j < 36; j++ ){ str += " "; } str += moment(score.timestamp).locale("zh-cn").fromNow(); var nameLabel = new cc.LabelTTF(str, "宋体", dimens.score_line_font_size); nameLabel.attr({ color: color, x: 10, y: (2 + i) * (dimens.score_line_height) + 10 + this.startHeight, anchorX: 0, anchorY: 0 }); this.scrollView.addChild(nameLabel); } }) var GameOverScene = cc.Scene.extend({ ctor:function(options){ this._super(); this.options = options || {}; }, onEnter:function (options) { this._super(); var layer = new GameOverLayer(); this.addChild(layer); } });<file_sep>/src/buy-card.js /** * Created by 赢潮 on 2015/3/25. */ var BUYABLE_CARD_PER_ROW = 4; var BuyCardLayer = cc.LayerColor.extend({ ctor: function (options) { options = options || {}; this._super(colors.card_detail_mask); this.model = options.model; this.initRegular(); this.initFlow(); this.__initUI(); }, __initUI:function(){ var cancelItem = new cc.MenuItemImage( cc.spriteFrameCache.getSpriteFrame("short-normal.png"), cc.spriteFrameCache.getSpriteFrame("short-selected.png"), function () { this.close(); }, this ); cancelItem.attr({ x: dimens.cancel_buy_position.x, y: dimens.cancel_buy_position.y, anchorX: 0.5, anchorY: 0.5 }); var cancelText = new cc.LabelTTF(texts.cancel, "宋体", dimens.cancel_buy_font_size); cancelText.attr({ color: colors.cancel_buy, x: 90, y: 25 }) cancelItem.addChild( cancelText ); var cancelMenu = new cc.Menu(cancelItem); cancelMenu.x = 0; cancelMenu.y = 0; this.addChild(cancelMenu, 5); }, close:function(){ /*mainGame.resumeAction(); this.removeFromParent(true);*/ cc.director.popScene(); }, initRegular:function(){ var buyItems = []; var layerHeight = cc.winSize.height - dimens.top_bar_height - dimens.cancel_buy_height; var row = Math.ceil( this.model.get("regularBuyableCards").length / BUYABLE_CARD_PER_ROW ) + this.model.get("flowBuyableCardLines").length; var marginY = Math.floor( layerHeight / row ); var marginX = Math.floor( cc.winSize.width / BUYABLE_CARD_PER_ROW ); var y = layerHeight - marginY/2 + dimens.cancel_buy_height + 25; var x = marginX/2; var i = 0; _.each( this.model.get("regularBuyableCards"), function(deck){ if ( !deck.length ) return; var cardModel = _.first(deck); var deckSprite = new DungeonDeckSprite({ array: deck, side: "front", fontSize : dimens.buyable_deck_count_font_size, countLabelOffset: { x: dimens.card_width/2-dimens.hero_icon_offset.x, y: -dimens.card_height/2 }, numberFormat: "×%d", cardClass: DUNGEON_SPRITE_CLASS_MAP[cardModel.get("name")] }); deckSprite.attr({ x: x, y: y }); this.addChild(deckSprite); var cost = cardModel.get("cost"); var icon = new IconSprite({ image: cc.spriteFrameCache.getSpriteFrame("money-icon.png"), text: cost, fontSize: dimens.buyable_deck_count_font_size, offset: { x: dimens.hero_icon_size.width/2-1, y: dimens.hero_icon_size.height/2-5 } }); icon.attr({ x: -dimens.card_width/2 + dimens.hero_icon_offset.x, y: -dimens.card_height/2 + dimens.hero_icon_offset.y - 10 }) deckSprite.addChild(icon); if ( cost <= this.model.get("money") ) { (function(cardModel, x, y, deck){ var cost = cardModel.get("cost"); var buyItem = new cc.MenuItemImage( cc.spriteFrameCache.getSpriteFrame("short-normal.png"), cc.spriteFrameCache.getSpriteFrame("short-selected.png"), function () { if (cost <= window.gameModel.get("money")) { window.gameModel.useMoney(cost); deck.splice(0,1); window.newDiscardCardModel = cardModel; window.newDiscardCardPosition = { x: x, y: y } window.newDiscardCardModel.onGain(); this.close(); } }, this); buyItem.attr({ x: x - 2, y: y - dimens.card_height / 2 - 43, anchorX: 0.5, anchorY: 0.5, scaleX: 0.7, scaleY: 0.8 }); var buyText = new cc.LabelTTF(texts.buy, "宋体", dimens.buy_font_size); buyText.attr({ color: colors.buy, x: x, y: y - dimens.card_height / 2 - 48 }); this.addChild(buyText,10); buyItems.push(buyItem); }).call(this, cardModel, x, y, deck); } x += marginX; i++; if ( i >= BUYABLE_CARD_PER_ROW ) { x = marginX/2; y -= marginY; i = 0; } },this); var buyMenu = new cc.Menu(buyItems); buyMenu.x = 0; buyMenu.y = 0; this.addChild(buyMenu, 5); }, initFlow:function(){ var buyItems = []; var layerHeight = cc.winSize.height - dimens.top_bar_height - dimens.cancel_buy_height; var row = Math.ceil( this.model.get("regularBuyableCards").length / BUYABLE_CARD_PER_ROW ) + this.model.get("flowBuyableCardLines").length; var marginY = Math.floor( layerHeight / row ); var marginX = Math.floor( cc.winSize.width / BUYABLE_CARD_PER_ROW ); var y = layerHeight - marginY/2 + dimens.cancel_buy_height + 25 - (Math.ceil( this.model.get("regularBuyableCards").length / BUYABLE_CARD_PER_ROW )*marginY); var x = marginX/2; _.each(this.model.get("flowBuyableCardLines"),function(line){ var i = 0; _.each(line,function(cardModel){ var arrow; if ( i === 0 ) { } else { arrow = new cc.Sprite(cc.spriteFrameCache.getSpriteFrame("flow-left.png")); arrow.attr({ x: x-marginX/2, y: y-20 }); this.addChild(arrow); } if ( cardModel == null ) { i++; x += marginX; return; } var cardSprite = new DUNGEON_SPRITE_CLASS_MAP[cardModel.get("name")]({ side: "front", model: cardModel }); cardSprite.attr({ x: x, y: y }); this.addChild(cardSprite); var cost = cardModel.get("cost"); var icon = new IconSprite({ image: cc.spriteFrameCache.getSpriteFrame("money-icon.png"), text: cost, fontSize: dimens.buyable_deck_count_font_size, offset: { x: dimens.hero_icon_size.width/2-1, y: dimens.hero_icon_size.height/2-5 } }); icon.attr({ x: dimens.hero_icon_offset.x, y: dimens.hero_icon_offset.y - 10 }) cardSprite.addChild(icon); if ( cost <= this.model.get("money") ) { (function(cardModel, x, y, line, index){ var cost = cardModel.get("cost"); var buyItem = new cc.MenuItemImage( cc.spriteFrameCache.getSpriteFrame("short-normal.png"), cc.spriteFrameCache.getSpriteFrame("short-selected.png"), function () { if (cost <= window.gameModel.get("money")) { window.gameModel.useMoney(cost); window.newDiscardCardModel = cardModel; window.newDiscardCardPosition = { x: x, y: y } window.newDiscardCardModel.onGain(); line[index] = null; this.close(); } }, this); buyItem.attr({ x: x - 2, y: y - dimens.card_height / 2 - 43, anchorX: 0.5, anchorY: 0.5, scaleX: 0.7, scaleY: 0.8 }); var buyText = new cc.LabelTTF(texts.buy, "宋体", dimens.buy_font_size); buyText.attr({ color: colors.buy, x: x, y: y - dimens.card_height / 2 - 48 }); this.addChild(buyText,10); buyItems.push(buyItem); }).call(this, cardModel, x, y, line, i); } i++; x += marginX; },this); x = marginX/2; y -= marginY; },this) var buyMenu = new cc.Menu(buyItems); buyMenu.x = 0; buyMenu.y = 0; this.addChild(buyMenu, 5); } }); var BuyCardScene = cc.Scene.extend({ ctor:function(options){ this._super(); this.options = options || {}; }, onEnter:function (options) { this._super(); var layer = new BuyCardLayer({model:this.options.model}); this.addChild(layer); var uiLayer = new UILayer({model:window.gameModel}); this.addChild(uiLayer,100); } });<file_sep>/src/hero-card-model.js /** * Created by 赢潮 on 2015/2/25. */ var HeroModel = Backbone.Model.extend({ //英雄牌 defaults:function(){ return { name: "", type:"hero", backType:"hero", displayName: "", baseMaxHp: 1, maxHp: 1, hp: 1, baseScore: 1, score: 1, baseDefense: 0, defense: 0, defenseBuff: 0, defenseDebuff: 0, level: 1, maxLevel: 3, positionInTeam: null, attackHeartPower: 1, poison: 0, slow: 0, silent: 0, poisonReduce: 1, poisonResistance: 0, slowReduce: 1, slowResistance: 1, silentReduce: 1, silentResistance: 0, bite: false, dodge:{ }, carry: [ "potion" ], skills : {} } }, initialize:function(){ this.__joinTeamOver = false; this.initByLevel(); this.evaluateMaxHp(); this.evaluateScore(); this.evaluateDefense(); this.set("maxHp",this.get("baseMaxHp"), {silent:true}); this.set("hp",this.get("maxHp"), {silent:true}); this.__initEvent(); }, __initEvent:function(){ this.on("change:hp",this.onChangeHp,this); this.on("change:level",this.onChangeLevel,this); this.on("change:baseScore", this.evaluateScore, this); this.on("change:baseMaxHp", this.evaluateMaxHp, this); this.on("change:baseDefense change:defenseBuff change:defenseDebuff", this.evaluateDefense, this); }, onChangeHp:function(){ if ( this.get("hp") <= 0 ) { window.gameModel.getScore( this.get("score")); window.gameModel.getExp( this.getExp() ); this.onDie(); if ( this.get("bite") ) { this.trigger("transform"); } else { this.trigger("die"); } } else if ( this.previous("hp") <= 0 ) { cc.log("alive"); this.trigger("alive"); this.onAlive(); } }, onChangeLevel:function(){ this.initByLevel(); }, evaluateScore:function(){ this.set("score", this.get("baseScore")) }, evaluateMaxHp:function(){ this.set("maxHp", this.get("baseMaxHp")); }, evaluateDefense:function(){ this.set("defense", Math.max(0, this.get("baseDefense") + this.get("defenseBuff") - this.get("defenseDebuff"))); }, getDescription:function(){ var desc = []; desc.push( "英雄" ); if ( this.get("score") ) { desc.push( "{[score]}杀死英雄得到"+this.get("score")+"分和"+this.getExp()+"经验"); } if ( this.get("defense") ) { desc.push( "{[defense]}怪物对该英雄的伤害减"+this.get("defense")); } if ( this.get("slow") ) { desc.push( "{[slow]}迟缓("+this.get("slow")+"轮)被同一个怪物攻击2次"); } if ( this.get("poison") ) { desc.push( "{[poison]}中毒("+this.get("poison")+"轮)每经过1间房间-1{[hp]}"); } if ( this.get("silent") ) { desc.push( "{[silent]}封印("+this.get("silent")+"轮)不能使用主动技能"); } var dodges = this.get("dodge"); if ( dodges.trap ) { desc.push( (dodges.trap)+"%不受陷阱影响"); } if ( dodges.att1 ) { desc.push( (dodges.att1 )+"%躲避{[attack]}1及以下的怪物攻击"); } if ( dodges.att2 ) { desc.push( (dodges.att2 )+"%躲避{[attack]}2及以下的怪物攻击"); } if ( dodges.att3 ) { desc.push( (dodges.att3 )+"%躲避{[attack]}3及以下的怪物攻击"); } if ( dodges.att8 ) { desc.push( (dodges.att8 )+"%躲避{[attack]}8及以上的怪物攻击"); } if ( dodges.att7 ) { desc.push( (dodges.att7 )+"%躲避{[attack]}7及以上的怪物攻击"); } if ( dodges.att6 ) { desc.push( (dodges.att6 )+"%躲避{[attack]}6及以上的怪物攻击"); } if ( dodges.att5 ) { desc.push( (dodges.att5 )+"%躲避{[attack]}5及以上的怪物攻击"); } if ( dodges.spell ) { desc.push( (dodges.spell )+"%躲避法术的伤害"); } var skills = this.get("skills"); if ( skills.steal ) { desc.push( "每经过"+skills.steal.maxCoolDown+"间房间,偷走"+skills.steal.effect+"{[money]}" ); } if ( skills.heal ) { desc.push( "每经过"+skills.heal.maxCoolDown+"间房间,回复最前的受伤英雄"+skills.heal.effect+"{[hp]}" ); } if ( skills.resurrection ) { desc.push( "每经过"+skills.resurrection.maxCoolDown+"间房间复活1个死去的英雄并恢复其"+skills.resurrection.effect+"{[hp]}" ); } return desc.join("\n"); }, isMaxLevel:function(){ return this.get("maxLevel") != "NA" && this.get("level") >= this.get("maxLevel"); }, isAlive:function(){ return this.get("hp") > 0; }, onBeforePositionInTeamChange:function(prevPosition){ }, onPositionInTeamChange:function(prevPosition, position){ }, onEnterDungeon:function(){ }, onPassDungeon:function(){ this.resetToOrigin(); var level = this.get("level"); if ( level < this.get("maxLevel") ) { this.set("level", level + 1); } else { this.set("leaving", true); } var hp = this.get("hp"); var maxHp = this.get("maxHp"); var diff = Math.max(0, maxHp - hp); if ( diff > 0 ) { var recovery = gameModel.getTavernRecoveryEffect(diff); if (recovery > 0) { this.set("hp", hp + recovery); this.trigger("give", { icon: "money" }); gameModel.getPayFromTavern(recovery); } } else { this.set("hp",maxHp); } }, resetToOrigin:function(){ this.set({ slow:0, poison: 0, defenseBuff:0, defenseDebuff:0 }); var skills = this.get("skills"); _.each(_.keys(skills), function(key) { var val = skills[key]; val.coolDown = 0; val.maxCoolDown = val.baseMaxCoolDown; }); }, onEnterStage:function(){ }, onEnterRoom:function(roomModel){ }, onPassRoom:function(roomModel){ this.set("bite", false); var poison = this.get("poison"); if ( poison ) { this.onBeDamaged(window.gameModel.get("poisonEffect"),"poison"); this.set("poison", Math.max(0,poison - this.get("poisonReduce")) ); } var slow = this.get("slow"); if ( slow ) { this.set("slow", Math.max(0,slow - this.get("slowReduce")) ); } var silent = this.get("silent"); if ( silent ) { this.set("silent", Math.max(0,silent - this.get("silentReduce")) ); } if ( !this.isAlive() ) return; if ( !silent ) { var skills = this.get("skills"); _.each(_.keys(skills), function (key) { var val = skills[key]; var coolDown = val.coolDown + 1; if (coolDown >= val.maxCoolDown) { val.coolDown = 0; SKILL_FUNC_MAP[key].call(this, val.effect); } else { val.coolDown = coolDown } }, this); } }, getPoison:function(amount){ this.set("poison",this.get("poison")+amount); }, getSlow:function(amount){ this.set("slow",this.get("slow")+amount); }, getSilent:function(amount){ this.set("silent",this.get("silent")+amount); }, onPassStage:function(){ }, onBeAttacked:function(damage,cardModel){ var dodge = this.get("dodge"); var dodgeRate = 0; if ( cardModel instanceof TrapModel ) { if ( dodge.trap ) dodgeRate += dodge.trap; } else if ( cardModel instanceof MonsterModel ) { var att = cardModel.get("attack"); if ( att <= 1 && dodge.att1 ) dodgeRate += dodge.att1; if ( att <= 2 && dodge.att2 ) dodgeRate += dodge.att2; if ( att <= 3 && dodge.att3 ) dodgeRate += dodge.att3; if ( att >= 5 && dodge.att5 ) dodgeRate += dodge.att5; if ( att >= 6 && dodge.att6 ) dodgeRate += dodge.att6; if ( att >= 7 && dodge.att7 ) dodgeRate += dodge.att7; if ( att >= 8 && dodge.att8 ) dodgeRate += dodge.att8; } if ( dodgeRate ) return Math.random() > dodgeRate/100; return true; }, onBeDamaged:function(damage, cardModel){ var currentHp = this.get("hp"); var realDefense = 0; var damageAfterBlock = 0; if ( cardModel instanceof Backbone.Model ) { var dodge = this.get("dodge"); var dodgeRate = 0; if ( cardModel instanceof SpellModel ) { if ( dodge.spell ) dodgeRate += dodge.spell; } if ( Math.random() > dodgeRate/100 ) { realDefense = ( cardModel.get("type") === "spell" || cardModel.get("type") === "trap" || cardModel.get("pierce") ) ? 0 : this.get("defense"); damageAfterBlock = Math.max(damage - realDefense, 0); // if (damageAfterBlock > currentHp) { // if (cardModel.onOverKillHero) { // cardModel.onOverKillHero(this, damageAfterBlock - currentHp); // } // } } } else { var type = cardModel; if ( type.contains( "poison" ) ) { realDefense = this.get("poisonResistance"); } damageAfterBlock = Math.max(damage - realDefense, 0); } var d = Math.min( currentHp , damageAfterBlock ); this.set("hp", currentHp - d); return [d, damage - d - realDefense]; }, getHeal:function(heal){ var currentHp = this.get("hp"); this.set("hp", Math.min(this.get("maxHp"),currentHp + heal)); }, getDefense:function(amount){ this.set("defenseBuff", this.get("defenseBuff") + 1); }, loseDefense:function(amount){ this.set("defense", Math.max(0, this.get("defense") - amount )); }, onAttackHeart:function(damange){ }, onDie:function(){ }, onAlive:function(){ }, getExp:function(){ return this.get("score"); } }) var AmazonModel = HeroModel.extend({ defaults:function(){ return _.extend(HeroModel.prototype.defaults.call(this), { name:"amazon", displayName:"亚马逊战士", maxLevel: 5, baseDefense: 0, carry: ["cape","potion"] }) }, initByLevel:function(){ var level = this.get("level"); this.set({ attackHeartPower: level*(level-1)/2+1, baseScore: level*(level+1)/2, baseMaxHp: 3 + Math.floor(level/2), dodge: { att1: level <= 3 ? Math.min(75, 25*level) : 0, att2: level >= 4? Math.min(75, 25*(level-3)) : 0 } }); } }); var AssassinModel = HeroModel.extend({ defaults:function(){ return _.extend(HeroModel.prototype.defaults.call(this), { name:"assassin", displayName:"刺客", maxLevel: 5, carry: ["cape","potion"] }) }, initByLevel:function(){ var level = this.get("level"); this.set({ attackHeartPower: level*(level-1)+2, baseScore: level*(level+1)/2, baseMaxHp: 2 + Math.ceil(level/2), baseDefense: 0, dodge: { att1: Math.min(100, 15*level) } }); }, getDescription:function(){ var desc = HeroModel.prototype.getDescription.call(this); return desc + "\n" + "对地城之心的伤害加倍"; } }); var BerserkerModel = HeroModel.extend({ defaults:function(){ return _.extend(HeroModel.prototype.defaults.call(this), { name:"berserker", displayName:"狂战士", maxLevel: 5 }) }, __initEvent:function(){ HeroModel.prototype.__initEvent.call(this); this.on("change:hp change:baseMaxHp",this.evaluateAttackHeartPower,this); }, initByLevel:function(){ var level = this.get("level"); this.set({ attackHeartPower: level*(level-1)/2+1, baseScore: level*(level+1)/2, baseMaxHp: 3 + Math.ceil(level/2), baseDefense: Math.floor(level/5) }); }, evaluateAttackHeartPower:function(){ var level = this.get("level"); this.set("attackHeartPower", level*(level-1)/2+1 + this.get("maxHp") - this.get("hp")); }, getDescription:function(){ var desc = HeroModel.prototype.getDescription.call(this); return desc + "\n" + "自身受到多少伤害就额外对地城之心造成多少伤害"; } }); var ClericModel = HeroModel.extend({ defaults:function(){ return _.extend(HeroModel.prototype.defaults.call(this), { name:"cleric", displayName:"牧师", maxLevel: 5, baseDefense: 0, array: ["potion","elixir"], skills:{ heal: { coolDown: 0, maxCoolDown: 2, baseMaxCoolDown: 2 } } }) }, initByLevel:function(){ var level = this.get("level"); this.set({ attackHeartPower: level*(level-1)/2+1, baseScore: level*(level+1)/2, baseMaxHp: 1 + level }); if ( level >= 3 ) { this.get("skills").heal.baseMaxCoolDown = this.get("skills").heal.maxCoolDown = 1; } this.get("skills").heal.effect = Math.ceil(this.get("level")/2); } }); var DragonSlayerModel = HeroModel.extend({ defaults:function(){ return _.extend(HeroModel.prototype.defaults.call(this), { name:"dragonslayer", displayName:"屠龙者", maxLevel: 5, baseDefense: 0, carry:["big-sword"] }) }, initByLevel:function(){ var level = this.get("level"); this.set({ attackHeartPower: level*(level-1)/2+1, baseScore: level*(level+1)/2, baseMaxHp: 3 + level, baseDefense: Math.floor(level/4), dodge: { att7: level <= 1 ? 100 : 0, att6: level >= 2? 100 : 0, att5: level >= 4? 100 : 0 } }); } }); var KnightModel = HeroModel.extend({ defaults:function(){ return _.extend(HeroModel.prototype.defaults.call(this), { name:"knight", displayName:"骑士", maxLevel: 5, baseDefense: 0, carry: ["helmet","armor"] }) }, initByLevel:function(){ var level = this.get("level"); this.set({ attackHeartPower: level*(level-1)/2+1, baseScore: level*(level+1), baseMaxHp: 3 + level, baseDefense: Math.floor(level/2) }); }, onBeforePositionInTeamChange:function(prevPosition){ var team = gameModel.get("team"); if ( prevPosition + 1 < team.length ) { var heroModel = team[prevPosition+1]; var buff = heroModel.get("defenseBuff"); if ( buff ) { heroModel.set("defenseBuff", buff - 1 ); } } }, onPositionInTeamChange:function(prevPosition, position){ var team = gameModel.get("team"); if ( position + 1 < team.length ) { var heroModel = team[position+1]; var buff = heroModel.get("defenseBuff"); heroModel.set("defenseBuff", buff + 1 ); } }, onDie:function(){ this.onBeforePositionInTeamChange(this.get("positionInTeam")) HeroModel.prototype.onDie.call(this); }, onAlive:function(){ HeroModel.prototype.onAlive.call(this); this.onPositionInTeamChange(null, this.get("positionInTeam")) }, getDescription:function(){ var desc = HeroModel.prototype.getDescription.call(this); return desc + "\n" + "为身后的英雄+"+this.getEffect()+"{[defense]}" }, getEffect:function(){ return this.get("level") } }); var NinjaModel = HeroModel.extend({ defaults:function(){ return _.extend(HeroModel.prototype.defaults.call(this), { name:"ninja", displayName:"忍者", maxLevel: 5, baseDefense: 0, carry: [ "boot" ] }) }, initByLevel:function(){ var level = this.get("level"); this.set({ attackHeartPower: level*(level-1)/2+1, baseScore: level*(level+1)/2, baseMaxHp: 2 + level, dodge: { trap: Math.min( 100, level*25 ) } }); } }); var SageModel = HeroModel.extend({ defaults:function(){ return _.extend(HeroModel.prototype.defaults.call(this), { name:"sage", displayName:"贤者", maxLevel: 5, baseDefense: 0, carry: ["elixir","sage","resurrection"], skills: { resurrection:{ coolDown: 0, maxCoolDown: 4, baseMaxCoolDown: 4 } } }) }, initByLevel:function(){ var level = this.get("level"); this.set({ attackHeartPower: level*(level-1)/2+1, baseScore: level*(level+1)/2, baseMaxHp: 2 + Math.floor(level/2) }); if ( level >= 4 ) { this.get("skills").resurrection.baseMaxCoolDown = this.get("skills").resurrection.maxCoolDown = 2; } this.get("skills").resurrection.effect = this.get("level"); } }); var SoldierModel = HeroModel.extend({ defaults:function(){ return _.extend(HeroModel.prototype.defaults.call(this), { name:"soldier", displayName:"士兵", maxLevel: 5, baseDefense: 0, carry: ["helmet"] }) }, initByLevel:function(){ var level = this.get("level"); this.set({ attackHeartPower: level*(level-1)/2+1, baseScore: level*(level+1), baseMaxHp: 3 + level, baseDefense: Math.floor(level/2) }); }, onBeforePositionInTeamChange:function(prevPosition){ var team = gameModel.get("team"); if ( prevPosition - 1 >= 0 ) { var heroModel = team[prevPosition-1]; var buff = heroModel.get("defenseBuff"); if ( buff ) { heroModel.set("defenseBuff", buff - 1 ); } } }, onPositionInTeamChange:function(prevPosition, position){ var team = gameModel.get("team"); if ( position - 1 >= 0 ) { var heroModel = team[position-1]; var buff = heroModel.get("defenseBuff"); heroModel.set("defenseBuff", buff + 1 ); } }, onDie:function(){ this.onBeforePositionInTeamChange(this.get("positionInTeam")) HeroModel.prototype.onDie.call(this); }, onAlive:function(){ HeroModel.prototype.onAlive.call(this); this.onPositionInTeamChange(null, this.get("positionInTeam")) }, getDescription:function(){ var desc = HeroModel.prototype.getDescription.call(this); return desc + "\n" + "为身前的英雄+"+this.getEffect()+"{[defense]}" }, getEffect:function(){ return this.get("level") } }); var SorcererModel = HeroModel.extend({ defaults:function(){ return _.extend(HeroModel.prototype.defaults.call(this), { name:"sorcerer", displayName:"法师", maxLevel: 4, baseDefense: 0, carry: ["staff"], dodge: { spell: 100 } }) }, initByLevel:function(){ var level = this.get("level"); this.set({ attackHeartPower: level*(level-1)/2+1, baseScore: level*(level+1)/2, baseMaxHp: 2 + level }); } }); var ThiefModel = HeroModel.extend({ defaults:function(){ return _.extend(HeroModel.prototype.defaults.call(this), { name:"thief", displayName:"盗贼", maxLevel: 5, baseDefense: 0, carry: ["lockpicker"], skills:{ steal: { coolDown: 0, maxCoolDown: 2, baseMaxCoolDown: 2 } } }) }, initByLevel:function(){ var level = this.get("level"); this.set({ attackHeartPower: level*(level-1)/2+1, baseScore: level*(level+1)/2, baseMaxHp: 3 + Math.floor(level/2) }); if ( level >= 4 ) { this.get("skills").steal.maxCoolDown = this.get("skills").steal.baseMaxCoolDown = 1; } this.get("skills").steal.effect = Math.ceil(this.get("level")/2) } }); var WarriorModel = HeroModel.extend({ defaults:function(){ return _.extend(HeroModel.prototype.defaults.call(this), { name:"warrior", displayName:"战士", maxLevel: 4, baseDefense: 0 }) }, initByLevel:function(){ var level = this.get("level"); this.set({ attackHeartPower: level*(level-1)/2+1, baseScore: level*(level+1)/2, baseMaxHp: 2 + level*2, baseDefense: Math.floor(level/3) }); } }); var SKILL_FUNC_MAP = { steal: function(effect){ gameModel.useMoney(effect); this.trigger("take",{ icon: "money" }); }, heal: function(effect){ var team = gameModel.get("team"); var hero = _.first(_.filter(team, function (heroModel) { var hp = heroModel.get("hp"); return hp > 0 && hp < heroModel.get("maxHp"); }, this)); if (hero) { hero.getHeal(effect); } }, resurrection:function(effect){ var team = gameModel.get("team"); var dead = _.filter(team, function(heroModel){ return !heroModel.isAlive(); },this); var first = _.first(dead); if ( first ) { first.set("hp", Math.min(effect, first.get("maxHp"))); } } } var HERO_CLASS_MAP = { amazon: AmazonModel, assassin: AssassinModel, berserker: BerserkerModel, cleric : ClericModel, dragonslayer: DragonSlayerModel, knight: KnightModel, ninja: NinjaModel, sage: SageModel, soldier: SoldierModel, sorcerer: SorcererModel, thief: ThiefModel, warrior : WarriorModel } <file_sep>/src/spell-book.js /** * Created by 赢潮 on 2015/3/28. */ var SpellBookLayer = cc.Layer.extend({ ctor:function(options){ this._super(); this.model = options.model; var bg = new cc.Sprite(res.book_bg_png); bg.attr({ x:320, y:0, anchorY:0 }); this.addChild(bg,1); this.__initEvent(); this.__renderCastSpell(); this.__renderCards(); }, __initEvent:function(){ var self = this; cc.eventManager.addListener(this.touchListener = cc.EventListener.create({ event: cc.EventListener.TOUCH_ONE_BY_ONE, swallowTouches: true, onTouchBegan: function (touch, event) { return true; }, onTouchMoved: function (touch, event) { }, onTouchEnded: function (touch, event) { self.close.call(self); } }), this); }, close:function(){ window.mainGame.resumeAction(); this.removeFromParent(true); }, onExit:function(){ cc.eventManager.removeListener(this.touchListener); _.each(this.model.get("hand"),function(cardModel){ cardModel.off(null,null,this); },this); }, __renderCastSpell:function(){ var item = new cc.MenuItemImage( cc.spriteFrameCache.getSpriteFrame("short-normal.png"), cc.spriteFrameCache.getSpriteFrame("short-selected.png"), function () { //TODO check timing cc.eventManager.dispatchCustomEvent("cast-spell",{ model: this.currentSelectedCard.model, x: this.currentSelectedCard.x, y: this.currentSelectedCard.y }); this.removeFromParent(true); }, this ); item.attr({ x: dimens.continue_position.x, y: dimens.continue_position.y, anchorX: 0.5, anchorY: 0.5 }); var text = new cc.LabelTTF(texts.cast_spell, "宋体", dimens.build_new_stage_font_size); text.attr({ color: cc.color.BLACK, x: 90, y: 25 }) item.addChild( text ); this.castMenu = new cc.Menu(item); this.castMenu.x = 0; this.castMenu.y = 0; this.addChild(this.castMenu, 20); this.castMenu.setVisible(false); }, __renderCards:function(){ var length = this.model.get("hand").length; if ( length === 0) return; var unitWidth = cc.winSize.width/length; var i = 0; _.each(this.model.get("hand"),function(cardModel){ var cardSprite = new DUNGEON_SPRITE_CLASS_MAP[cardModel.get("name")]({ model: cardModel }) cardSprite.setSwallowEvent(true); cardSprite.attr({ x : i*unitWidth+unitWidth/2, y : dimens.card_height/2 + 60 }); cardSprite.setOnClickListener(function(){ if ( this.currentSelectedCard === cardSprite ) return; if ( this.currentSelectedCard ) { this.currentSelectedCard.runAction(cc.moveBy(times.select_spell, 0, -dimens.select_spell_offset)); } cardSprite.runAction(cc.moveBy(times.select_spell,0,dimens.select_spell_offset)); this.currentSelectedCard = cardSprite; this.castMenu.setVisible(true); },this); this.addChild(cardSprite, i+1 + 60); i++; },this) } }); <file_sep>/src/spell-card-model.js /** * Created by 赢潮 on 2015/2/25. */ var SpellModel = DungeonCardModel.extend({ //法术 defaults:function(){ return _.extend( DungeonCardModel.prototype.defaults.call(this),{ type: "spell", target: null, // none, all-hero, random-hero, single-hero, single-dungeon, single-monster, single-room, , item, cardInDiscard, cardInDeck timing: null // }) }, onCast:function(options){ options = options || {}; switch ( this.get("target") ){ case null: case "all-hero": this.onEffect(); break; case "single-hero": this.trigger("please-choose-hero", _.extend(options,{ hint: texts.please_choose_target_hero_for_spell })); break; case "single-dungeon": this.trigger("please-choose-dungeon", _.extend(options,{ hint: texts.please_choose_target_dungeon_for_spell })); break; case "single-dungeon-monster": this.trigger("please-choose-dungeon", _.extend(options,{ hint: texts.please_choose_target_dungeon_for_spell, filter:function(model){ return model.get("type") === "monster"; } })); break; } }, onEffect:function(){ this.trigger("cast-spell-finish",this); }, onSelectTarget:function(heroModel){ this.onEffect(heroModel); }, reEvaluate:function(){ DungeonCardModel.prototype.reEvaluate.call(this); this.evaluateAttack(); }, evaluateAttack:function(){ this.set("attack", this.get("baseAttack")) } }) var CycloneModel = SpellModel.extend({ defaults:function(){ return _.extend(SpellModel.prototype.defaults.call(this), { name:"cyclone", displayName:"狂风术", target: null, baseAttack: 0, attack: 0, baseCost: 6, maxLevel: 3 }) }, initByLevel:function(){ var level = this.get("level"); this.set({ baseScore: level, baseUpgradeCost: level*2 } ); this.reEvaluate(); }, onEffect:function(){ var level = this.get("level"); var team = gameModel.get("team"); if ( team.length > 1 ) { if (level == 1) { var i = 0; var oldPosition = 0; var thisHero = _.sample(team); _.each(team, function (heroModel) { if ( heroModel != thisHero ) { heroModel.___temp = i; i++; } else { oldPosition = i; } }, this); do { thisHero.___temp = Math.random() * (team.length) - 1; } while ( Math.ceil(thisHero.___temp) == oldPosition ); team = _.sortBy(team, function (heroModel) { return heroModel.___temp; }); } else if (level == 2) { var newTeam; do { newTeam = _.shuffle(team, team.length); } while (_.isEqual(newTeam, team) ); team = newTeam; } else if (level >= 3) { var newTeam = []; _.each(team, function (heroModel) { newTeam.unshift(heroModel); }, this); team = newTeam; } gameModel.changeTeamPosition(team); /*gameModel.set("team", team); for (var i = 0; i < team.length; i++) { var model = team[i]; model.set("positionInTeam", i, {silent: true}); model.trigger("change:positionInTeam"); }*/ } SpellModel.prototype.onEffect.call(this); }, getDescription:function(){ var desc = RoomModel.prototype.getDescription.call(this); if ( desc !== "" ) { desc += "\n"; } var level = this.get("level"); if ( level == 1 ) { return desc + "使1个英雄移动到队伍中某个随机位置" } else if ( level == 2 ) { return desc + "使英雄队伍的顺序变得随机" } else if ( level >= 3 ) { return desc + "使英雄队伍的顺序变得相反" } } }); var FireballModel = SpellModel.extend({ defaults:function(){ return _.extend(SpellModel.prototype.defaults.call(this), { name:"fireball", displayName:"火球术", target: "single-hero", baseCost: 12, maxLevel: 3 }) }, initialize:function(){ SpellModel.prototype.initialize.call(this); this.on("change:baseAttack change:attackBuff change:attackDebuff", this.evaluateAttack, this) }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: level+1, baseScore: 0, baseUpgradeCost: level*16-1, payScore: level } ); this.reEvaluate(); }, onEffect:function(heroModel){ heroModel.onBeDamaged(this.getEffect(), this); var team = gameModel.get("team"); var index = _.indexOf(team, heroModel); if ( index - 1 >= 0 && team[index-1].isAlive()) { team[index-1].onBeDamaged(this.getEffect()-1, this); } if ( index + 1 < team.length && team[index+1].isAlive()) { team[index+1].onBeDamaged(this.getEffect()-1, this); } SpellModel.prototype.onEffect.call(this); }, getEffect:function(){ return this.get("attack"); }, getDescription:function(){ var desc = RoomModel.prototype.getDescription.call(this); if ( desc !== "" ) { desc += "\n"; } return desc + "对英雄造成"+this.getEffect()+"点伤害,对其两旁的英雄造成"+(this.getEffect()-1)+"点伤害" } }); var LighteningModel = SpellModel.extend({ defaults:function(){ return _.extend(SpellModel.prototype.defaults.call(this), { name:"lightening", displayName:"闪电链", target: "all-hero", baseCost: 6, maxLevel: 3, payScore: 1 }) }, initialize:function(){ SpellModel.prototype.initialize.call(this); this.on("change:baseAttack change:attackBuff change:attackDebuff", this.evaluateAttack, this) }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: level, baseScore: 0, baseUpgradeCost: level*16-1 } ); this.reEvaluate(); }, getEffect:function(level){ return this.get("attack"); }, onEffect:function(){ _.each( gameModel.get("team"),function(heroModel){ heroModel.onBeDamaged(this.getEffect(), this); },this); SpellModel.prototype.onEffect.call(this); }, getDescription:function(){ var desc = RoomModel.prototype.getDescription.call(this); if ( desc !== "" ) { desc += "\n"; } return desc + "对每个英雄造成"+this.getEffect()+"点伤害" } }) var MagicMissileModel = SpellModel.extend({ defaults:function(){ return _.extend(SpellModel.prototype.defaults.call(this), { name:"magic-missile", displayName:"魔导弹", target: "single-hero", baseCost: 4, maxLevel:3 }) }, initEvent:function(){ SpellModel.prototype.initEvent.call(this); this.on("change:baseAttack change:attackBuff change:attackDebuff", this.evaluateAttack, this); }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: level, baseScore: (level-1)*3, baseUpgradeCost: level*6 } ); this.reEvaluate(); }, getEffect:function(level){ return this.get("attack"); }, onEffect:function(heroModel){ heroModel.onBeDamaged(this.getEffect(), this); SpellModel.prototype.onEffect.call(this); }, getDescription:function(){ var desc = RoomModel.prototype.getDescription.call(this); if ( desc !== "" ) { desc += "\n"; } return desc + "选择1个英雄对其造成"+this.getEffect()+"点伤害" } }) var TouchStoneModel = SpellModel.extend({ defaults:function(){ return _.extend(SpellModel.prototype.defaults.call(this), { name:"touchstone", displayName:"炼金术", target: null, attack: 0, baseAttack: 0, baseCost: 4, maxLevel: 3 }) }, initByLevel:function(){ var level = this.get("level"); this.set({ baseScore: level, baseUpgradeCost: level+3 } ); this.reEvaluate(); }, getEffect:function(){ return this.get("level"); }, onEffect:function(){ gameModel.getMoney(this.getEffect()); SpellModel.prototype.onEffect.call(this); }, getDescription:function(){ var desc = RoomModel.prototype.getDescription.call(this); if ( desc !== "" ) { desc += "\n"; } return desc + "获得"+this.getEffect()+"{[money]}" } }); var WarDrumModel = SpellModel.extend({ defaults:function(){ return _.extend(SpellModel.prototype.defaults.call(this), { name:"war-drum", displayName:"战鼓", target: "single-dungeon-monster", attack: 0, baseAttack: 0, baseCost: 4, maxLevel: 3 }) }, initByLevel:function(){ var level = this.get("level"); this.set({ baseScore: level, baseUpgradeCost: level*5 } ); this.reEvaluate(); }, getEffect:function(){ return this.get("level"); }, onEffect:function(dungeonModel){ dungeonModel.set("attackBuff", dungeonModel.get("attackBuff")+this.getEffect()); SpellModel.prototype.onEffect.call(this); }, getDescription:function(){ var desc = RoomModel.prototype.getDescription.call(this); if ( desc !== "" ) { desc += "\n"; } return desc + "使地城中的1个怪物攻击力+"+this.getEffect() } }); //TODO 回到一层地城起点 //TODO 找牌<file_sep>/src/trap-card-model.js var TrapModel = DungeonCardModel.extend({ //房间 defaults:function(){ return _.extend( DungeonCardModel.prototype.defaults.call(this),{ type: "trap", attackBuff: 0, attackDebuff : 0 }) }, onTeamEnter:function(team){ this.onAttackTeam(team); }, onTeamPass:function(team){ }, onMiss:function(heroModel){ }, onDamageHero:function(heroModel, damageTaken ){ }, onBeBlocked:function(heroModel){ }, onKillHero:function(heroModel){ }, reEvaluate:function(){ DungeonCardModel.prototype.reEvaluate.call(this); this.evaluateAttack(); }, evaluateAttack:function(){ var baseAttack = this.get("baseAttack"); if ( isValidInt( baseAttack ) ) { this.set("attack", Math.max(0,baseAttack + this.get("attackBuff") - this.get("attackDebuff"))); } else { this.set("attack", baseAttack); } }, onAttackTeam:function(team, damageLeft){ var att = damageLeft || this.get("attack"); //find all alive hero var allAlive = _.filter( team ,function(model){ return model.isAlive(); }, this ); if ( allAlive.length > 0 ) { switch (this.get("attackRange")) { case "first": var heroModel = _.first(allAlive); this.onAttackHero(heroModel, att); break; case "first2": var heroes = _.first(allAlive,2); _.each(heroes, function (heroModel) { this.onAttackHero(heroModel, att); }, this); break; case "first3": var heroes = _.first(allAlive,3); _.each(heroes, function (heroModel) { this.onAttackHero(heroModel, att); }, this); break; case "last": var heroModel = _.last(allAlive); this.onAttackHero(heroModel, att); break; case "last2": var heroes = _.last(allAlive,2); _.each(heroes, function (heroModel) { this.onAttackHero(heroModel, att); }, this); break; case "last3": var heroes = _.last(allAlive,3); _.each(heroes, function (heroModel) { this.onAttackHero(heroModel, att); }, this); break; case "random": var heroModel = _.sample(allAlive); this.onAttackHero(heroModel, att); break; case "all": _.each(allAlive, function (heroModel) { this.onAttackHero(heroModel, att); }, this); break; } } }, onAttackHero:function(hero, att){ if ( att > 0 ) { var hit = hero.onBeAttacked(att, this); if (hit) { var damageTaken = hero.onBeDamaged(att, this); if (damageTaken > 0) { this.onDamageHero(hero, damageTaken); if (hero.get("hp") == 0) { this.trigger("kill-hero"); this.onKillHero(hero); } // var attackLeft = att - damageTaken; // if ( attackLeft > 0 ) { // this.onOverKillHero( hero, attackLeft ); // } } else { //totally blocked this.trigger("blocked"); this.onBeBlocked(hero); } } else { //miss this.trigger("miss"); this.onMiss(hero); } } }, getDescription:function(){ var desc = DungeonCardModel.prototype.getDescription.call(this); var descs = [desc]; switch ( this.get("attackRange") ) { case "first": descs.push( "{[attack-first]}:影响排在队首的英雄" ); break; case "first2": descs.push( "{[attack-first2]}:影响排在队首的2个英雄" ); break; case "first3": descs.push( "{[attack-first3]}:影响排在队首的3个英雄" ); break; case "last": descs.push( "{[attack-last]}:影响排在队尾的英雄" ); break; case "last2": descs.push( "{[attack-last2]}:影响排在队尾的2个英雄" ); break; case "last3": descs.push( "{[attack-last3]}:影响排在队尾的3个英雄" ); break; case "random": descs.push( "{[attack-random]}:随机影响队伍中的1个英雄" ); break; case "all": descs.push( "{[attack-all]}:影响队伍中的所有英雄" ); break; } return descs.join("\n"); } }); var ArrowTrapModel = TrapModel.extend({ defaults:function(){ return _.extend( TrapModel.prototype.defaults.call(this),{ name: "arrow-trap", displayName:"飞箭陷阱", attackRange:"last", baseCost: 4, maxLevel: 5 }) }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: level, baseScore: level, baseUpgradeCost: level*4+3, payMoney: 1 } ); this.reEvaluate(); } }); var PitfallModel = TrapModel.extend({ defaults:function(){ return _.extend( TrapModel.prototype.defaults.call(this),{ name: "pitfall", displayName:"陷坑", attackRange:"first", baseCost: 3, maxLevel: 4 }) }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: "*", baseScore: level, baseUpgradeCost: level+1, payMoney: Math.max(0,level - 2) } ); if ( level == 1 ) { this.set("attackRange","first"); } else if ( level == 2 ) { this.set("attackRange","first2"); } else if ( level == 3 ) { this.set("attackRange","first3"); } else if ( level >= 4 ) { this.set("attackRange","all"); } this.reEvaluate(); }, onAttackHero:function(hero, att){ att = hero.get("defense"); if ( att > 0 ) { var hit = hero.onBeAttacked(att, this); if (hit) { var damageTaken = hero.onBeDamaged(att, this); if (damageTaken > 0) { this.onDamageHero(hero, damageTaken); if (hero.get("hp") == 0) { this.trigger("kill-hero"); this.onKillHero(hero); } // var attackLeft = att - damageTaken; // if ( attackLeft > 0 ) { // this.onOverKillHero( hero, attackLeft ); // } } else { //totally blocked this.trigger("blocked"); this.onBeBlocked(hero); } } else { //miss this.trigger("miss"); this.onMiss(hero); } } }, getDescription:function(){ var desc = TrapModel.prototype.getDescription.call(this); if ( desc != "" ) { desc += "\n"; } desc += "英雄受到等于其{[defense]}的伤害"; return desc; } }) var PoisonGasModel = TrapModel.extend({ defaults:function(){ return _.extend( TrapModel.prototype.defaults.call(this),{ name: "poison-gas", displayName:"毒气陷阱", attackRange:"first", baseCost: 5, maxLevel: 6 }) }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: 0, baseScore: level, baseUpgradeCost: level + 1, payMoney: level } ); if ( level == 1 ) { this.set("attackRange","first"); } else if ( level <= 3 && level >= 2 ) { this.set("attackRange","first2"); } else if ( level <= 5 && level >= 4 ) { this.set("attackRange","first3"); } else if ( level >= 6 ) { this.set("attackRange","all"); } this.reEvaluate(); }, getEffect:function(level){ level = level || this.get("level"); return Math.floor((level+1)/2)+1; }, onAttackHero:function(heroModel, att){ var hit = heroModel.onBeAttacked(0, this); if (hit) { heroModel.getPoison(this.getEffect()); } }, getDescription:function(){ var desc = TrapModel.prototype.getDescription.call(this); if ( desc != "" ) { desc += "\n"; } desc += "英雄中毒"+this.getEffect()+"轮"; return desc; } }) var RollingBoulderModel = TrapModel.extend({ defaults:function(){ return _.extend( TrapModel.prototype.defaults.call(this),{ name: "rolling-boulder", displayName:"滚石陷阱", attackRange:"last", maxLevel: 5, baseCost: 5 }) }, onAttackHero:function(heroModel, att){ var hit = heroModel.onBeAttacked(0, this); if (hit) { heroModel.set("hp",0); } }, getDescription:function(){ var desc = TrapModel.prototype.getDescription.call(this); if ( desc != "" ) { desc += "\n"; } desc += "受影响的英雄立即死亡"; return desc; }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: "*", baseUpgradeCost: level*10+10, payMoney: 6-level } ); this.reEvaluate(); } });<file_sep>/src/class-map.js /** * Created by 赢潮 on 2015/3/8. */ var DUNGEON_CLASS_MAP = { basilisk: BasiliskModel, "dark-elf": DarkElfModel, dragon: DragonModel, gargoyle: GargoyleModel, ghost: GhostModel, lich: LichModel, lilith: LilithModel, minotaur: MinotaurModel, imp : ImpModel, ooze: OozeModel, orc: OrcModel, "orc-bandit":OrcBanditModel, "orc-warlord":OrcWarlordModel, skeleton : SkeletonModel, spider: SpiderModel, titan: TitanModel, treefolk: TreefolkModel, zombie: ZombieModel, cyclone: CycloneModel, fireball : FireballModel, lightening : LighteningModel, "magic-missile": MagicMissileModel, touchstone: TouchStoneModel, "war-drum": WarDrumModel, armor: ArmorModel, "big-sword": BitSwordModel, boot: BootModel, cape: CapeModel, elixir: ElixirModel, helmet: HelmetModel, lockpicker: LockPickerModel, potion : PotionModel, resurrection: ResurrectionPotionModel, staff: StaffModel, blacksmith: BlacksmithModel, library: LibraryModel, "hen-den": HenDenModel, prison: PrisonModel, "spoiled-food": SpoiledFoodModel, vault: VaultModel, "arrow-trap":ArrowTrapModel, pitfall: PitfallModel, "poison-gas": PoisonGasModel, "rolling-boulder": RollingBoulderModel } var DUNGEON_SPRITE_CLASS_MAP = { basilisk: MonsterCardSprite, "dark-elf": MonsterCardSprite, dragon: MonsterCardSprite, gargoyle: MonsterCardSprite, ghost: MonsterCardSprite, lich: MonsterCardSprite, lilith: MonsterCardSprite, minotaur: MonsterCardSprite, imp : MonsterCardSprite, ooze: MonsterCardSprite, orc : MonsterCardSprite, "orc-bandit" : MonsterCardSprite, "orc-warlord": MonsterCardSprite, skeleton : MonsterCardSprite, spider: MonsterCardSprite, titan: MonsterCardSprite, treefolk: MonsterCardSprite, zombie: MonsterCardSprite, cyclone: SpellCardSprite, fireball: FireballCardSprite, lightening: SpellCardSprite, "magic-missile": MagicMissileCardSprite, touchstone: SpellCardSprite, "war-drum": WarDrumCardSprite, armor: ItemCardSprite, "big-sword": ItemCardSprite, boot: ItemCardSprite, cape: ItemCardSprite, elixir: ItemCardSprite, helmet: ItemCardSprite, lockpicker: ItemCardSprite, potion : ItemCardSprite, resurrection: ItemCardSprite, staff: ItemCardSprite, blacksmith: RoomCardSprite, library: RoomCardSprite, "hen-den": RoomCardSprite, prison: RoomCardSprite, "spoiled-food": RoomCardSprite, vault: RoomCardSprite, "arrow-trap":TrapCardSprite, pitfall:TrapCardSprite, "poison-gas":TrapCardSprite, "rolling-boulder":TrapCardSprite } var CARD_TYPE_MAP = { "trap":"陷阱", "monster":"怪物", "spell":"法术", "item":"宝物", "room":"设施" } var CARD_SUBTYPE_MAP = { "undead":"亡灵" }<file_sep>/src/monster-card-model.js /** * Created by 赢潮 on 2015/2/25. */ var MonsterModel = DungeonCardModel.extend({ //怪物牌 defaults:function(){ return _.extend( DungeonCardModel.prototype.defaults.call(this), { type: "monster", subType: null, baseAttack: 1, attack: 1, attackBuff: 0, attackDebuff: 0, attackType: "melee", attackRange: "first", status: null }) }, initEvent:function(){ DungeonCardModel.prototype.initEvent.call(this); this.on("change:baseAttack change:attackBuff change:attackDebuff", this.evaluateAttack, this); }, reEvaluate:function(){ DungeonCardModel.prototype.reEvaluate.call(this); this.evaluateAttack(); }, evaluateAttack:function(){ var baseAttack = this.get("baseAttack"); if ( isValidInt( baseAttack ) ) { this.set("attack", Math.max(0,baseAttack + this.get("attackBuff") - this.get("attackDebuff"))); } else { this.set("attack", baseAttack); } }, onStageReveal:function(dungeonCards){ this.evaluateAttack(); }, onTeamEnter:function(team){ }, onAttackTeam:function(team, damageLeft){ var att = damageLeft || this.get("attack"); //find all alive hero var allAlive = _.filter( team ,function(model){ return model.isAlive(); }, this ) if ( allAlive.length > 0 ) { switch (this.get("attackRange")) { case "first": var heroModel = _.first(allAlive); this.onAttackHero(heroModel, att); break; case "first2": var heroes = _.first(allAlive,2); _.each(heroes, function (heroModel) { this.onAttackHero(heroModel, att); }, this); break; case "first3": var heroes = _.first(allAlive,3); _.each(heroes, function (heroModel) { this.onAttackHero(heroModel, att); }, this); break; case "last": var heroModel = _.last(allAlive); this.onAttackHero(heroModel, att); break; case "last2": var heroes = _.last(allAlive,2); _.each(heroes, function (heroModel) { this.onAttackHero(heroModel, att); }, this); break; case "last3": var heroes = _.last(allAlive,3); _.each(heroes, function (heroModel) { this.onAttackHero(heroModel, att); }, this); break; case "random": var heroModel = _.sample(allAlive); this.onAttackHero(heroModel, att); break; case "all": _.each(allAlive, function (heroModel) { this.onAttackHero(heroModel, att); }, this); break; } } }, onAttackHero:function(hero, att){ if ( att > 0) { var hit = hero.onBeAttacked(att, this); if (hit) { var result = hero.onBeDamaged(att, this); var damageTaken = result[0]; if (damageTaken > 0) { this.onDamageHero(hero, damageTaken); if (hero.get("hp") == 0) { this.trigger("kill-hero"); this.onKillHero(hero); var attackLeft = result[1]; if (attackLeft > 0) { this.onOverKillHero(hero, attackLeft); } } } else { //totally blocked hero.trigger("blocked"); this.onBeBlocked(hero); } } else { //miss this.trigger("miss"); this.onMiss(hero); } } }, onBeBlocked:function(heroModel){ }, onMiss:function(heroModel){ }, onDamageHero:function(heroModel, damageTaken ){ }, onKillHero:function(heroModel){ }, onOverKillHero:function(heroModel, damageLeft ){ if ( this.get("trample") && this.get("attackRange") !== "all" ) { this.onAttackTeam(window.gameModel.get("team"), damageLeft); } }, onTeamPass:function(team){ }, getDescription:function(){ var desc = DungeonCardModel.prototype.getDescription.call(this); var descs = [desc]; switch ( this.get("attackRange") ) { case "first": descs.push( "{[attack-first]}:攻击排在队首的英雄" ); break; case "first2": descs.push( "{[attack-first2]}:攻击排在队首的2个英雄" ); break; case "first3": descs.push( "{[attack-first3]}:攻击排在队首的3个英雄" ); break; case "last": descs.push( "{[attack-last]}:攻击排在队尾的英雄" ); break; case "last2": descs.push( "{[attack-last2]}:攻击排在队尾的2个英雄" ); break; case "last3": descs.push( "{[attack-last3]}:攻击排在队尾的3个英雄" ); break; case "random": descs.push( "{[attack-random]}:随机攻击队伍中的1个英雄" ); break; case "all": descs.push( "{[attack-all]}:攻击队伍中的所有英雄" ); break; } if ( this.get("pierce") ) { descs.push( "{[pierce]}:攻击时无视英雄的防御" ); } if ( this.get("trample") ) { descs.push( "{[trample]}:杀死英雄后多余的伤害转嫁到之后的英雄上" ); } return descs.join("\n"); } }); var BasiliskModel = MonsterModel.extend({ defaults:function(){ return _.extend(MonsterModel.prototype.defaults.call(this), { name:"basilisk", displayName:"巨蟒", maxLevel: 5, attackRange: "last", baseCost: 6 }) }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: level+1, baseScore: level, baseUpgradeCost: level === 1 ? 9 : 4*level+2, trample: level >= 2 } ); this.reEvaluate(); }, maxLevelBonus:function(){ this.set("baseScore",this.get("baseScore")+2); } }); var DarkElfModel = MonsterModel.extend({ defaults:function(){ return _.extend(MonsterModel.prototype.defaults.call(this), { name:"dark-elf", displayName:"暗精灵", maxLevel: 5, baseCost: 2, attackRange: "last" }) }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: level, baseScore: level, baseUpgradeCost: 4*(level-1)+2 } ); this.reEvaluate(); }, maxLevelBonus:function(){ this.set("baseScore",this.get("baseScore")+2); } }) var DragonModel = MonsterModel.extend({ defaults:function(){ return _.extend(MonsterModel.prototype.defaults.call(this), { name:"dragon", displayName:"龙", maxLevel: 5, baseCost: 16 }) }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: level+4, baseScore: 0, baseUpgradeCost: 18+level, payHp: level > 3 ? 2 : 3, trample: level > 3 } ); this.reEvaluate(); } }) var GhostModel = MonsterModel.extend({ defaults:function(){ return _.extend(MonsterModel.prototype.defaults.call(this), { name:"ghost", displayName:"鬼魂", subtype:"undead", maxLevel: 5, baseCost: 3, attackRange: "random", pierce: true }) }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: level, baseScore: level*2-1, baseUpgradeCost: level*4-1 } ); this.reEvaluate(); }, maxLevelBonus:function(){ this.set("baseScore",this.get("baseScore")+2); } }); var GargoyleModel = MonsterModel.extend({ defaults:function(){ return _.extend(MonsterModel.prototype.defaults.call(this), { name:"gargoyle", displayName:"石像鬼", baseCost: 5, maxLevel: 5 }) }, getDescription:function(){ var desc = MonsterModel.prototype.getDescription.call(this); if ( desc != "" ) { desc += "\n"; } return desc + "封印英雄的主动技能"+this.getEffect()+"轮"; }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: Math.floor(level/3)+1, baseScore: level, baseUpgradeCost: Math.ceil(level*4.5) } ); this.reEvaluate(); }, getEffect:function(){ return Math.floor(this.get("level")/2)+1; }, onDamageHero:function(heroModel, damageTaken ){ heroModel.getSilent(this.getEffect()); }, onBeBlocked:function(heroModel){ heroModel.getSilent(this.getEffect()); } }); var ImpModel = MonsterModel.extend({ defaults:function(){ return _.extend(MonsterModel.prototype.defaults.call(this), { name:"imp", displayName:"小鬼", baseCost: 1, maxLevel: 5 }) }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: 0, baseScore: level, baseUpgradeCost: level*level } ); this.reEvaluate(); }, getDescription:function(){ var desc = MonsterModel.prototype.getDescription.call(this); if ( desc != "" ) { desc += "\n"; } return desc+"翻开时,+"+this.getEffect()+"{[money]}"; }, getEffect:function(){ return this.get("level"); }, onReveal:function(){ MonsterModel.prototype.onReveal.call(this); var money = this.getEffect(); gameModel.getMoney(money); this.trigger("give",{ icon: "money" }); } }); var LichModel = MonsterModel.extend({ defaults:function(){ return _.extend(MonsterModel.prototype.defaults.call(this), { name:"lich", displayName:"巫妖", baseCost: 5, maxLevel: 5 }) }, getDescription:function(){ var desc = MonsterModel.prototype.getDescription.call(this); if ( desc != "" ) { desc += "\n"; } return desc + "杀死的英雄变成僵尸"; }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: level, baseScore: level, baseUpgradeCost: Math.ceil(level*2.5) } ); this.reEvaluate(); }, onAttackHero:function(hero, att){ hero.set("bite",true); MonsterModel.prototype.onAttackHero.call(this,hero,att); } }); var LilithModel = MonsterModel.extend({ defaults:function(){ return _.extend(MonsterModel.prototype.defaults.call(this), { name:"lilith", displayName:"莉莉丝", baseCost: 5, maxLevel: 5 }) }, getDescription:function(){ var desc = MonsterModel.prototype.getDescription.call(this); if ( desc !== "" ) { desc += "\n"; } return desc+"获得与英雄受到的伤害等量的{[black-hp]}"; }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: level, baseScore: level>4?2:0, baseUpgradeCost: level*5+5 } ); this.reEvaluate(); }, onDamageHero:function(heroModel, damageTaken){ if ( damageTaken ) { gameModel.getHp(damageTaken); this.trigger("give", { icon: "black-hp" }); } } }); var MinotaurModel = MonsterModel.extend({ defaults:function(){ return _.extend(MonsterModel.prototype.defaults.call(this), { name:"minotaur", displayName:"牛头人", baseCost: 4, maxLevel: 4 }) }, getDescription:function(){ var desc = MonsterModel.prototype.getDescription.call(this); if ( desc != "" ) { desc += "\n"; } var level = this.get("level"); if ( level === 1 ) { return desc + "牛头人的攻击力等于地城深度"; } else if ( level === 2 ) { return desc + "牛头人的攻击力等于地城深度+1"; } else if ( level === 3 ) { return desc + "牛头人的攻击力等于地城深度的2倍"; } else if ( level >= 4 ) { return desc + "牛头人的攻击力等于地城深度的2倍+1"; } else if ( level >= 5 ) { return desc + "牛头人的攻击力等于地城深度的3倍"; } }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: "*", baseScore: level, baseUpgradeCost: level*6 } ); this.reEvaluate(); }, onStageReveal:function(dungeonCards){ var stageNumber = window.gameModel.get("stageNumber") + 1; //翻开时英雄还未走下新的地城,所以数值要+1 var level = this.get("level"); var att = stageNumber; if ( level === 1 ) { att = stageNumber; } else if ( level === 2 ) { att = stageNumber+1; } else if ( level === 3 ) { att = stageNumber*2; } else if ( level >= 4 ) { att = stageNumber*2+1; } else if ( level >= 5 ) { att = stageNumber*3; } this.set({ baseAttack: att }) } }); var OozeModel = MonsterModel.extend({ defaults:function(){ return _.extend(MonsterModel.prototype.defaults.call(this), { name:"ooze", displayName:"软泥怪", baseCost: 4, maxLevel: 6 }) }, getDescription:function(){ var desc = MonsterModel.prototype.getDescription.call(this); if ( desc != "" ) { desc += "\n"; } var level = this.get("level"); if ( level <= 3 ) return desc + "经过的英雄-"+level+"{[defense]}"; else return desc + "所有英雄-"+(level-3)+"{[defense]}"; }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: 1, baseScore: level, baseUpgradeCost: level*2 } ); this.reEvaluate(); }, onDamageHero:function(heroModel, damageTaken ){ var level = this.get("level"); if ( level <= 3 ) heroModel.loseDefense(level); }, onBeBlocked:function(heroModel){ var level = this.get("level"); if ( level <= 3 ) heroModel.loseDefense(level); }, onTeamPass:function(team){ var level = this.get("level"); if ( level >= 4) { _.each(team, function (heroModel) { if (heroModel.isAlive()) { heroModel.loseDefense(level-3); } }, this); } } }); var OrcModel = MonsterModel.extend({ defaults:function(){ return _.extend(MonsterModel.prototype.defaults.call(this), { name:"orc", displayName:"兽人", maxLevel: 5, baseCost: 5 }) }, getDescription:function(){ var desc = MonsterModel.prototype.getDescription.call(this); if ( desc !== "" ) { desc += "\n"; } var level = this.get("level"); desc += "兽人的攻击力等于本层地城中怪物的数量"; if ( level === 1 ) desc += "-1"; else if ( level > 2 ) desc += "+"+(level-2); return desc; }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: "*", baseScore: level, baseUpgradeCost: Math.max(6,(level-1)*6) } ); this.reEvaluate(); }, onStageReveal:function(dungeonCards){ var att = _.reduce(dungeonCards, function(memo, cardModel){ if ( cardModel.isEffecting() && cardModel instanceof MonsterModel ) { return memo + 1; } else { return memo; } },0,this); this.set({ baseAttack: att + this.get("level") - 2 }) } }); var OrcBanditModel = MonsterModel.extend({ defaults:function(){ return _.extend(MonsterModel.prototype.defaults.call(this), { name:"orc-bandit", displayName:"兽人强盗", baseCost: 3, maxLevel: 5 }) }, getDescription:function(){ var desc = MonsterModel.prototype.getDescription.call(this); if ( desc !== "" ) { desc += "\n"; } return desc+"获得与英雄受到的伤害等量的{[money]}"; }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: level, baseScore: level, baseUpgradeCost: 6*level+6 } ); this.reEvaluate(); }, onDamageHero:function(heroModel, damageTaken){ if ( damageTaken ) { gameModel.getMoney(damageTaken); this.trigger("give", { icon: "money" }); } } }); var OrcWarlordModel = MonsterModel.extend({ defaults:function(){ return _.extend(MonsterModel.prototype.defaults.call(this), { name:"orc-warlord", displayName:"兽人酋长", baseCost: 9, maxLevel: 5 }) }, getDescription:function(){ var desc = MonsterModel.prototype.getDescription.call(this); if ( desc !== "" ) { desc += "\n"; } return desc+"本层其他怪物+"+this.getEffect()+"{[attack]}"; }, getEffect:function(){ return Math.ceil(this.get("level")/5); }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: Math.ceil(this.get("level")/2), baseScore: level*2, baseUpgradeCost: level*6+7 } ); this.reEvaluate(); }, onStageReveal:function(dungeonCards){ _.each(dungeonCards, function(cardModel){ if ( cardModel.isEffecting() && cardModel instanceof MonsterModel ) { if ( cardModel !== this ) { cardModel.set("attackBuff",cardModel.get("attackBuff")+this.getEffect()); } } },this); } }); var SkeletonModel = MonsterModel.extend({ defaults:function(){ return _.extend(MonsterModel.prototype.defaults.call(this), { name:"skeleton", displayName:"骷髅", subtype:"undead", maxLevel: 5, baseCost: 1 }) }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: level, baseScore: level, baseUpgradeCost: 4*(level-1)+2 } ); this.reEvaluate(); }, maxLevelBonus:function(){ this.set("baseScore",this.get("baseScore")+2); } }); var SpiderModel = MonsterModel.extend({ defaults:function(){ return _.extend(MonsterModel.prototype.defaults.call(this), { name:"spider", displayName:"毒蜘蛛", baseCost: 4, maxLevel: 5 }) }, getDescription:function(){ var desc = MonsterModel.prototype.getDescription.call(this); if ( desc != "" ) { desc += "\n"; } return desc + "受伤的英雄中毒"+this.getEffect()+"轮"; }, getEffect:function(){ return this.get("level")+1; }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: Math.ceil(level/2), baseScore: level, baseUpgradeCost: level*2 } ); this.reEvaluate(); }, onDamageHero:function(heroModel, damageTaken ){ heroModel.getPoison(this.getEffect()); } }); var TitanModel = MonsterModel.extend({ defaults:function(){ return _.extend(MonsterModel.prototype.defaults.call(this), { name:"titan", displayName:"泰坦巨人", maxLevel: 5, baseCost: 12 }) }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: level+2, baseScore: 0, baseUpgradeCost: level === 1 ? 12 : level*4+5, trample: level > 1 } ); this.reEvaluate(); } }); var TreefolkModel = MonsterModel.extend({ defaults:function(){ return _.extend(MonsterModel.prototype.defaults.call(this), { name:"treefolk", displayName:"树妖", baseCost: 8, maxLevel: 5 }) }, initByLevel:function(){ var level = this.get("level"); var scores = [0,1,2,4,6]; this.set({ baseAttack: Math.floor(level/2)+1, baseScore: scores[level-1], baseUpgradeCost: level != 1 ? 7 : 2 } ); this.reEvaluate(); }, getDescription:function(){ var desc = MonsterModel.prototype.getDescription.call(this); if ( desc != "" ) { desc += "\n"; } return desc+"翻开时,+"+this.getEffect()+"{[black-hp]}"; }, getEffect:function(){ return Math.ceil(this.get("level")/2); }, onReveal:function(){ MonsterModel.prototype.onReveal.call(this); var hp = this.getEffect(); gameModel.getHp(hp); this.trigger("give",{ icon: "black-hp" }); } }); var ZombieModel = MonsterModel.extend({ defaults:function(){ return _.extend(MonsterModel.prototype.defaults.call(this), { name:"zombie", displayName:"僵尸", subtype:"undead", maxLevel: 5, baseCost: 1 }) }, initByLevel:function(){ var level = this.get("level"); this.set({ baseAttack: level, baseScore: level, baseUpgradeCost: 4*(level-1)+2 } ); this.reEvaluate(); } });<file_sep>/src/game-model.js /** * Created by 赢潮 on 2015/3/1. */ var UPGRADE_RANGE_LEVEL = { FROM_DISCARD : 1, FROM_DECK : 2, FROM_HAND : 3, FROM_DUNGEON : 4 }; var CARD_PER_LINE = 4; var GameModel = Backbone.Model.extend({ defaults:function(){ return { turn: 0, score: 0, money : 8, maxMoney: 8, levelUpHpEffect: 5, baseHp: 20, hp : 1, maxHp : 1, upgradeChance: 4, defense: 0, level: 1, maxLevel: 1, spoiled: 0, cunning: 0, cunningEffect: 5, exp: 0, maxExp: 10, status: null, phase: "hero-generate", //hero-generate , team-enter-dungeon, team-enter-level, team-enter-room, team-leave-room, team-leave-level, team //generateHeroType : "deck", //deck, pool generateHeroType : "pool", initHeroDeck: [{type:"cleric",level:1,maxLevel:1},{type:"cleric",level:1,maxLevel:3},{type:"cleric",level:1,maxLevel:3},{type:"thief",level:1,maxLevel:3}], heroDeck: [], isHeroDeckShuffle: false, //heroList: ["dragonslayer","berserker"], heroList: [ "amazon","assassin", "berserker", "cleric", "dragonslayer", "knight", "ninja", "sage", "soldier","sorcerer", "thief", "warrior" ], heroLevelPool: [1], heroMaxLevelPool: [ 3, 3, 3 ], maxHeroMaxLevelAppearCount: 3, maxHeroMaxLevel: 3, increaseDifficultyPerTurn: 13, generateHeroNumber: 1, //heroList: [ "sorcerer"], initDeck: [ "skeleton", "skeleton","skeleton","skeleton","imp","imp","imp","imp" ], //initDeck: [ "magic-missile","skeleton", "skeleton","skeleton","skeleton","imp","imp","imp","imp" ], //initDeck: [ /*"titan","arrow-trap","ooze",*/"dragon","arrow-trap","lilith","arrow-trap" ], deck: [], isInitDeckShuffle: true, //initDiscardDeck: [ "magic-missile","skeleton", "skeleton","skeleton","skeleton","imp","imp","imp","imp","magic-missile","skeleton", "skeleton","skeleton","skeleton","imp","imp","imp","imp" ], initDiscardDeck: [ ], discardDeck: [], //initHand: ["fireball","magic-missile","fireball"], initHand: ["magic-missile"], hand: [], //魔法 maxHand: 1, team: [], costPerStage: 4, costCut: 0, stage: [], stageNumber: 0, upgradeRangeLevel: UPGRADE_RANGE_LEVEL.FROM_DISCARD, //initBonus: ["blacksmith","maxHp"], initBonus: ["upgradeChance","maxHp","money","upgradeFromDeck","cullDiscard","cullDeck","flowBuyableCard","blacksmith", "library","prison","spoiled-food"], bonusPool : [], bonusChoiceNumber:3, bonusEachLevelUp: "alwaysLevelUpBonus", unlockedBuyableCards:["basilisk","dark-elf","dragon","gargoyle","ghost","lich","lilith","minotaur","ooze","orc","orc-bandit","orc-warlord","spider","titan", "treefolk", "cyclone","fireball","lightening","touchstone","war-drum", "hen-den", "arrow-trap","pitfall","poison-gas","rolling-boulder"], regularBuyableCards: [], initRegularBuyableCount : 4, initRegularBuyableCards : [ { type:"imp", count: 8 }, { type:"skeleton", count: 8 }, { type:"magic-missile", count: 8 }, { type:"vault", count: 8 }], initFlowBuyableCards: [["arrow-trap"],["pitfall"]], flowBuyableLineNumber: 2, flowBuyableCardLines: [], poisonEffect: 1 } }, initialize:function(){ this.expUnused = 0; this.set("maxHp",this.get("baseHp")); this.setLevel(1); this.on("change:cunning",function(){ this.set("maxExp",this.calExpRequire()); },this) }, increaseTurn:function(){ var turn = this.get("turn"); this.set("turn", ++turn); if ( turn % this.get("increaseDifficultyPerTurn") === 0 ) { if ( this.get("maxHeroMaxLevelAppearCount") >= this.get("maxHeroMaxLevel")) { this.set({ maxHeroMaxLevel: this.get("maxHeroMaxLevel") + 1, maxHeroMaxLevelAppearCount : 0 }); } this.set("maxHeroMaxLevelAppearCount", this.get("maxHeroMaxLevelAppearCount") + 1); this.get("heroMaxLevelPool").push( this.get("maxHeroMaxLevel") ); var heroLevelPool = this.get("heroLevelPool"); for ( var i = 1; i < this.get("maxHeroMaxLevel") ; i++) { heroLevelPool.push(i); } if ( turn % (this.get("increaseDifficultyPerTurn")*4) === 0 ) { var genHeroNumber = this.get("generateHeroNumber"); if ( genHeroNumber < 4 ) this.set("generateHeroNumber",genHeroNumber+1); } } }, changeTeamPosition:function(team){ var oldTeam = this.get("team"); for ( var i = 0; i < oldTeam.length; i++ ) { var model = oldTeam[i]; model.onBeforePositionInTeamChange(i); } this.set("team",team); for ( var i = 0; i < team.length; i++ ) { var model = team[i]; model.set("positionInTeam", i, {silent:true}); model.trigger("change:positionInTeam"); } }, sortTeam:function(){ var team = this.get("team"); team = _.sortBy(team, function(heroModel){ return 1000000 - (heroModel.get("hp") * 100 + heroModel.get("level")); }); /*this.set("team",team); for ( var i = 0; i < team.length; i++ ) { var model = team[i]; model.set("positionInTeam", i, {silent:true}); model.trigger("change:positionInTeam"); }*/ this.changeTeamPosition(team); }, setLevel:function(l){ this.set("level",l); this.set("hp", this.get("maxHp")); this.set("exp",0); this.set("maxExp",this.calExpRequire(l)); }, getExp:function(exp){ if ( this.expUnused == 0 ) { this.expUnused += exp; this.checkLevelUp(); } else { this.expUnused += exp; } }, getScore:function(score){ this.set("score",this.get("score")+score); }, loseScore:function(score){ this.set("score",this.get("score")-score); }, getTavernRecoveryEffect:function(diff){ return Math.max( diff - this.get("spoiled"), 0 ); }, getPayFromTavern:function(money){ this.getMoney(money); }, getMoney:function(money){ this.set("money",Math.min( this.get("maxMoney") , this.get("money")+money ) ); }, useMoney:function(money){ this.set("money", Math.max(0, this.get("money") - money )); }, payHp:function(hp){ this.set("hp",Math.max(1, this.get("hp")-hp)); }, payScore:function(score){ this.set("score",Math.max(0, this.get("score")-score)); }, getHp:function(hp){ this.set("hp",Math.min(this.get("maxHp"), this.get("hp")+hp)); }, calExpRequire: function (lv) { lv = lv || this.get("level"); return Math.round((Math.log10(lv) * lv * 8.8 /*16.61*/ + 5) * (1 - (this.get("cunningEffect") / 100) * this.get("cunning"))); }, checkLevelUp:function(){ var currentExp = this.get("exp"); var expRequire = this.get("maxExp"); if (currentExp + this.expUnused >= expRequire) { this.levelUp(); this.expUnused -= ( expRequire - currentExp ); mainGame.showLevelUp(function(){ this.checkLevelUp(); },this) } else { this.set("exp", currentExp + this.expUnused); this.expUnused = 0; } }, levelUp:function(){ var newLevel = this.get("level") + 1; this.set("maxHp",this.get("maxHp")+this.get("levelUpHpEffect")); this.setLevel(newLevel); }, isTeamAlive:function(){ var team = this.get("team"); if ( team.length === 0 ) return false; return _.any(team,function(heroModel){ return heroModel.get("hp") > 0; },this) }, getTeamAttackDungeonHeartPower:function(){ return _.reduce(this.get("team"),function(memo, heroModel){ if ( heroModel.isAlive() ) { return memo + heroModel.get("attackHeartPower"); } else return memo; }, 0 ,this) }, removeDeadHeroFromTeam:function(){ var team = this.get("team"); for ( var i = 0;i < team.length; ) { var model = team[i]; if ( model.isAlive() ) { i++; } else { team.splice(i,1); model.destroy(); model.off(); model = null; } } this.sortTeam(); }, overMaxLevelHeroLeave:function(){ var team = this.get("team"); for ( var i = 0;i < team.length; ) { var model = team[i]; if ( model.get("leaving") ) { model.onBeforePositionInTeamChange(model.get("positionInTeam")); team.splice(i,1); model.trigger("leaveTeam"); model = null; } else { i++; } } this.sortTeam(); }, getBuildCost:function(){ return Math.max(1, this.get("stageNumber")* this.get("costPerStage") - this.get("costCut")); }, isFullHand:function(){ return this.get("hand").length >= this.get("maxHand"); }, getSpellCard:function(cardSprite){ this.get("hand").push(cardSprite.model); cardSprite.removeFromParent(true); this.trigger("change:hand"); }, useSpellCard:function(cardModel){ var hand = this.get("hand"); var index = hand.indexOf(cardModel); if ( index != -1 ) this.get("hand").splice(index,1); this.trigger("change:hand"); }, initDeck:function(){ _.each( this.get("initDeck"), function(cardName){ var Model = DUNGEON_CLASS_MAP[cardName]; var model = new Model(); this.get("deck").push( model ); this.getScore(model.get("score")); },this); if ( this.get("isInitDeckShuffle") ) this.set("deck",_.shuffle(this.get("deck"))); }, initDiscardDeck:function(){ _.each( this.get("initDiscardDeck"), function(cardName){ var Model = DUNGEON_CLASS_MAP[cardName]; var model = new Model({ side: "front" }); this.get("discardDeck").push( model ); this.getScore(model.get("score")); },this); if ( this.get("isInitDeckShuffle") ) this.set("deck",_.shuffle(this.get("deck"))); }, initRegularBuyableCards:function(){ var initBuyable = this.get("initRegularBuyableCards"); _.each( initBuyable , function(entry){ this.newRegularBuyableDeck(entry); },this); if ( initBuyable.length < this.get("initRegularBuyableCount") ) { var diff = this.get("initRegularBuyableCount") - initBuyable.length; for ( var i = 0 ; i < diff; i++ ){ this.randomUnlockedToBuyable(); } } }, initFlowBuyableCards:function(){ var lineNumber = 0; var cardLines= this.get("flowBuyableCardLines"); _.each( this.get("initFlowBuyableCards"), function(line){ cardLines[lineNumber] = []; _.each(line,function(cardName){ cardLines[lineNumber].push( new DUNGEON_CLASS_MAP[cardName]({side:"front"})); }); lineNumber++; }); this.refillFlowBuyableCards(); }, maintainFlowBuyableCards:function(){ var cardLines= this.get("flowBuyableCardLines"); _.each( cardLines, function(line){ line.shift(); }); this.removeNullFlowBuyableCards(); this.refillFlowBuyableCards(); }, removeNullFlowBuyableCards:function(){ var cardLines= this.get("flowBuyableCardLines"); for ( var i = 0; i < cardLines.length; i++ ){ var line = cardLines[i]; line = _.filter(line,function(model){ return model != null; }); cardLines[i] = line; } }, refillFlowBuyableCards:function(){ var cardLines= this.get("flowBuyableCardLines"); _.each( cardLines, function(line){ for ( var i = line.length; i<CARD_PER_LINE; i++){ var type = _.sample(this.get("unlockedBuyableCards")) line.push( new DUNGEON_CLASS_MAP[type]({side:"front"})); } },this); }, newRegularBuyableDeck:function(entry){ var deck = []; for ( var i = 0; i < entry.count; i++ ) { var Model = DUNGEON_CLASS_MAP[entry.type]; var model = new Model({ side:"front" }); deck.push( model ); } this.get("regularBuyableCards").push(deck); }, randomUnlockedToBuyable:function(){ var unlocked = this.get("unlockedBuyableCards"); if ( unlocked.length ) { var index = Math.floor(Math.random()*unlocked.length); var type = unlocked[index]; unlocked.splice(index,1); var entry = { type: type, count: 8 }; this.newRegularBuyableDeck(entry); } }, initHeroDeck:function(){ if ( this.get("isShuffleHeroDeck") ) { this.set("heroDeck", _.shuffle(this.get("initHeroDeck"))); } else { this.set("heroDeck", _.clone(this.get("initHeroDeck"))); } }, initSpellBook:function(){ _.each( this.get("initHand"), function(cardName){ var Model = DUNGEON_CLASS_MAP[cardName]; var model = new Model({ side: "front" }); this.get("hand").push( model ); this.getScore(model.get("score")); },this); this.trigger("change:hand"); }, initBonus:function(){ _.each( this.get("initBonus"), function(bonusName){ var Model = LEVEL_UP_BONUS_CLASS_MAP[bonusName]; var model = new Model(); this.get("bonusPool").push( model ); },this); var eachLevelBonus = this.get("bonusEachLevelUp"); if ( eachLevelBonus ) { var Model = LEVEL_UP_BONUS_CLASS_MAP[eachLevelBonus]; this.set("bonusEachLevelUp", new Model()); } }, beAttacked:function(damage){ var hp = this.get("hp"); var realDamage = damage - this.get("defense"); var hpLose = Math.min(hp, realDamage); this.set("hp", hp - hpLose ); return hpLose; }, initAll:function(){ this.initHeroDeck(); this.initDeck(); this.initDiscardDeck(); this.initRegularBuyableCards(); this.initFlowBuyableCards(); this.initSpellBook(); this.initBonus(); }, gainUpgradeChance:function(count){ this.set("upgradeChance", this.get("upgradeChance")+count); }, cullFromDiscard:function(cardModel){ var deck = this.get("discardDeck"); var index = _.indexOf(deck, cardModel); if ( index != -1 ) { deck.splice(index, 1); cardModel.onExile(); this.trigger("change:discardDeck", this); return true; } return false; }, cullFromDeck:function(cardModel){ var deck = this.get("deck"); var index = _.indexOf(deck, cardModel); if ( index != -1 ) { deck.splice(index, 1); cardModel.onExile(); this.trigger("change:deck", this); return true; } return false; }, cullCard:function(cardModel){ if ( !this.cullFromDiscard(cardModel) ) { if ( !this.cullFromDeck(cardModel) ) { } } }, generateHeroModel:function(){ var generateType = this.get("generateHeroType"); if ( generateType === "pool") { var heroType = _.sample(this.get("heroList")) var maxLevel = _.sample(this.get("heroMaxLevelPool")); var level = Math.min(_.sample(this.get("heroLevelPool")), maxLevel); return new HERO_CLASS_MAP[ heroType ]({ level: level, maxLevel: maxLevel }); } else if ( generateType === "deck" ) { var entry = this.get("heroDeck").shift(); if ( entry ) { return new HERO_CLASS_MAP[ entry.type ]({ level: entry.level, maxLevel: entry.maxLevel }); } else return null; } } }) var DungeonCardModel = Backbone.Model.extend({ //地城牌 defaults:function(){ return { name: "", backType:"dungeon", baseCost: 1, cost: 1, baseScore: 0, score: 0, baseUpgradeCost: 0, upgradeCost: 0, side: "back", level: 1, maxLevel: 1, status: "", upgradeable: true, cullable: true, payMoney: 0, payScore: 0, payHp: 0, payCard: 0 } }, initialize:function(){ this.initEvent(); this.initByLevel(); if ( this.get("level") >= this.get("maxLevel") ) { this.maxLevelBonus(); } this.reEvaluate(); }, initEvent:function(){ this.on("change:baseScore", this.evaluateScore, this); this.on("change:baseCost", this.evaluateCost, this); this.on("change:baseUpgradeCost", this.evaluateUpgradeCost, this); this.on("change:level", function(){ this.initByLevel(); if ( this.get("level") >= this.get("maxLevel") ) { this.maxLevelBonus(); } },this); }, reEvaluate:function(){ this.evaluateScore(); this.evaluateCost(); this.evaluateUpgradeCost(); }, initByLevel:function(){ }, maxLevelBonus:function(){ }, evaluateScore:function(){ this.set("score", this.get("baseScore")); }, evaluateCost:function(){ this.set("cost", this.get("baseCost")); }, evaluateUpgradeCost:function(){ this.set("upgradeCost", this.get("baseUpgradeCost")); }, getDescription:function(){ var descs = []; var desc = CARD_TYPE_MAP[this.get("type")]; if ( this.get("subtype") ) { desc = _.reduce(this.get("subtype").split(" "), function(memo, subtype){ return memo + "—" + CARD_SUBTYPE_MAP[subtype]; },desc, this); } if ( this.get("type") !== "item" && this.get("score") ) { desc += " "+this.get("score")+"{[score]}"; } descs[0] = desc; var upgradeAndCullable = ""; if ( !this.get("upgradeable") ) { upgradeAndCullable += "不可升级 " } if ( !this.get("cullable") ) { upgradeAndCullable += "不可被精简" } if ( upgradeAndCullable !== "" ) descs.push(upgradeAndCullable); if ( this.get("payHp") ) { descs.push("{[pay-hp]}翻开本牌时支付"+this.get("payHp")+"{[black-hp]}") } if ( this.get("payMoney") ) { descs.push("{[pay-money]}翻开本牌时支付"+this.get("payMoney")+"{[money]}") } if ( this.get("payScore") ) { descs.push("{[pay-score]}翻开本牌时支付"+this.get("payScore")+"{[score]}") } return descs.join("\n"); }, onDiscard : function(){ this.resetToOrigin(); }, onReveal : function(){ }, onStageReveal: function(dungeonCards){ }, onGain:function(){ if ( this.get("type") !== "item" ) { window.gameModel.getScore(this.get("score")); } }, onExile:function(){ if ( this.get("type") !== "item" ) { window.gameModel.loseScore(this.get("score")); } }, levelUp:function(silent){ var newLevel = this.get("level") + 1; this.set("level", newLevel); this.onLevelUp(); }, onLevelUp:function(){ var ps = this.previous("score"); var cs = this.get("score"); window.gameModel.getScore(cs-ps); }, isMaxLevel:function(){ return this.get("maxLevel") != "NA" && this.get("level") >= this.get("maxLevel"); }, resetToOrigin:function(){ this.set({ attackBuff: 0, attackDebuff: 0 }) }, isEffecting:function(){ return this.get("side") === "front" && !this.get("exiled") }, isNeedPay:function(){ return this.get("payMoney") || this.get("payScore") || this.get("payHp"); }, onPay:function(){ var payMoney = this.get("payMoney"); var payScore = this.get("payScore"); var payHp = this.get("payHp"); if ( (!payMoney || gameModel.get("money") >= payMoney) && (!payScore || gameModel.get("score") >= payScore) && (!payHp || gameModel.get("hp") > payHp) ) { if ( payMoney ) { gameModel.useMoney(payMoney); this.trigger("take", { icon: "money" }); } if ( payHp ) { gameModel.payHp(payHp); this.trigger("take", { icon: "hp" }); } if ( payScore ) { gameModel.payScore(payScore); this.trigger("take", { icon: "score" }); } this.onPaySuccess(); return true; } else { this.onPayFail(); return false; } }, onPayFail:function(){ }, onPaySuccess:function(){ } }) <file_sep>/src/room-card-model.js /** * Created by 赢潮 on 2015/4/12. */ var RoomModel = DungeonCardModel.extend({ //房间 defaults:function(){ return _.extend( DungeonCardModel.prototype.defaults.call(this),{ type: "room" }) }, onTeamEnter:function(team){ }, onTeamPass:function(team){ } }); var BlacksmithModel = RoomModel.extend({ defaults:function(){ return _.extend(RoomModel.prototype.defaults.call(this), { baseCost: 10, name:"blacksmith", displayName:"铁匠铺", maxLevel: "NA", upgradeable: false }) }, getDescription:function(){ var desc = RoomModel.prototype.getDescription.call(this); if ( desc !== "" ) { desc += "\n"; } return desc + "建造地城花费{[money]}减"+this.getEffect()+"(至少1)"; }, getEffect:function(level){ level = level || this.get("level"); return level; }, onGain:function(){ RoomModel.prototype.onGain.call(this); window.gameModel.set("costCut", window.gameModel.get("costCut") + this.getEffect()); }, onExile:function(){ RoomModel.prototype.onExile.call(this); window.gameModel.set("costCut", window.gameModel.get("costCut") - this.getEffect()); }, onLevelUp:function(){ window.gameModel.set("costCut", window.gameModel.get("costCut") + this.getEffect() - this.getEffect(this.get("level")-1) ); } }); var HenDenModel = RoomModel.extend({ defaults:function(){ return _.extend(RoomModel.prototype.defaults.call(this), { baseCost: 10, name:"hen-den", displayName:"鸡窝", maxLevel: 3, upgradeable: true }) }, getDescription:function(){ var desc = RoomModel.prototype.getDescription.call(this); if ( desc !== "" ) { desc += "\n"; } return desc + "地城之心HP上限+"+this.getEffect() }, getEffect:function(level){ level = level || this.get("level"); return level * 5; }, onGain:function(){ RoomModel.prototype.onGain.call(this); window.gameModel.set("maxHp", window.gameModel.get("maxHp") + this.getEffect()); }, onExile:function(){ RoomModel.prototype.onExile.call(this); window.gameModel.set("maxHp", window.gameModel.get("maxHp") - this.getEffect()); window.gameModel.set("hp", Math.min(window.gameModel.get("hp"), window.gameModel.get("maxHp"))); }, onLevelUp:function(){ window.gameModel.set("maxHp", window.gameModel.get("maxHp") + this.getEffect() - this.getEffect(this.get("level")-1) ); }, initByLevel:function(){ var level = this.get("level"); this.set({ baseUpgradeCost: level*10 } ); this.reEvaluate(); } }); var LibraryModel = RoomModel.extend({ defaults:function(){ return _.extend(RoomModel.prototype.defaults.call(this), { baseCost: 10, name:"library", displayName:"图书馆", maxLevel: "NA", upgradeable: false }) }, getDescription:function(){ var desc = RoomModel.prototype.getDescription.call(this); if ( desc !== "" ) { desc += "\n"; } return desc + "魔法手牌上限+"+this.getEffect() }, getEffect:function(level){ level = level || this.get("level"); return level; }, onGain:function(){ RoomModel.prototype.onGain.call(this); window.gameModel.set("maxHand", window.gameModel.get("maxHand") + this.getEffect()); }, onExile:function(){ RoomModel.prototype.onExile.call(this); window.gameModel.set("maxHand", window.gameModel.get("maxHand") - this.getEffect()); }, onLevelUp:function(){ window.gameModel.set("maxHand", window.gameModel.get("maxHand") + this.getEffect() - this.getEffect(this.get("level")-1) ); } }); var PrisonModel = RoomModel.extend({ defaults:function(){ return _.extend(RoomModel.prototype.defaults.call(this), { baseCost: 10, name:"prison", displayName:"监狱", maxLevel: "NA", upgradeable: false }) }, getDescription:function(){ var desc = RoomModel.prototype.getDescription.call(this); if ( desc !== "" ) { desc += "\n"; } return desc + "地城之心升级所需经验减"+(this.getEffect()*window.gameModel.get("cunningEffect"))+"%"; }, getEffect:function(level){ level = level || this.get("level"); return level; }, onGain:function(){ RoomModel.prototype.onGain.call(this); window.gameModel.set("cunning", window.gameModel.get("cunning") + this.getEffect()); }, onExile:function(){ RoomModel.prototype.onExile.call(this); window.gameModel.set("cunning", window.gameModel.get("cunning") - this.getEffect()); }, onLevelUp:function(){ window.gameModel.set("cunning", window.gameModel.get("cunning") + this.getEffect() - this.getEffect(this.get("level")-1) ); } }); var SpoiledFoodModel = RoomModel.extend({ defaults:function(){ return _.extend(RoomModel.prototype.defaults.call(this), { baseCost: 10, name:"spoiled-food", displayName:"腐烂食物", maxLevel: "NA", upgradeable: false }) }, getDescription:function(){ var desc = RoomModel.prototype.getDescription.call(this); if ( desc !== "" ) { desc += "\n"; } return desc + "英雄在酒店少恢复"+this.getEffect()+"{[hp]}"; }, getEffect:function(level){ level = level || this.get("level"); return level; }, onGain:function(){ RoomModel.prototype.onGain.call(this); window.gameModel.set("spoiled", window.gameModel.get("spoiled") + this.getEffect()); }, onExile:function(){ RoomModel.prototype.onExile.call(this); window.gameModel.set("spoiled", window.gameModel.get("spoiled") - this.getEffect()); }, onLevelUp:function(){ window.gameModel.set("spoiled", window.gameModel.get("spoiled") + this.getEffect() - this.getEffect(this.get("level")-1) ); } }); var VaultModel = RoomModel.extend({ defaults:function(){ return _.extend(RoomModel.prototype.defaults.call(this), { baseCost: 5, name:"vault", displayName:"金库", maxLevel: 3, upgradeable: true }) }, getDescription:function(){ var desc = RoomModel.prototype.getDescription.call(this); if ( desc !== "" ) { desc += "\n"; } return desc + "{[money]}上限+"+this.getEffect() }, getEffect:function(level){ level = level || this.get("level"); return level * 4; }, onGain:function(){ RoomModel.prototype.onGain.call(this); window.gameModel.set("maxMoney", window.gameModel.get("maxMoney") + this.getEffect()); }, onExile:function(){ RoomModel.prototype.onExile.call(this); window.gameModel.set("maxMoney", window.gameModel.get("maxMoney") - this.getEffect()); window.gameModel.set("money", Math.min(window.gameModel.get("money"), window.gameModel.get("maxMoney"))); }, onLevelUp:function(){ window.gameModel.set("maxMoney", window.gameModel.get("maxMoney") + this.getEffect() - this.getEffect(this.get("level")-1) ); }, initByLevel:function(){ var level = this.get("level"); this.set({ baseUpgradeCost: level*10+5 } ); this.reEvaluate(); } })<file_sep>/src/upgrade.js /** * Created by 赢潮 on 2015/5/1. */ var showUpgrade = function(options){ var range = ["discard"]; var rangeText = "弃牌堆中" if ( gameModel.get("upgradeRangeLevel") === UPGRADE_RANGE_LEVEL.FROM_DECK ) { range.push("deck"); rangeText = "弃牌堆及牌堆中的" } cc.director.pushScene(new ChooseCardScene({ model: gameModel, range: range, validText: texts.level_up, hint: function(){ var chance = gameModel.get("upgradeChance"); return chance > 0 ? ("你可以升级"+chance+"次"+rangeText+"卡牌") : "升级地城之心以获得升级卡牌的机会"; }, visibleFilter:function(cardModel){ return cardModel.get("upgradeable"); }, validFilter:function(cardModel){ return gameModel.get("upgradeChance") > 0 && cardModel.get("level") < cardModel.get("maxLevel") && gameModel.get("money") >= cardModel.get("upgradeCost"); }, invalidText:function(cardModel){ if ( gameModel.get("upgradeChance") === 0 ) return null; if ( cardModel.get("level") >= cardModel.get("maxLevel") ) return texts.max_level; return null; }, appendIcon:function(cardModel){ if ( cardModel.get("level") >= cardModel.get("maxLevel") ) return null; var cost = cardModel.get("upgradeCost"); var icon = new IconSprite({ image: cc.spriteFrameCache.getSpriteFrame("money-icon.png"), text: cost, fontSize: dimens.buyable_deck_count_font_size, offset: { x: dimens.hero_icon_size.width / 2 - 1, y: dimens.hero_icon_size.height / 2 - 5 } }); icon.attr({ x: dimens.hero_icon_offset.x, y: dimens.hero_icon_offset.y }) return icon; }, onSelectCallback:function(cardModel, chooseCardLayer){ var cost = cardModel.get("upgradeCost"); if (cost <= gameModel.get("money")) { var targetLevel = cardModel.get("level") + 1; var upgradeVersionModel = new DUNGEON_CLASS_MAP[cardModel.get("name")]({ level: targetLevel }); var self = this; window.mainGame.pauseAction(); var layer = new CardDetailLayer({model:upgradeVersionModel, hint: "支付"+cardModel.get("upgradeCost")+"{[money]}将"+cardModel.get("displayName")+"升到"+targetLevel+"级?", choices:[{ text: texts.level_up, callback: function(){ gameModel.useMoney(cardModel.get("upgradeCost")); cardModel.levelUp(); gameModel.set("upgradeChance", gameModel.get("upgradeChance")-1); chooseCardLayer.__renderAll(); layer.close(); }, context: this, textOffset: { x: 150, y: 8 } },{ text: texts.cancel, callback: function(){ layer.close(); }, context: this, textOffset: { x: 150, y: 8 } }]}); chooseCardLayer.addChild(layer, 300); } }, onSelectContext:this })); }<file_sep>/src/app.js var DUNGEON_CARD_PER_STAGE = 4; var MAX_HERO_COUNT = 4; var UILayer = cc.Layer.extend({ ctor:function (options) { this._super(); this.model = options.model this.titleBar = new cc.Sprite(res.title_bar_jpg); this.titleBar.attr({ x: cc.winSize.width/2, y: cc.winSize.height, anchorX: 0.5, anchorY: 1 }) this.addChild(this.titleBar,100); this.scoreIcon = new cc.Sprite(cc.spriteFrameCache.getSpriteFrame("score-icon.png")) this.scoreIcon.attr({ x: dimens.ui_score_icon_position.x, y: dimens.ui_score_icon_position.y, scaleX : 0.5, scaleY : 0.5 }) this.addChild(this.scoreIcon,101) this.scoreLabel = new cc.LabelTTF("", "宋体", dimens.top_bar_label_font_size); this.scoreLabel.attr({ color: colors.top_bar_label, x: dimens.ui_score_icon_position.x + 30, y: dimens.ui_score_icon_position.y - 5 }) this.addChild(this.scoreLabel,101) this.moneyIcon = new cc.Sprite(cc.spriteFrameCache.getSpriteFrame("money-icon.png")) this.moneyIcon.attr({ x: dimens.ui_money_icon_position.x, y: dimens.ui_money_icon_position.y, scaleX : 0.5, scaleY : 0.5 }) this.addChild(this.moneyIcon,101) this.moneyLabel = new cc.LabelTTF("", "宋体", dimens.top_bar_label_font_size); this.moneyLabel.attr({ color: colors.top_bar_label, x: dimens.ui_money_icon_position.x + 30, y: dimens.ui_money_icon_position.y - 5, anchorX : 0 }) this.addChild(this.moneyLabel,101) var closeItem = new cc.MenuItemImage( cc.spriteFrameCache.getSpriteFrame("CloseNormal.png"), cc.spriteFrameCache.getSpriteFrame("CloseSelected.png"), function () { this.openSystemMenu(); }, this); closeItem.attr({ x: cc.winSize.width - 20, y: cc.winSize.height - 20, anchorX: 0.5, anchorY: 0.5 }); var menu = new cc.Menu(closeItem); menu.x = 0; menu.y = 0; this.addChild(menu, 101); }, onEnter:function(){ this._super(); this.__initEvent(); this.__refresh(); }, __refresh:function(){ this.__renderScore(); this.__renderMoney(); }, onExit:function(){ this.model.off(null,null,this); }, __initEvent:function(){ this.model.on("change:score",this.__renderScore, this); this.model.on("change:money change:maxMoney",this.__renderMoney, this); }, __renderScore:function(){ this.scoreLabel.setString( this.model.get("score") ); }, __renderMoney:function(){ this.moneyLabel.setString( this.model.get("money") + " / " + this.model.get("maxMoney") ); }, openSystemMenu:function(){ } }); var MainGameLayer = cc.Layer.extend({ ctor:function (options) { this._super(); this.model = options.model var size = cc.winSize; this.firstHero = true; window.effectIconMananger = new EffectIconManager({ layer:this }); this.__initUI(); this.__initBackground(); this.__initEvent(); this.meeple = new cc.Sprite(cc.spriteFrameCache.getSpriteFrame("meeple.png") ) this.addChild(this.meeple); this.meeple.setVisible(false); this.__resetMeeple(); this.throne = new IconSprite({ image: cc.spriteFrameCache.getSpriteFrame("throne-menu.png"), offset:dimens.throne_label_offset, fontSize: dimens.throne_font_size, fontColor: colors.dungeon_hp_normal }); this.throne.attr({ x: dimens.throne_position.x, y: dimens.throne_position.y, anchorY:0 }); this.addChild(this.throne,20); this.expLabel = new cc.LabelTTF("", "宋体", dimens.throne_font_size); this.expLabel.attr({ color: cc.color(255,0,0,255), x: dimens.throne_position.x, y: dimens.throne_position.y + 16 }) this.addChild(this.expLabel,21); this.__renderDungeonHP(); var bookMenuItem = new cc.MenuItemImage( cc.spriteFrameCache.getSpriteFrame("book-menu.png"), cc.spriteFrameCache.getSpriteFrame("book-menu-selected.png"), this.openBookMenu, this); bookMenuItem.attr({ x: dimens.book_menu_position.x, y: dimens.book_menu_position.y, anchorX: 0.5, anchorY: 0 }); this.bookText = new cc.LabelTTF("", "宋体", dimens.book_font_size); this.bookText.attr({ color: colors.book, x: dimens.book_menu_position.x, y: dimens.book_menu_position.y+dimens.book_label_offset.y }); this.addChild(this.bookText,21); var vaultMenuItem = new cc.MenuItemImage( cc.spriteFrameCache.getSpriteFrame("vault-menu.png"), cc.spriteFrameCache.getSpriteFrame("vault-menu.png"), function(){ }, this); vaultMenuItem.attr({ x: dimens.vault_menu_position.x, y: dimens.vault_menu_position.y, anchorX: 0.5, anchorY: 0 }); this.moneyLabel = new cc.LabelTTF("", "宋体", dimens.vault_font_size); this.moneyLabel.attr({ color: colors.book, x: dimens.vault_menu_position.x, y: dimens.vault_menu_position.y+dimens.vault_label_offset.y }); this.addChild(this.moneyLabel,21); this.dungeonList = new SortableSpriteList({ margin:dimens.dungeon_card_margin }); this.dungeonList.attr({ x: dimens.dungeon_list_position.x, y: dimens.dungeon_list_position.y }) this.dungeonList.setEnabled(false); this.addChild(this.dungeonList,2) this.deckSprite = new DungeonDeckSprite({ array: this.model.get("deck"), side: "back", fontSize : dimens.deck_count_font_size, countLabelOffset: { x: 0, y: -dimens.card_height/2 - dimens.deck_count_font_size }, numberFormat: "%d张" }); this.deckSprite.attr({ x: dimens.deck_position.x, y: dimens.deck_position.y, scaleX : dimens.deck_scale_rate, scaleY : dimens.deck_scale_rate }); this.addChild(this.deckSprite); this.discardDeckSprite = new DungeonDeckSprite({ array: this.model.get("discardDeck"), side: "front", fontSize : dimens.deck_count_font_size, countLabelOffset: { x: 0, y: -dimens.card_height/2 - dimens.deck_count_font_size }, numberFormat: "%d张", cardClass: DiscardCardSprite }); this.discardDeckSprite.attr({ x: dimens.discard_deck_position.x, y: dimens.discard_deck_position.y, scaleX : dimens.deck_scale_rate, scaleY : dimens.deck_scale_rate }); this.addChild(this.discardDeckSprite); this.deckSprite.setDiscardDeck( this.discardDeckSprite, true, "shuffle" ); this.hintLable = new cc.LabelTTF("", "宋体", dimens.hint_font_size); this.hintLable.attr({ color: colors.hint, x: dimens.hint_position.x, y: dimens.hint_position.y }) this.addChild(this.hintLable, 100); this.hintLable.setVisible(false); this.conflictIcon = new cc.Sprite(cc.spriteFrameCache.getSpriteFrame("cross-sword.png")); this.addChild(this.conflictIcon,21); this.conflictIcon.setVisible(false); var buildItem = new cc.MenuItemImage( cc.spriteFrameCache.getSpriteFrame("build-menu.png"), cc.spriteFrameCache.getSpriteFrame("build-menu-selected.png"), function () { this.openBuildMenu(); }, this); buildItem.attr({ x: dimens.build_menu_position.x, y: dimens.build_menu_position.y, anchorX: 0.5, anchorY: 0 }); var upgradeItem = new cc.MenuItemImage( cc.spriteFrameCache.getSpriteFrame("upgrade-menu.png"), cc.spriteFrameCache.getSpriteFrame("upgrade-menu-selected.png"), function () { this.openUpgradeMenu(); }, this); upgradeItem.attr({ x: dimens.upgrade_menu_position.x, y: dimens.upgrade_menu_position.y, anchorX: 0.5, anchorY: 0 }); this.upgradeLabel = new cc.LabelTTF("", "宋体", dimens.vault_font_size); this.upgradeLabel.attr({ color: colors.upgrade_chance_label, x: dimens.upgrade_menu_position.x, y: dimens.upgrade_menu_position.y+dimens.upgrade_label_offset.y }); this.addChild(this.upgradeLabel,21); var menu = new cc.Menu(buildItem,upgradeItem, bookMenuItem, vaultMenuItem); menu.x = 0; menu.y = 0; this.addChild(menu); window.iconSource = { money : this.moneyLabel, "black-hp" : this.throne, score : this.throne } return true; }, newCardToDiscard:function(){ if ( window.newDiscardCardModel ) { var boughtCardSprite = new DUNGEON_SPRITE_CLASS_MAP[ window.newDiscardCardModel.get("name") ]({ model: window.newDiscardCardModel }); boughtCardSprite.attr({ x: window.newDiscardCardPosition.x, y: window.newDiscardCardPosition.y }); this.addChild(boughtCardSprite,60); this.discardCard( boughtCardSprite ); window.newDiscardCardModel = null; window.newDiscardCardPosition = null; } }, onEnter:function(){ this._super(); if ( this.firstHero ) { this.firstHero = false; this.generateHero(); } this.newCardToDiscard(); this.__refresh(); }, __refresh:function(){ this.__renderExp(); this.__renderBook(); this.__renderDungeonHP(); this.__renderMoney(); this.__renderUpgrade(); }, cleanUp:function(){ this.model.off(null,null,this); cc.director.popScene(); }, __initEvent:function(){ this.model.on("change:hp change:maxHp",this.__onDungeonHPChanged,this); this.model.on("change:hp",this.__checkGameOver,this); this.model.on("change:hand change:maxHand",this.__renderBook,this); this.model.on("change:exp change:maxExp",this.__renderExp,this); this.model.on("change:money change:maxMoney",this.__renderMoney,this); this.model.on("change:upgradeChance",this.__renderUpgrade, this); this.model.on("change:deck",function(){ this.deckSprite.__render(); }, this); this.model.on("change:discardDeck",function(){ this.discardDeckSprite.__render(); }, this); var self = this; cc.eventManager.addListener(cc.EventListener.create({ event: cc.EventListener.CUSTOM, eventName: "double-tap", callback: function (event) { var target = event.getUserData(); if (target.side === "front") { window.mainGame.showCardDetailLayer(target.model) } } }), 1); cc.eventManager.addListener(cc.EventListener.create({ event: cc.EventListener.CUSTOM, eventName: "generate-hero-end", callback: function (event) { self.model.set("phase","generate-hero-end"); self.continueMenu.setVisible(true); } }), 1); cc.eventManager.addListener(cc.EventListener.create({ event: cc.EventListener.CUSTOM, eventName: "team-leave-stage", callback: function (event) { self.onTeamLeaveStage(); } }), 1); cc.eventManager.addListener(cc.EventListener.create({ event: cc.EventListener.CUSTOM, eventName: "cast-spell", callback: function (event) { self.onCastSpell.call(self, event.getUserData()); } }), 1); }, __initBackground:function(){ this.background = []; var level = 0; this.background[level] = new cc.Sprite(res.bg0_jpg) this.__resetBackground(); this.addChild(this.background[level],-1) }, __resetBackground:function(){ var level = 0; var y = cc.winSize.height - dimens.top_bar_height - level * dimens.levelHeight; this.background[level].attr({ x: 0, y: y, anchorX: 0, anchorY: 1 }) }, __initUI:function(){ var continueItem = new cc.MenuItemImage( cc.spriteFrameCache.getSpriteFrame("short-normal.png"), cc.spriteFrameCache.getSpriteFrame("short-selected.png"), function () { var phase = this.model.get("phase"); switch ( phase ) { case "generate-dungeon": this.continueMenu.setVisible(false); if ( this.model.get("stageNumber") === 0 ) { cc.log("teamEnterDungeon") this.teamEnterDungeon(); } else { cc.log("teamEnterNextStage") this.teamEnterNextStage(); } break; case "generate-hero-end": this.continueMenu.setVisible(false); this.moveTeamToEntry(); break; case "team-die": this.continueMenu.setVisible(false); this.afterTeamDie(); break; } }, this ); continueItem.attr({ x: dimens.continue_position.x, y: dimens.continue_position.y, anchorX: 0.5, anchorY: 0.5 }); var continueText = buildRichText({ str : texts.continue, fontSize : dimens.build_new_stage_font_size, fontColor: cc.color.BLACK, width: 180, height: 60 }); continueText.attr({ x: 120, y: 25, anchorX : 0.5, anchorY : 0.5 }) continueItem.addChild( continueText ); this.continueMenu = new cc.Menu(continueItem); this.continueMenu.x = 0; this.continueMenu.y = 0; this.addChild(this.continueMenu, 20); this.continueMenu.setVisible(false); this.stageNumberLabel = new cc.LabelTTF("", "宋体", dimens.hint_font_size); this.stageNumberLabel.attr({ x: dimens.stage_number_position.x, y: dimens.stage_number_position.y }); this.addChild(this.stageNumberLabel); this.stageNumberLabel.setVisible(false); this.giveUpItem = new cc.MenuItemImage( cc.spriteFrameCache.getSpriteFrame("long-normal.png"), cc.spriteFrameCache.getSpriteFrame("long-selected.png"), function () { this.onGiveUp(); }, this ); this.giveUpItem.attr({ x: dimens.give_up_position.x, y: dimens.give_up_position.y, anchorX: 0.5, anchorY: 0.5 }); this.giveUpMenu = new cc.Menu(this.giveUpItem); this.giveUpMenu.x = 0; this.giveUpMenu.y = 0; this.addChild(this.giveUpMenu, 20); this.giveUpMenu.setVisible(false); this.buildStageItem = new cc.MenuItemImage( cc.spriteFrameCache.getSpriteFrame("long-normal.png"), cc.spriteFrameCache.getSpriteFrame("long-selected.png"), function () { if ( this.model.get("money") >= this.model.getBuildCost() ) { this.onBuildNewStage(); } else { } }, this ); this.buildStageItem.attr({ x: dimens.build_new_stage_position.x, y: dimens.build_new_stage_position.y, anchorX: 0.5, anchorY: 0.5 }); this.buildStageMenu = new cc.Menu(this.buildStageItem); this.buildStageMenu.x = 0; this.buildStageMenu.y = 0; this.addChild(this.buildStageMenu, 20); this.buildStageMenu.setVisible(false); }, openBuildMenu:function(){ cc.director.pushScene(new BuyCardScene({ model:this.model })); /*this.runningTargets = this.actionManager.pauseAllRunningActions(); var layer = new BuyCardLayer({model:this.model}); this.addChild(layer, 50);*/ }, openUpgradeMenu:function(){ showUpgrade({ model:this.model }) }, onCastSpell:function(options){ var cardModel = options.model; var castingCard = new DUNGEON_SPRITE_CLASS_MAP[cardModel.get("name")]({ model: cardModel }); castingCard.attr({ x: options.x, y: options.y }); this.addChild(castingCard,80); cardModel.on("please-choose-hero", function(options){ options = options || {}; mainGame.showChooseHero(_.extend(options,{ sourceCardSprite: castingCard, onSelectCallback:castingCard.onSelectTarget, onSelectContext: castingCard })); }, this); cardModel.on("please-choose-dungeon", function(options){ options = options || {}; mainGame.showChooseDungeon(_.extend(options,{ sourceCardSprite: castingCard, onSelectCallback:castingCard.onSelectTarget, onSelectContext: castingCard })); }, this); cardModel.on("cast-spell-finish", function(){ cardModel.off(null,null,this); this.model.useSpellCard(cardModel); this.discardCard( castingCard ); mainGame.resumeAction(); }, this); cardModel.onCast({ onCancelCallback:function(){ cardModel.off(null,null,this); castingCard.removeFromParent(true); mainGame.resumeAction(); }, onCancelContext:this }); }, openBookMenu:function(){ if ( this.model.get("hand").length === 0 ) return; mainGame.pauseAction(); var spellBookLayer = new SpellBookLayer({ model: this.model }); spellBookLayer.attr({ y: -300 }); this.addChild(spellBookLayer,150); spellBookLayer.runAction(cc.moveTo(times.book_appear,0,0)); }, __renderDungeonHP:function(){ this.throne.setString( "hp "+this.model.get("hp") + "/" + this.model.get("maxHp") ); }, __onDungeonHPChanged:function(){ var hp = this.model.get("hp"); if ( this.model.previous("hp") != hp ) { var diff = hp - this.model.previous("hp"); if ( diff > 0 ) diff = "+"+diff; effectIconMananger.enqueue(this.throne, { icon: "black-hp-icon", text: diff, offset: {x:0, y:80} }); } this.__renderDungeonHP(); }, __checkGameOver:function(){ if ( this.model.get("hp") <= 0 ) { cc.director.runScene( new GameOverScene() ); } }, __renderBook:function(){ var l = this.model.get("hand").length; this.bookText.setString( l + "/" + this.model.get("maxHand") ); }, __renderExp:function(){ this.expLabel.setString( "exp "+this.model.get("exp") + "/" + this.model.get("maxExp") ) }, __renderMoney:function(){ this.moneyLabel.setString( this.model.get("money") + "/" + this.model.get("maxMoney") ) }, __renderUpgrade:function(){ this.upgradeLabel.setString( this.model.get("upgradeChance") ) }, __resetMeeple:function(){ this.meeple.attr({ x: dimens.meeple_position.x, y: dimens.meeple_position.y, scaleX : 1, scaleY : 1, anchorX: 0.5, anchorY: 0 }); this.meeple.setSpriteFrame( cc.spriteFrameCache.getSpriteFrame("meeple.png") ); this.meeple.setVisible(true); }, generateHero:function(){ if ( gameModel.get("turn") != 0 ) { gameModel.maintainFlowBuyableCards(); } gameModel.increaseTurn(); var team = this.model.get("team"); if ( team.length >= MAX_HERO_COUNT ) { cc.eventManager.dispatchCustomEvent("generate-hero-end"); return; } this.model.set("phase","generate-hero"); var count = gameModel.get("generateHeroNumber"); for ( var i = 0; i < count && team.length < MAX_HERO_COUNT; i++ ) { var heroModel = gameModel.generateHeroModel(); if (!heroModel) { cc.director.runScene(new GameOverScene()); return; } var card = new HeroCardSprite({ model: heroModel, side: "front"}) card.attr({ x: cc.winSize.width + dimens.card_width, y: dimens.team_position.y, name: heroModel.cid }) this.addChild(card, 1, heroModel.cid); team.push(heroModel); heroModel.on("die transform", function () { if (!this.model.isTeamAlive()) { this.teamDie(); } else { this.renderGiveUp(); } }, this); heroModel.on("change:attackHeartPower alive", function () { this.renderGiveUp(); }, this); } this.model.sortTeam(); this.runAction(cc.sequence(cc.delayTime(times.hero_join_team+0.1), cc.callFunc(function(){ cc.eventManager.dispatchCustomEvent("generate-hero-end"); },this))) }, teamEnterDungeon:function(){ this.model.set("phase","team-enter-dungeon"); this.model.set("stageNumber", 0); this.hintLable.setVisible(false); this.dungeonList.setEnabled(false); var meepleX = this.meeple.x + dimens.enter_door_width; this.meeple.runAction(cc.sequence( cc.moveTo( times.one_step, meepleX, this.meeple.y ), cc.callFunc(function(){ _.each( this.model.get("team"), function( heroModel){ if ( heroModel.isAlive() ) heroModel.onEnterDungeon(); },this); },this), cc.callFunc(this.teamEnterNextStage, this) )) }, teamEnterNextStage:function(){ this.model.set("phase","team-enter-stage"); this.model.set("stageNumber", this.model.get("stageNumber") + 1); this.hintLable.setVisible(false); this.dungeonList.setEnabled(false); var moveWidth = this.meeple.x - this.dungeonList.x - dimens.card_width/2; var moveDeep = dimens.dungeon_depth; var stepCount = 8; var stepWidth = moveWidth / stepCount; var stepDeep = moveDeep / stepCount; var meepleArray = []; var bgArray = []; var dungeonArray = []; var meepleX = this.meeple.x; var meepleY = this.meeple.y; var bgY = this.background[0].y; meepleArray.push( cc.scaleTo(times.one_step/2, -1, 1 ) ); bgArray.push( cc.delayTime(times.one_step/2) ); bgY += stepDeep; bgArray.push( cc.moveTo( times.one_step/2, 0, bgY) ); dungeonArray.push( cc.delayTime(times.one_step/2) ); dungeonArray.push( cc.moveBy(times.one_step/2,0, stepDeep) ); for ( var i = 0 ; i < stepCount ; i++ ){ meepleArray.push( cc.moveTo( times.one_step/2, meepleX - stepWidth, meepleY ) ); meepleArray.push( cc.delayTime( times.one_step/2 ) ); meepleX-= stepWidth; bgArray.push( cc.delayTime(times.one_step/2) ); bgY += stepDeep; bgArray.push( cc.moveTo( times.one_step/2, 0, bgY ) ); dungeonArray.push( cc.delayTime(times.one_step/2) ); dungeonArray.push( cc.moveBy( times.one_step/2, 0, stepDeep ) ); } meepleArray.push( cc.scaleTo(times.one_step/2, 1, 1 ) ); meepleArray.push( cc.callFunc(function(){ cc.eventManager.dispatchCustomEvent("team-enter-stage-end"); this.model.set("currentRoomNumber", 0); this.teamEnterStage(); },this)); this.meeple.runAction(cc.sequence(meepleArray)); this.background[0].runAction(cc.sequence(bgArray)); var seq = cc.sequence(dungeonArray); this.dungeonList.runAction(seq); this.stageNumberLabel.runAction(seq.clone()); }, __resetStage:function(){ this.model.set({ stage:[], stageNumber:0 } ); }, teamLeaveDungeon:function(){ this.__resetStage(); var hasDeadHero = _.any(this.model.get("team"),function(heroModel){ return !heroModel.isAlive(); },this); var hasMaxLevelHero = _.any(this.model.get("team"),function(heroModel){ return heroModel.get("leaving"); },this); var sequence = cc.sequence( cc.scaleTo(times.team_teleport_leave, 0.1, 4 ), cc.callFunc(function(){ this.__resetBackground(); this.meeple.attr({ x: dimens.meeple_position.x, y: dimens.meeple_position.y + dimens.teleport_effect_offset }) },this), cc.scaleTo(times.team_teleport_leave, 1, 1 ), cc.callFunc(function(){ _.each( this.model.get("team"),function(heroModel){ if ( heroModel.isAlive() ){ effectIconMananger.enqueue(this.meeple, { icon: "beer-icon", offset: { x : -25, y : 0 } }); heroModel.onPassDungeon(); } },this); },this), cc.delayTime(1), cc.callFunc(this.removeDeadHero,this), cc.delayTime(hasDeadHero?times.hero_join_team:0), cc.callFunc(this.overMaxLevelHeroLeave,this), cc.delayTime(hasMaxLevelHero?times.hero_join_team:0), cc.callFunc(function(){ this.generateHero(); this.__resetMeeple(); },this)); var sequence2 = cc.sequence( cc.moveBy(times.team_teleport_leave, 0, dimens.teleport_effect_offset ), cc.moveBy(times.team_teleport_leave, 0, -dimens.teleport_effect_offset ) ); this.meeple.runAction(sequence); this.meeple.runAction(sequence2); }, removeDeadHero:function(){ this.model.removeDeadHeroFromTeam(); }, overMaxLevelHeroLeave:function(){ this.model.overMaxLevelHeroLeave(); }, moveTeamToEntry:function(){ this.meeple.runAction( cc.sequence( cc.moveTo(times.move_to_entry, dimens.dungeon_entry_position.x+10, dimens.dungeon_entry_position.y), cc.callFunc( function(){ this.generateDungeonStageUntilFull(); }, this) ) ); }, getCurrentDungeonModels:function(){ return _.map( this.dungeonList.sprites, function(sprite){ return sprite.model; },this); }, teamEnterStage:function(){ var dungeonCards = this.getCurrentDungeonModels(); this.model.set("stage", dungeonCards ); _.each( this.model.get("team"), function( heroModel){ if ( heroModel.isAlive() ) heroModel.onEnterStage(dungeonCards); },this); this.teamEnterRoom(); }, teamMoveToNextRoom:function(){ var currentNumber = this.model.get("currentRoomNumber"); if ( this.dungeonList.sprites.length > currentNumber + 1 ) { var distance = this.dungeonList.sprites[currentNumber+1].x - this.dungeonList.sprites[currentNumber].x; var sequence = cc.sequence(cc.moveBy( times.team_move_to_next_room, distance,0), cc.callFunc(function(){ this.model.set("currentRoomNumber", currentNumber + 1 ); this.teamEnterRoom(); },this)); this.meeple.runAction(sequence); } else { //team leave stage var sequence = cc.sequence(cc.moveBy( times.team_move_to_next_room, dimens.card_width/2, 0), cc.callFunc(function(){ var dungeonCards = this.getCurrentDungeonModels(); _.each( this.model.get("team"), function( heroModel){ if ( heroModel.isAlive() ) heroModel.onPassStage(dungeonCards); },this); cc.eventManager.dispatchCustomEvent("team-leave-stage"); },this)); this.meeple.runAction(sequence); } }, renderGiveUp:function(){ if ( this.giveUpText ) this.giveUpText.removeFromParent(true); this.giveUpText = buildRichText({ str : texts.give_up+ "(-"+this.model.getTeamAttackDungeonHeartPower()+"{[black-hp]})", fontSize : dimens.build_new_stage_font_size+2, fontColor: cc.color.BLACK, width: 390, height: 60 }); this.giveUpText.attr({ x: 240, y: 25, anchorX : 0.5, anchorY : 0.5 }); this.giveUpItem.addChild( this.giveUpText ); }, renderBuildStageMenu:function(){ var cost = this.model.getBuildCost(); if ( this.buildStageText ) { this.buildStageText.removeFromParent(true); } this.buildStageText = buildRichText({ str : texts.pay + cost + "{[money]}" + texts.build_new_stage, fontSize : dimens.build_new_stage_font_size, fontColor: cc.color.BLACK, width: 390, height: 60 }); this.buildStageText.attr({ x: 240, y: 25, anchorX : 0.5, anchorY : 0.5 }); this.buildStageMenu.setVisible(true); this.buildStageItem.addChild(this.buildStageText); this.renderGiveUp(); this.giveUpMenu.setVisible(true); }, onTeamLeaveStage:function(){ //user choose build new stage or pass this.hintLable.setVisible(true); this.hintLable.setString(texts.please_choose); this.giveUpMenu.setVisible(true); var cardLeft = this.model.get("deck").length + this.model.get("discardDeck").length; var buildNewText; if ( cardLeft == 0 ) { this.giveUpText = buildRichText({ str : texts.not_enough_card, fontSize : dimens.build_new_stage_font_size, fontColor: cc.color.BLACK, width: 390, height: 60 }); this.giveUpText.attr({ x: 240, y: 20, anchorX : 0.5, anchorY : 0.5 }); this.giveUpMenu.setVisible(true); this.giveUpItem.addChild( this.giveUpText ); } else { // var cost = this.model.getBuildCost(); // if ( cost <= this.model.get("money") ) { // this.buildStageText = buildRichText({ // str : texts.pay + cost + "{[money]}" + texts.build_new_stage, // fontSize : dimens.build_new_stage_font_size, // fontColor: cc.color.BLACK, // width: 390, // height: 60 // }); // this.buildStageText.attr({ // x: 240, // y: 25, // anchorX : 0.5, // anchorY : 0.5 // }); // this.buildStageMenu.setVisible(true); // this.buildStageItem.addChild(this.buildStageText); // // this.giveUpText = buildRichText({ // str : texts.give_up, // fontSize : dimens.build_new_stage_font_size, // fontColor: cc.color.BLACK, // width: 390, // height: 60 // }); // this.giveUpText.attr({ // x: 330, // y: 25, // anchorX : 0.5, // anchorY : 0.5 // }); // this.giveUpMenu.setVisible(true); // this.giveUpItem.addChild( this.giveUpText ); // } else { // this.buildStageText = null; // this.giveUpText = buildRichText({ // str : texts.not_enough_money_1 + cost + texts.not_enough_money, // fontSize : dimens.build_new_stage_font_size, // fontColor: cc.color.BLACK, // width: 390, // height: 60 // }); // this.giveUpText.attr({ // x: 240, // y: 25, // anchorX : 0.5, // anchorY : 0.5 // }); // this.giveUpMenu.setVisible(true); // this.giveUpItem.addChild( this.giveUpText ); // } this.renderBuildStageMenu(); } }, discardCard:function(cardSprite, callback, context, time){ time = time || times.discard_card; cardSprite.model.onDiscard(); var sequence = cc.sequence( cc.moveTo( time , this.discardDeckSprite.x, this.discardDeckSprite.y ), cc.callFunc(function(){ this.discardDeckSprite.putCard(cardSprite); if ( callback ) callback.call(context); },this)) cardSprite.runAction(sequence); cardSprite.runAction(cc.scaleTo(times.draw_card,dimens.deck_scale_rate,dimens.deck_scale_rate)); }, discardAllDungeonCards:function(){ this.stageNumberLabel.setVisible(false); var len = this.dungeonList.sprites.length; for ( var i = len - 1; i >= 0; i --){ var sprite = this.dungeonList.removeSpriteByIndex(i); if ( sprite.model.get("exiled") ) { sprite = null; } else { sprite.model.resetToOrigin(); sprite.model.set("side","front"); this.addChild(sprite); this.discardCard(sprite); } } this.model.set("stage", [] ); }, onGiveUp:function(){ this.hintLable.setVisible(false); this.buildStageMenu.setVisible(false); this.giveUpMenu.setVisible(false); this.giveUpText.removeFromParent(true); this.discardAllDungeonCards(); this.teamAttackDungeonHeart(); }, onBuildNewStage:function(){ this.hintLable.setVisible(false); this.buildStageMenu.setVisible(false); this.giveUpMenu.setVisible(false); this.giveUpText.removeFromParent(true); this.model.useMoney(this.model.getBuildCost()); this.discardAllDungeonCards(); this.generateDungeonStageUntilFull(); }, teamAttackDungeonHeart:function(){ this.conflictIcon.attr({ x: dimens.throne_position.x, y: dimens.throne_position.y + dimens.attack_dungeon_heart_offset - 40, scaleX : 0.5, scaleY : 0.5 }); this.conflictIcon.runAction(cc.sequence( cc.delayTime( times.move_to_dungeon_heart), cc.callFunc(function(){ this.conflictIcon.setVisible(true); },this), cc.scaleTo( times.attack*2, 1,1), cc.callFunc(function(){ this.conflictIcon.setVisible(false); }, this ))) var sequence = cc.sequence( cc.moveTo( times.move_to_dungeon_heart, dimens.throne_position.x, dimens.throne_position.y + dimens.attack_dungeon_heart_offset), cc.moveBy(times.attack, 0, -dimens.hero_attack_offset ), cc.callFunc(function(){ var totalPower = 0; _.each( this.model.get("team"), function(heroModel){ if ( heroModel.isAlive() ) { var power = heroModel.get("attackHeartPower"); heroModel.onAttackHeart(power); totalPower += power; } }); this.model.beAttacked(totalPower); },this), cc.moveBy(times.attack, 0, dimens.hero_attack_offset ), cc.delayTime(0.2), cc.callFunc(function(){ this.teamLeaveDungeon() },this)); this.meeple.runAction(sequence); }, generateItemCard:function(level, team){ var carry=[]; _.each(team,function(heroModel){ _.each(heroModel.get("carry"),function(c){ for ( var i = 0; i < heroModel.get("level"); i++ ) { carry.push(c); } }); },this); if ( !carry.length ) carry.push("potion"); var itemName = _.sample(carry); return new DUNGEON_CLASS_MAP[itemName]({ level: level, side: "front" }); }, teamDie:function() { this.giveUpMenu.setVisible(false); this.buildStageMenu.setVisible(false); cc.log("team die"); var filterTeam = []; var totalLevel = _.reduce(this.model.get("team"), function (memo, heroModel) { if ( !heroModel.get("bite") ) { filterTeam.push(heroModel); return memo + heroModel.get("level"); } else { return memo; } }, 0, this); //meeple disappear var meepleSequence = cc.sequence(cc.scaleTo(0.2, 1, 0.1), cc.callFunc(function () { this.meeple.setSpriteFrame(cc.spriteFrameCache.getSpriteFrame("rip-icon.png")); }, this), cc.scaleTo(0.4, 1, 1), cc.callFunc(function(){ this.model.set("phase","team-die"); this.continueMenu.setVisible(true); },this)); this.meeple.stopAllActions(); this.meeple.runAction(meepleSequence); if ( totalLevel > 0 ) { var itemCard = this.generateItemCard(totalLevel, filterTeam) this.newItemCardSprite = new ItemCardSprite({ model: itemCard }); this.newItemCardSprite.attr({ x: dimens.new_item_card_position.x, y: dimens.new_item_card_position.y }) this.addChild(this.newItemCardSprite, 60); } this.removeDeadHero(); }, afterTeamDie:function(){ this.meeple.setVisible(false); this.discardAllDungeonCards(); this.__resetStage(); if ( this.newItemCardSprite ) { this.discardCard(this.newItemCardSprite, function(){ this.newItemCardSprite = null; this.__resetBackground(); this.__resetMeeple(); this.generateHero(); },this); } else { this.__resetBackground(); this.__resetMeeple(); this.generateHero(); } }, teamEnterRoom:function(){ if ( !this.model.isTeamAlive() ) return; var currentNumber = this.model.get("currentRoomNumber"); var roomSprite = this.dungeonList.sprites[currentNumber]; var dungeonModel = roomSprite.model; if ( dungeonModel.get("side") === "back" || dungeonModel.get("exiled") ) { this.afterTeamEnterRoom() return; } var team = this.model.get("team"); _.each( team, function( heroModel){ if ( heroModel.isAlive() ) heroModel.onEnterRoom(dungeonModel); },this); dungeonModel.onTeamEnter(team); //attack! if ( dungeonModel instanceof MonsterModel ){ this.conflictIcon.setVisible(true); this.conflictIcon.attr({ x: this.meeple.x + dimens.conflict_icon_offset.x, y: this.meeple.y + dimens.conflict_icon_offset.y + 24, scaleX : 0.5, scaleY : 0.5 }); this.conflictIcon.runAction(cc.sequence( cc.scaleTo( times.attack*2, 1,1), cc.callFunc( function(){ this.conflictIcon.setVisible(false); }, this ))) var sequenceMeeple = cc.sequence( cc.moveBy(times.attack, 0, -dimens.hero_attack_offset ), cc.moveBy(times.attack, 0, dimens.hero_attack_offset )); this.meeple.runAction(sequenceMeeple); var sequenceMonster = cc.sequence( cc.moveBy(times.attack, 0, dimens.monster_attack_offset ), cc.callFunc(function(){ dungeonModel.onAttackTeam(team); },this), cc.moveBy(times.attack, 0, -dimens.monster_attack_offset ), cc.callFunc(this.afterTeamEnterRoom,this)); roomSprite.runAction(sequenceMonster); } else if ( dungeonModel instanceof RoomModel || dungeonModel instanceof TrapModel ){ var sequenceMeeple = cc.sequence( cc.moveBy(times.attack, 0, -dimens.hero_attack_offset-dimens.monster_attack_offset ), cc.moveBy(times.attack, 0, dimens.hero_attack_offset+dimens.monster_attack_offset ), cc.callFunc(this.afterTeamEnterRoom,this)); this.meeple.runAction(sequenceMeeple); } else if ( dungeonModel instanceof ItemModel ){ var sequenceMeeple = cc.sequence( cc.moveBy(times.attack, 0, -dimens.hero_attack_offset-dimens.monster_attack_offset ), cc.callFunc(function(){ roomSprite.runAction(cc.moveBy(times.get_item, 0, dimens.card_height/2+25)); roomSprite.runAction(cc.scaleTo(times.get_item, 0.1, 0.1)); },this), cc.delayTime(times.get_item), cc.callFunc(function(){ dungeonModel.onTeamGet(team); roomSprite.setVisible(false); },this), cc.moveBy(times.attack, 0, dimens.hero_attack_offset+dimens.monster_attack_offset ), cc.callFunc(this.afterTeamEnterRoom,this)); this.meeple.runAction(sequenceMeeple); } }, afterTeamEnterRoom:function(dungeonModel){ if ( this.model.isTeamAlive()) { _.each( this.model.get("team"), function( heroModel){ if ( heroModel.isAlive() ) heroModel.onPassRoom(dungeonModel); },this); if ( this.model.isTeamAlive() ) { this.teamMoveToNextRoom(); } } }, generateDungeonStageUntilFull:function(){ this.model.set("phase","generate-dungeon"); this.dungeonList.attr({ y: dimens.dungeon_list_position.y }) this.generateDungeonStage(); this.stageNumberLabel.setVisible(true); this.stageNumberLabel.attr({ y: dimens.stage_number_position.y }) this.stageNumberLabel.setString("第"+(1+this.model.get("stageNumber"))+"层地城"); }, generateDungeonStage:function(){ if ( this.dungeonList.sprites.length >= DUNGEON_CARD_PER_STAGE ) { var dungeonCards = this.getCurrentDungeonModels(); _.each(dungeonCards,function(card){ card.onStageReveal(dungeonCards); },this); cc.eventManager.dispatchCustomEvent("generate-dungeon-end"); //show hint this.hintLable.setVisible(true); this.hintLable.setString(texts.you_can_arrange_dungeon_card); //show choice this.continueMenu.setVisible(true); //enable sort this.dungeonList.setEnabled(true); var dungeonCards = this.getCurrentDungeonModels(); this.model.set("stage", dungeonCards ); return; } var self = this; this.deckSprite.drawCard(function(cardSprite){ if ( !cardSprite ) return; cardSprite.attr({ x: this.deckSprite.getPosition().x, y: this.deckSprite.getPosition().y, scaleX: dimens.deck_scale_rate, scaleY: dimens.deck_scale_rate }) this.addChild(cardSprite,60); var doorCardSequence = cc.sequence(cardSprite.getFlipToBackSequence(), cc.callFunc(function () { this.dungeonList.addSprite( cardSprite, -1); }, this), cc.callFunc(function () { this.generateDungeonStage(); }, this)); var hullHandSpellSequence = cc.sequence( cc.moveTo(times.draw_card, dimens.book_menu_position), doorCardSequence); var normalSpellSequence = cc.sequence( cc.callFunc(function () { this.runAction(cc.scaleTo(times.draw_card, 0.5, 0.5)); }, cardSprite), cc.moveTo(times.draw_card, dimens.book_menu_position), cc.callFunc(function () { this.model.getSpellCard(cardSprite); }, this), cc.callFunc(function () { this.generateDungeonStage(); }, this)); var normalDungeonCardSequence = cc.sequence(cc.callFunc(function(){ cardSprite.model.onReveal(); this.dungeonList.addSprite( cardSprite, -1); },this), cc.callFunc(function(){ this.generateDungeonStage(); },this)); var revealSequence = cc.sequence( cc.moveTo(times.draw_card, dimens.draw_card_position), cardSprite.getFlipSequence(), cc.callFunc(function(){ if ( cardSprite.model.isNeedPay() ) { var nextSequence = null; var paySuccess = cardSprite.model.onPay(); cardSprite.runAction( new cc.sequence(cc.delayTime( times.pay ), new cc.callFunc( function(){ cardSprite.runAction(nextSequence); },this) ) ); if (paySuccess) { if (cardSprite.model.get("type") == "spell") { if (self.model.isFullHand()) { nextSequence = hullHandSpellSequence; } else { nextSequence = normalSpellSequence; } } else { nextSequence = normalDungeonCardSequence; } } else { nextSequence = doorCardSequence; } } else { var nextSequence = null; if (cardSprite.model.get("type") == "spell") { if (self.model.isFullHand()) { nextSequence = hullHandSpellSequence; } else { nextSequence = normalSpellSequence; } } else { nextSequence = normalDungeonCardSequence; } cardSprite.runAction(nextSequence); } }) ); // var sequence; // if ( cardSprite.model.get("type") == "spell" ) { // if ( this.model.isFullHand() ) { // sequence = cc.sequence( // cc.moveTo(times.draw_card, dimens.draw_card_position), // cardSprite.getFlipSequence(), // cc.moveTo(times.draw_card, dimens.book_menu_position), // cardSprite.getFlipToBackSequence(), // cc.callFunc(function () { // this.dungeonList.addSprite( cardSprite, -1); // }, this), // cc.callFunc(function () { // this.generateDungeonStage(); // }, this)); // } else { // sequence = cc.sequence( // cc.moveTo(times.draw_card, dimens.draw_card_position), // cardSprite.getFlipSequence(), // cc.callFunc(function () { // this.runAction(cc.scaleTo(times.draw_card, 0.5, 0.5)); // }, cardSprite), // cc.moveTo(times.draw_card, dimens.book_menu_position), // cc.callFunc(function () { // this.model.getSpellCard(cardSprite); // }, this), // cc.callFunc(function () { // this.generateDungeonStage(); // }, this)); // } // } else { // sequence = cc.sequence( // cc.moveTo(times.draw_card, dimens.draw_card_position), // cardSprite.getFlipSequence(), // cc.callFunc(function(){ // cardSprite.model.onReveal(); // this.dungeonList.addSprite( cardSprite, -1); // },this), cc.callFunc(function(){ // this.generateDungeonStage(); // },this)); // } cardSprite.runAction(cc.scaleTo(times.draw_card,1,1)); cardSprite.runAction(revealSequence); }, this); }, getHeroSpriteByModel:function(heroModel){ return this.getChildByName(heroModel.cid); }, getDungeonSpriteByModel:function(dungeonModel){ return this.getChildByName(dungeonModel.cid); } }); var MainGameScene = cc.Scene.extend({ onEnter:function () { this._super(); if ( window.gameModel ) return false; window.gameModel = new GameModel(); window.gameModel.initAll(); var layer = new MainGameLayer({model:window.gameModel}); window.mainLayer = layer; this.addChild(layer); var uiLayer = new UILayer({model:window.gameModel}); this.addChild(uiLayer,100); return true; }, showCardDetailLayer:function(cardModel){ this.pauseAction(); var layer = new CardDetailLayer({model:cardModel}); cc.director.getRunningScene().addChild(layer, 300); }, pauseAction:function(){ var targets = this.actionManager.pauseAllRunningActions(); if ( this.runningTargetStack == null ) this.runningTargetStack = []; this.runningTargetStack.push(targets); }, resumeAction:function(){ var targets = this.runningTargetStack.pop(); this.actionManager.resumeTargets(targets); }, showChooseHero:function(options){ this.pauseAction(); var layer = new ChooseHeroLayer(_.extend(options,{ gameModel: window.gameModel })); cc.director.getRunningScene().addChild(layer, 300); }, showChooseDungeon:function(options){ this.pauseAction(); var layer = new ChooseDungeonLayer(_.extend(options,{ gameModel: window.gameModel })); cc.director.getRunningScene().addChild(layer, 300); }, showLevelUp:function(callback,context){ cc.director.pushScene(new LevelUpScene({ model:window.gameModel, callback:callback, context:context })); } }); <file_sep>/src/spell-card-sprite.js /** * Created by 赢潮 on 2015/2/27. */ var SpellCardSprite = BaseCardSprite.extend({ ctor: function( options ){ this._super( options ) //add attack icon and label this.attackIcon = new IconSprite({ image:cc.spriteFrameCache.getSpriteFrame("attack-icon.png") }); this.attackIcon.attr({ x: dimens.card_width - dimens.hero_icon_offset.x, y: dimens.card_height - dimens.hero_icon_offset.y }); this.addChild(this.attackIcon,1); this.addFrontSprite( this.attackIcon ); }, __refresh:function(){ this._super(); this.renderAttack(); }, __initEvent:function(){ BaseCardSprite.prototype.__initEvent.call(this); this.model.on("change:attack",this.renderAttack, this); }, renderAttack:function(){ if ( this.model.get("attack") === 0 ) { this.attackIcon.opacity = 0; } else { this.attackIcon.opacity = 255; this.attackIcon.setString(this.model.get("attack")) } } }); var MagicMissileCardSprite = SpellCardSprite.extend({ onSelectTarget:function(heroModel){ var heroSprite = mainLayer.getHeroSpriteByModel( heroModel ); if ( heroSprite ) { effectIconMananger.fly(this, heroSprite, { icon: "attack", callback: function(){ this.model.onSelectTarget(heroModel) }, context: this }); } else { this.model.onSelectTarget(heroModel); } } }); var FireballCardSprite = SpellCardSprite.extend({ onSelectTarget:function(heroModel){ var heroSprite = mainLayer.getHeroSpriteByModel( heroModel ); if ( heroSprite ) { effectIconMananger.fly(this, heroSprite, { icon: "attack", callback: function(){ this.model.onSelectTarget(heroModel) }, context: this }); } else { this.model.onSelectTarget(heroModel); } } }); var WarDrumCardSprite = SpellCardSprite.extend({ onSelectTarget:function(dungeonModel){ var dungeonSprite = mainLayer.getDungeonSpriteByModel( dungeonModel ); if ( dungeonSprite ) { effectIconMananger.fly(this, dungeonSprite, { icon: "attack", callback: function(){ this.model.onSelectTarget(dungeonModel) }, context: this }); } else { this.model.onSelectTarget(dungeonModel); } } });<file_sep>/src/scenario.js var ScenarioModel = Backbone.Model.extend({ defaults:function(){ return { name: "", description: "" } }, getDescription:function(){ return this.get("description"); } });<file_sep>/src/libs/utils.js if ( !Math.log10 ){ Math.log10 = function(num){ return Math.log(num)/Math.log(10) } } if ( !String.prototype.contains ) { String.prototype.contains = function(str){ return this.indexOf(str) > -1; } } window.clone = function(obj){ return JSON.parse( JSON.stringify(obj) ); } window.isInArray = function(array, item){ for ( var i = 0 ; i < array.length; i++ ){ if ( array[i] == item ) return true; } return false; } window.isValidInt = function (value) { if (value.length == 0) { return false; } var intValue = parseInt(value, 10); if (intValue.toString() === "NaN") { return false; } return true; } window.isFunction=function(obj){ return Object.prototype.toString.call(obj) === "[object Function]"; } window.isString = function(obj){ return typeof obj == 'string' || obj instanceof String; } /* * encodeURI replaces each instance of certain characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character. * Each one in the escape sequences is represented in the format of ‘%NN’, where ‘N’ is one Hex number. * * @return the UTF-8 byte length of a string. */ function utf8ByteLength(str) { if (!str) return 0; var escapedStr = encodeURI(str); var match = escapedStr.match(/%/g); return match ? (escapedStr.length - match.length *2) : escapedStr.length; } /* * The method charCodeAt returns the numeric Unicode value of the character at the given index. * * @return the unicode byte length of a string. */ function unicodeByteLength(str) { if (!str) return 0; var ch; var count = 0; for ( var i = 0; i < str.length; i++) { ch = str.charCodeAt(i); do { count++; ch = ch >> 8; // shift value down by 1 byte } while (ch); } return count; } /* * The DBSC encodes , like BIG5,GBK , use two bytes to represent a none-ASCII character, which is represented by multiple bytes in Unicode. * * @return the double-byte character set (DBCS) byte length of a string. */ function dbcsByteLength(str) { if (!str) return 0; var count = 0; for ( var i = 0; i < str.length; i++) { count++; if(str.charCodeAt(i) >> 8) count++; } return count; }
7c25347b79ea130c965086084640240966bf7e70
[ "JavaScript" ]
20
JavaScript
eastfire/dungeon-deck
f4066812fd56c2c34d1ad4dbdd0193489193efb9
05eac74d8cc5e253d3278ce4756c0ce03cca0839
refs/heads/master
<repo_name>kfgodel/komprension<file_sep>/src/main/kotlin/info/kfgodel/komprension/impl/enumeration/NoOutputStrategy.kt package info.kfgodel.komprension.impl.enumeration import java.nio.ByteBuffer /** * This type represents the element enumeration for the empty set (no bytes) * Date: 5/7/20 - 17:04 */ class NoOutputStrategy : EnumerationStrategy { override fun enumerate(): ByteBuffer { return ByteBuffer.allocate(0) } }<file_sep>/src/test/kotlin/info/kfgodel/komprension/ext/Flow.kt package info.kfgodel.komprension.ext import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.fold import kotlinx.coroutines.runBlocking import java.nio.ByteBuffer /** * Extension methods to ease testing of Flows * Date: 28/6/20 - 18:55 */ /** * Collects all the byte arrays in the flow to a single joined array with the contents of each.<br> * Because the nature of this method, calling it may consume all available memory if the underlying flow * is not limited */ @ExperimentalCoroutinesApi fun Flow<ByteBuffer>.collectToByteArray(): ByteArray = runBlocking { fold(ByteArray(0)) { array, buffer -> array.plus(buffer.getByteArray()) } } /** * Creates a flow of bytebuffer describing each byte.<br> * Using this function the flow will contain only 1 buffer */ fun flowOfByteBuffer(vararg bytes: Byte): Flow<ByteBuffer> { return flowOf(byteBufferOf(*bytes)) }<file_sep>/src/test/kotlin/info/kfgodel/komprension/impl/comprehension/NoComprehensionHeuristicTest.kt package info.kfgodel.komprension.impl.comprehension import info.kfgodel.jspek.api.JavaSpecRunner import info.kfgodel.jspek.api.KotlinSpec import info.kfgodel.komprension.ext.byteBufferOf import info.kfgodel.komprension.ext.collectToByteArray import info.kfgodel.komprension.impl.Komprenser import info.kfgodel.komprension.impl.UNCOMPRESSED_FUNCTION import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flowOf import org.assertj.core.api.Assertions import org.junit.runner.RunWith /** * This class verifies that no comprehension algorithm handles some cases correctly * Date: 9/7/20 - 17:17 */ @ExperimentalCoroutinesApi @RunWith(JavaSpecRunner::class) class NoComprehensionHeuristicTest : KotlinSpec() { override fun define() { describe("a no comprehension heuristic") { val compressor by let { Komprenser().compressor() } it("joins input chunks into a single output chunk") { val input = flowOf(byteBufferOf(2, 6, 3, 10, 23), byteBufferOf(110, 84, 91, -44, -43)) val output = compressor().invoke(input) Assertions.assertThat(output.collectToByteArray()) .containsExactly(UNCOMPRESSED_FUNCTION, 10 /*size*/, 2, 6, 3, 10, 23, 110, 84, 91, -44, -43) } } } }<file_sep>/src/test/kotlin/info/kfgodel/komprension/impl/enumeration/ConstantValueStrategyTest.kt package info.kfgodel.komprension.impl.enumeration import info.kfgodel.jspek.api.JavaSpecRunner import info.kfgodel.jspek.api.KotlinSpec import info.kfgodel.komprension.ext.byteBufferOf import info.kfgodel.komprension.ext.collectToByteArray import info.kfgodel.komprension.impl.CONSTANT_FUNCTION import info.kfgodel.komprension.impl.Komprenser import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flowOf import org.assertj.core.api.Assertions import org.junit.runner.RunWith /** * This class verifies that constant enumeration algorithm handles some cases correctly * Date: 9/7/20 - 17:17 */ @ExperimentalCoroutinesApi @RunWith(JavaSpecRunner::class) class ConstantValueStrategyTest : KotlinSpec() { override fun define() { describe("a constant value strategy") { val decompressor by let { Komprenser().decompressor() } it("can handle a header split into different input chunks") { val input = flowOf(byteBufferOf(CONSTANT_FUNCTION, 10 /*count*/), byteBufferOf(5)) val output = decompressor().invoke(input) Assertions.assertThat(output.collectToByteArray()).containsExactly(5, 5, 5, 5, 5, 5, 5, 5, 5, 5) } it("generates an output chunk for each occurrence") { val input = flowOf(byteBufferOf(CONSTANT_FUNCTION, 4, 5, CONSTANT_FUNCTION, 4, 6)) val output = decompressor().invoke(input) Assertions.assertThat(output.collectToByteArray()).containsExactly(5, 5, 5, 5, 6, 6, 6, 6) } } } }<file_sep>/src/main/kotlin/info/kfgodel/komprension/impl/DefaultCompressor.kt package info.kfgodel.komprension.impl import info.kfgodel.komprension.api.Compressor import info.kfgodel.komprension.ext.forward import info.kfgodel.komprension.impl.comprehension.ComprehensionHeuristic import info.kfgodel.komprension.impl.comprehension.ConstantValueHeuristic import info.kfgodel.komprension.impl.comprehension.NoComprehensionHeuristic import info.kfgodel.komprension.impl.comprehension.NoInputHeuristic import info.kfgodel.komprension.impl.memory.BufferedMemory import info.kfgodel.komprension.impl.memory.WorkingMemory import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.onEach import java.nio.ByteBuffer /** * This type is the default implementation of a Komprension compressor * Date: 28/6/20 - 19:35 */ class DefaultCompressor: Compressor { @ExperimentalCoroutinesApi override fun invoke(input: Flow<ByteBuffer>): Flow<ByteBuffer> { return flow { val workingMemory = BufferedMemory() // Half-there. Use memory to accummulate all input input.onEach { inputChunk -> workingMemory.include(inputChunk) }.collect() do { val smallestRepresentation = getAvailableHeuristics(workingMemory) .map { comp -> comp.comprehend() } .filterNotNull() .reduce { aRep, otherRep -> if (aRep.outputSize() < otherRep.outputSize()) aRep else otherRep } emit(smallestRepresentation.outputData()) workingMemory.inputData().forward(smallestRepresentation.inputSize()) } while(workingMemory.inputData().hasRemaining()) } } private fun getAvailableHeuristics(workingMemory: WorkingMemory): Sequence<ComprehensionHeuristic> { return sequenceOf( NoInputHeuristic(workingMemory), ConstantValueHeuristic(workingMemory), NoComprehensionHeuristic(workingMemory) ) } } <file_sep>/src/main/kotlin/info/kfgodel/komprension/impl/DefaultDecompressor.kt package info.kfgodel.komprension.impl import info.kfgodel.komprension.api.Decompressor import info.kfgodel.komprension.impl.enumeration.ConstantValueStrategy import info.kfgodel.komprension.impl.enumeration.MemoryChunkStrategy import info.kfgodel.komprension.impl.enumeration.NoOutputStrategy import info.kfgodel.komprension.impl.memory.BufferedMemory import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.onEach import java.nio.ByteBuffer /** * This type is the default implementation of a Komprension decompressor * Date: 28/6/20 - 19:36 */ class DefaultDecompressor : Decompressor { @ExperimentalCoroutinesApi override fun invoke(input: Flow<ByteBuffer>): Flow<ByteBuffer> { return flow { val workingMemory = BufferedMemory() // Half-there. Use memory to accummulate all input input.onEach { inputChunk -> workingMemory.include(inputChunk) }.collect() while(workingMemory.inputData().hasRemaining()){ val functionType = workingMemory.inputData().get() // Consume first available byte val output:ByteBuffer = when (functionType) { EMPTY_FUNCTION -> NoOutputStrategy().enumerate() CONSTANT_FUNCTION -> ConstantValueStrategy(workingMemory).enumerate() UNCOMPRESSED_FUNCTION -> MemoryChunkStrategy(workingMemory).enumerate() else -> throw IllegalArgumentException("Unknown function type: $functionType") } if(output.hasRemaining()){ emit(output) } } } } } <file_sep>/src/main/kotlin/info/kfgodel/komprension/impl/comprehension/ByteRepresentation.kt package info.kfgodel.komprension.impl.comprehension import java.nio.ByteBuffer /** * This type represents buffer of bytes that when enumerated, can reproduce a larger buffer of bytes.<br> * Instances of this type are produced by an heuristic when patterns can be found on larger buffers and * encoded into smaller representations * * Date: 10/7/20 - 21:27 */ interface ByteRepresentation { /** * Returns the bytes that compose this representation in a buffer */ fun outputData(): ByteBuffer /** * Indicates the amount of bytes required to store the output data of this representation */ fun outputSize() = outputData().remaining() /** * Indicates the amount of bytes the original data required for storage before representation */ fun inputSize(): Int }<file_sep>/src/main/kotlin/info/kfgodel/komprension/api/Decompressor.kt package info.kfgodel.komprension.api import kotlinx.coroutines.flow.Flow import java.nio.ByteBuffer /** * This interface defines the minimum contract a decompressor requires to be used in Komprension.<br> * It transforms a flow of compressed bytes into an un-compressed flow of bytes, restoring original data * * Date: 27/6/20 - 17:08 */ interface Decompressor : (Flow<ByteBuffer>) -> Flow<ByteBuffer> { }<file_sep>/src/test/kotlin/info/kfgodel/komprension/CompressionBasicCasesTest.kt package info.kfgodel.komprension import info.kfgodel.jspek.api.JavaSpecRunner import info.kfgodel.jspek.api.KotlinSpec import info.kfgodel.komprension.ext.collectToByteArray import info.kfgodel.komprension.ext.flowOfByteBuffer import info.kfgodel.komprension.impl.CONSTANT_FUNCTION import info.kfgodel.komprension.impl.EMPTY_FUNCTION import info.kfgodel.komprension.impl.Komprenser import info.kfgodel.komprension.impl.UNCOMPRESSED_FUNCTION import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.emptyFlow import org.assertj.core.api.Assertions.assertThat import org.junit.runner.RunWith import java.nio.ByteBuffer /** * This test verifies on an integration level the basic cases a Komprenser must support * Date: 6/5/20 - 00:49 */ @ExperimentalCoroutinesApi @RunWith(JavaSpecRunner::class) class CompressionBasicCasesTest : KotlinSpec() { override fun define() { describe("a compressor") { val compressor by let { Komprenser().compressor() } it("uses the empty function type when an empty flow is passed") { val input = emptyFlow<ByteBuffer>() val output = compressor().invoke(input) assertThat(output.collectToByteArray()).containsExactly(EMPTY_FUNCTION) } it("uses the empty function type when a flow with no bytes is passed") { val input = flowOfByteBuffer() val output = compressor().invoke(input) assertThat(output.collectToByteArray()).containsExactly(EMPTY_FUNCTION) } it("uses the uncompressed function type when a flow of random bytes is passed") { val input = flowOfByteBuffer(2, 6, 3, 10, 23, 110, 84, 91, -44, -43) val output = compressor().invoke(input) assertThat(output.collectToByteArray()) .containsExactly(UNCOMPRESSED_FUNCTION, 10 /*size*/, 2, 6, 3, 10, 23, 110, 84, 91, -44, -43) } it("uses the constant function type when a flow with repetitions of a number is passed") { val input = flowOfByteBuffer(5,5,5,5,5, 5,5,5,5,5) val output = compressor().invoke(input) assertThat(output.collectToByteArray()) .containsExactly(CONSTANT_FUNCTION, 10 /*count*/, 5) } } } }<file_sep>/src/main/kotlin/info/kfgodel/komprension/impl/enumeration/ConstantValueStrategy.kt package info.kfgodel.komprension.impl.enumeration import info.kfgodel.komprension.impl.memory.WorkingMemory import java.nio.ByteBuffer /** * This type represents the enumeration of elements in a set with duplicates of only 1 number * Date: 5/7/20 - 17:07 */ class ConstantValueStrategy(private val memory: WorkingMemory) : EnumerationStrategy { override fun enumerate(): ByteBuffer { val input = memory.inputData() // First parameter is repetition count val byteCount = input.get().toInt() val buffer = ByteBuffer.allocate(byteCount) // 2nd parameter is the value val constantValue = input.get() for (i in 1..byteCount) { buffer.put(constantValue) } buffer.flip() return buffer } }<file_sep>/src/test/kotlin/info/kfgodel/komprension/impl/enumeration/MemoryChunkStrategyTest.kt package info.kfgodel.komprension.impl.enumeration import info.kfgodel.jspek.api.JavaSpecRunner import info.kfgodel.jspek.api.KotlinSpec import info.kfgodel.komprension.ext.byteBufferOf import info.kfgodel.komprension.ext.collectToByteArray import info.kfgodel.komprension.impl.Komprenser import info.kfgodel.komprension.impl.UNCOMPRESSED_FUNCTION import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flowOf import org.assertj.core.api.Assertions import org.junit.runner.RunWith /** * This class verifies that memory enumeration algorithm handles some cases correctly * Date: 9/7/20 - 17:17 */ @ExperimentalCoroutinesApi @RunWith(JavaSpecRunner::class) class MemoryChunkStrategyTest : KotlinSpec() { override fun define() { describe("a memory chunk strategy") { val decompressor by let { Komprenser().decompressor() } it("joins its input chunks into a single output chunk") { val input = flowOf(byteBufferOf(UNCOMPRESSED_FUNCTION, 10 /*size*/, 2, 6, 3), byteBufferOf(10, 23, 110, 84, 91, -44, -43)) val output = decompressor().invoke(input) Assertions.assertThat(output.collectToByteArray()).containsExactly(2, 6, 3, 10, 23, 110, 84, 91, -44, -43) } it("generates an output chunk for each occurrence") { val input = flowOf(byteBufferOf(UNCOMPRESSED_FUNCTION, 3, 1, 2, 3, UNCOMPRESSED_FUNCTION, 3, 4, 5, 6)) val output = decompressor().invoke(input) Assertions.assertThat(output.collectToByteArray()).containsExactly(1, 2, 3, 4, 5, 6) } } } }<file_sep>/src/main/kotlin/info/kfgodel/komprension/api/Compressor.kt package info.kfgodel.komprension.api import kotlinx.coroutines.flow.Flow import java.nio.ByteBuffer /** * This interface defines the minimum contract a compressor requires to be used in Komprension.<br> * It transforms a flow of bytes into a compressed flow of bytes, reducing its size (when possible) * * Date: 27/6/20 - 16:23 */ interface Compressor : (Flow<ByteBuffer>) -> Flow<ByteBuffer> { }<file_sep>/src/main/kotlin/info/kfgodel/komprension/impl/enumeration/EnumerationStrategy.kt package info.kfgodel.komprension.impl.enumeration import java.nio.ByteBuffer /** * This type represents a strategy for enumerating the elements of a set as a buffer of bytes.<br> * Each strategy represents a known function that takes the input data as parameters to generate * the output data * * Date: 5/7/20 - 16:07 */ interface EnumerationStrategy { /** * Generates a buffer with the elements of the set enumerated as bytes, taking the input as parameters * for the function to enumerate.<br> */ fun enumerate() : ByteBuffer }<file_sep>/src/main/kotlin/info/kfgodel/komprension/impl/comprehension/ComprehensionHeuristic.kt package info.kfgodel.komprension.impl.comprehension /** * This type represents an ongoing approach to represent input data as a set described with less bytes than received.<br> * The heuristic analyses input data trying to express it as a particular known function with defined parameters.<br> * The result of a successful comprehension heuristic is a buffer of bytes representing the function and its parameters. * Using an EnumerationStrategy the buffer can reproduce the original input.<br> * <br> * Because not every function can reproduce every input data, this heuristic may fail if it cannot find the correct * parameters to make the underlying function reproduce the input data * * Date: 5/7/20 - 15:45 */ interface ComprehensionHeuristic{ /** * Tries to generate a buffer representation of the underlying function and its parameters (if possible). * If not, it returns null */ fun comprehend() : ByteRepresentation? }<file_sep>/src/main/kotlin/info/kfgodel/komprension/impl/memory/BufferedMemory.kt package info.kfgodel.komprension.impl.memory import info.kfgodel.komprension.ext.plus import java.nio.ByteBuffer /** * This memory is backed by a byte buffer where input is appended * Date: 9/7/20 - 17:14 */ class BufferedMemory : WorkingMemory { private var buffer:ByteBuffer = ByteBuffer.allocate(0) //Start empty override fun include(inputChunk: ByteBuffer) { buffer += inputChunk } override fun inputData(): ByteBuffer { return buffer } }<file_sep>/src/main/kotlin/info/kfgodel/komprension/impl/comprehension/BufferToBufferRepresentation.kt package info.kfgodel.komprension.impl.comprehension import java.nio.ByteBuffer /** * This type is a representation where a buffer of bytes represents another bigger buffer * Date: 10/7/20 - 22:08 */ class BufferToBufferRepresentation( private val inputData: ByteBuffer, private val outputData: ByteBuffer ) : ByteRepresentation { override fun outputData(): ByteBuffer { return outputData } override fun inputSize(): Int { return inputData.position() } }<file_sep>/src/main/kotlin/info/kfgodel/komprension/impl/comprehension/NoInputHeuristic.kt package info.kfgodel.komprension.impl.comprehension import info.kfgodel.komprension.ext.byteBufferOf import info.kfgodel.komprension.impl.EMPTY_FUNCTION import info.kfgodel.komprension.impl.memory.WorkingMemory /** * This type represents the comprehension that can describe the empty set * Date: 5/7/20 - 16:14 */ class NoInputHeuristic(private val memory: WorkingMemory) : ComprehensionHeuristic { override fun comprehend(): ByteRepresentation? { val input = memory.inputData() if(input.remaining() > 0){ // Is not empty, cannot represent input return null } val outputData = byteBufferOf(EMPTY_FUNCTION) return BufferToBufferRepresentation(input.slice(), outputData) } }<file_sep>/src/main/kotlin/info/kfgodel/komprension/impl/memory/WorkingMemory.kt package info.kfgodel.komprension.impl.memory import java.nio.ByteBuffer /** * This type represents the shared space of memory where input data is received and comprehension or enumeration * algorithms analyze the data to generate their output.<br> * It helps to view received data as a whole even if it comes in chunks * * Date: 9/7/20 - 17:11 */ interface WorkingMemory { /** * Updates this memory with the latest received chunk to be available for algorithms to move forward their * analysis */ fun include(inputChunk: ByteBuffer) /** * Returns all the received input as a single buffer */ fun inputData(): ByteBuffer }<file_sep>/src/test/kotlin/info/kfgodel/komprension/DecompressionBasicCasesTest.kt package info.kfgodel.komprension import info.kfgodel.jspek.api.JavaSpecRunner import info.kfgodel.jspek.api.KotlinSpec import info.kfgodel.komprension.ext.collectToByteArray import info.kfgodel.komprension.ext.flowOfByteBuffer import info.kfgodel.komprension.impl.CONSTANT_FUNCTION import info.kfgodel.komprension.impl.EMPTY_FUNCTION import info.kfgodel.komprension.impl.Komprenser import info.kfgodel.komprension.impl.UNCOMPRESSED_FUNCTION import kotlinx.coroutines.ExperimentalCoroutinesApi import org.assertj.core.api.Assertions.assertThat import org.junit.runner.RunWith /** * This test verifies on an integration level the basic cases a Komprenser must support * Date: 6/5/20 - 00:49 */ @ExperimentalCoroutinesApi @RunWith(JavaSpecRunner::class) class DecompressionBasicCasesTest : KotlinSpec() { override fun define() { describe("a decompressor") { val decompressor by let { Komprenser().decompressor() } it("returns en empty flow when the empty function is passed") { val input = flowOfByteBuffer(EMPTY_FUNCTION) val output = decompressor().invoke(input) assertThat(output.collectToByteArray()).isEmpty() } it("returns a flow with a chunk of uncompressed data when uncompressed function is passed") { val input = flowOfByteBuffer(UNCOMPRESSED_FUNCTION, 10 /*size*/, 2, 6, 3, 10, 23, 110, 84, 91, -44, -43) val output = decompressor().invoke(input) assertThat(output.collectToByteArray()).containsExactly(2, 6, 3, 10, 23, 110, 84, 91, -44, -43) } it("returns a flow with repetitions of a single number when constant function is passed ") { val input = flowOfByteBuffer(CONSTANT_FUNCTION, 10 /*count*/, 5) val output = decompressor().invoke(input) assertThat(output.collectToByteArray()).containsExactly(5, 5, 5, 5, 5, 5, 5, 5, 5, 5) } } } }<file_sep>/src/main/kotlin/info/kfgodel/komprension/impl/BuiltinFunctions.kt package info.kfgodel.komprension.impl /** * This file declares as contstants all the included functions in Kompression (the well known functions codes) * Date: 27/6/20 - 16:52 */ const val EMPTY_FUNCTION:Byte = -1 const val UNCOMPRESSED_FUNCTION:Byte = -2 const val CONSTANT_FUNCTION:Byte = 0<file_sep>/src/test/kotlin/info/kfgodel/komprension/ext/ByteBufferTest.kt package info.kfgodel.komprension.ext import info.kfgodel.jspek.api.JavaSpecRunner import info.kfgodel.jspek.api.KotlinSpec import kotlinx.coroutines.ExperimentalCoroutinesApi import org.assertj.core.api.Assertions.assertThat import org.junit.runner.RunWith /** * This test verifies extensions added to ByteBuffer * Date: 6/5/20 - 00:49 */ @ExperimentalCoroutinesApi @RunWith(JavaSpecRunner::class) class ByteBufferTest : KotlinSpec() { override fun define() { describe("a ByteBuffer") { val buffer by let { byteBufferOf(1, 2 ,3) } it("can be summed to other buffer to be joined") { val result = buffer() + byteBufferOf(4, 5, 6) assertThat(result.position()).isEqualTo(0) assertThat(result.limit()).isEqualTo(6) assertThat(result).isEqualTo(byteBufferOf(1, 2, 3, 4 ,5, 6)) } it("allows getting remaining bytes as an array") { buffer().position(1) assertThat(buffer().getByteArray()).isEqualTo(byteArrayOf(2, 3)) } it("allows moving the position forward by an amount of bytes") { buffer().forward(2) assertThat(buffer().position()).isEqualTo(2) } it("allows getting the byte without changing the current position") { val currentByte = buffer().getByte() assertThat(currentByte).isEqualTo(1) assertThat(buffer().position()).isEqualTo(0) } } } }<file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <groupId>info.kfgodel</groupId> <artifactId>komprension</artifactId> <version>1.0.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <kotlin.version>1.3.72</kotlin.version> <kotlinx-coroutines.version>1.3.7</kotlinx-coroutines.version> <junit.version>4.12</junit.version> <version.slf4j>1.7.30</version.slf4j> <version.logback>1.2.3</version.logback> <!-- Allow incremental compiler to increase dev speed --> <kotlin.compiler.incremental>true</kotlin.compiler.incremental> </properties> <dependencies> <!-- Base for everything Kotlin related --> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib-jdk8</artifactId> <version>${kotlin.version}</version> </dependency> <!-- Allow co-routines --> <dependency> <groupId>org.jetbrains.kotlinx</groupId> <artifactId>kotlinx-coroutines-core</artifactId> <version>${kotlinx-coroutines.version}</version> </dependency> <!-- Kotlin specific logger wrapper on top of slf4j --> <dependency> <groupId>io.github.microutils</groupId> <artifactId>kotlin-logging</artifactId> <version>1.7.9</version> </dependency> <!-- Standard slf4j loggin api --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${version.slf4j}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${version.slf4j}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>log4j-over-slf4j</artifactId> <version>${version.slf4j}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>${version.logback}</version> <scope>test</scope> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${version.logback}</version> <scope>test</scope> </dependency> <!-- Testing with Kotlin --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-test-junit</artifactId> <version>${kotlin.version}</version> <scope>test</scope> </dependency> <!-- Mock for Kotlin --> <dependency> <groupId>io.mockk</groupId> <artifactId>mockk</artifactId> <version>1.10.0</version> <scope>test</scope> </dependency> <!-- Spec-like tests --> <dependency> <groupId>info.kfgodel</groupId> <artifactId>jspek</artifactId> <version>1.0.0</version> <scope>test</scope> </dependency> <!-- Nice assertions --> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>3.11.1</version> <scope>test</scope> </dependency> </dependencies> <build> <!-- Required to compile sources as indicated by doc --> <sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory> <testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory> <plugins> <!-- Compile kotlin sources. required --> <plugin> <artifactId>kotlin-maven-plugin</artifactId> <groupId>org.jetbrains.kotlin</groupId> <version>${kotlin.version}</version> <configuration> <args> <arg>-Xinline-classes</arg> </args> </configuration> <executions> <execution> <id>compile</id> <phase>compile</phase> <goals> <goal>compile</goal> </goals> </execution> <execution> <id>test-compile</id> <phase>test-compile</phase> <goals> <goal>test-compile</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project> <file_sep>/README.md # komprension Kotlin POC for compressing data by comprehension - Status: Experimental - Phase: Ideation ## Brief description Komprension is a test project to implement a compression algorithm using comprehension to describe the contents of a byte stream. Instead of storing compressed data, Komprension tries to encode different functions that can reproduce the original compressed data. ## Longer description Imagine having to store an infinite file of alternating '1' and '0', and I mean literally infinite. Like in never ending stream of bytes. Common compression methods try to have a single smart algorithm that can compress data into a compact format. However, they fail at having to compress infinite streams of bytes. While not a real case scenario, infinite sized files begs for a different approach. Solving that problem may help on compression really large files which are more common nowadays. Instead of using a single smart algorithm, Komprenssion uses as many as it needs to describe the original data as a sequence of functions. Each reproducing a range of bytes of the original data. Then, it only needs to store the ID of the function to use, and whatever parameters that function needs. In our example, it could represent an infinite stream of alternating 0/1 bytes with only 3 bytes. The first to identify the function that repeats the rest of bytes forever and the next 2 bytes with the starting pair. Based on human communication where common knowledge is shared between parties allowing more economic data transfers, Komprension is designed to be open and extended, so more algorithms can be added as part of the available repertoire of functions to use. This, combined with the ability to share a common server to store functions allows Komprension to be used as an efficient data transfer method. ### About the project This is a proof of concept to test possible implementations of the underlying ideas that make Komprension a feasible compression method. Because its early stage it cannot be used yet and the implementation is still in the phase of ideation. A lot can and will change during development until a stable implementation can be used. When that happens, probably a new project will replace this POC with a user friendlier version <file_sep>/src/main/kotlin/info/kfgodel/komprension/impl/comprehension/ConstantValueHeuristic.kt package info.kfgodel.komprension.impl.comprehension import info.kfgodel.komprension.ext.byteBufferOf import info.kfgodel.komprension.ext.forward import info.kfgodel.komprension.ext.getByte import info.kfgodel.komprension.impl.CONSTANT_FUNCTION import info.kfgodel.komprension.impl.memory.WorkingMemory /** * This type represents the comprehension for input that can be represents by a constant function * * Date: 5/7/20 - 16:30 */ class ConstantValueHeuristic(private val memory: WorkingMemory) : ComprehensionHeuristic { override fun comprehend(): ByteRepresentation? { if(!memory.inputData().hasRemaining()){ return null // No input to take a constant from } val input = memory.inputData().slice() // Create a view from current position val constantValue = input.get() while(input.hasRemaining() && (input.getByte() == constantValue)){ input.forward(1) } val occurrences = input.position() if(occurrences < 3){ return null // This heuristic can't produce a smaller representation } val output = byteBufferOf(CONSTANT_FUNCTION, occurrences.toByte(), constantValue) return BufferToBufferRepresentation(input, output) } }<file_sep>/src/main/kotlin/info/kfgodel/komprension/ext/ByteBuffer.kt package info.kfgodel.komprension.ext import java.nio.ByteBuffer /** * Extensions to ByteBuffer in order to reduce verbosity * Date: 5/7/20 - 01:27 */ /** * Creates an empty byte buffer */ fun emptyBuffer(): ByteBuffer { return ByteBuffer.allocate(0) } /** * Creates a byte buffer from the bytes that make its content */ fun byteBufferOf(vararg bytes: Byte): ByteBuffer { return ByteBuffer.wrap(bytes) } /** * Creates a slice of this buffer starting at the given position */ fun ByteBuffer.sliceFrom(position: Int) : ByteBuffer { this.position(position) return this.slice() } /** * Creates a buffer with the contents of this with the other passed */ operator fun ByteBuffer.plus(other: ByteBuffer): ByteBuffer { val buffer = ByteBuffer.allocate(this.remaining() + other.remaining()) .put(this) .put(other) buffer.flip() // Let it ready to be read return buffer } /** * Reads the remaining bytes in this buffer into a byte array * (from current position to the limit) */ fun ByteBuffer.getByteArray(): ByteArray { val extracted = ByteArray(this.remaining()) this.get(extracted) return extracted } /** * Moves the position forward (positively) as many steps as indicated */ fun ByteBuffer.forward(positions: Int) : ByteBuffer { this.position(this.position() + positions) return this } /** * Gets the byte on the current position without changing it */ fun ByteBuffer.getByte() : Byte { return this.get(this.position()) }<file_sep>/src/test/kotlin/info/kfgodel/komprension/impl/comprehension/ConstantValueHeuristicTest.kt package info.kfgodel.komprension.impl.comprehension import info.kfgodel.jspek.api.JavaSpecRunner import info.kfgodel.jspek.api.KotlinSpec import info.kfgodel.komprension.ext.byteBufferOf import info.kfgodel.komprension.ext.collectToByteArray import info.kfgodel.komprension.impl.CONSTANT_FUNCTION import info.kfgodel.komprension.impl.Komprenser import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flowOf import org.assertj.core.api.Assertions import org.junit.runner.RunWith /** * This class verifies that constant comprehension algorithm handles some cases correctly * Date: 9/7/20 - 17:17 */ @ExperimentalCoroutinesApi @RunWith(JavaSpecRunner::class) class ConstantValueHeuristicTest : KotlinSpec() { override fun define() { describe("a constant value heuristic") { val compressor by let { Komprenser().compressor() } it("joins input chunk with same constant value") { val input = flowOf(byteBufferOf(5,5,5,5,5), byteBufferOf(5,5,5,5,5)) val output = compressor().invoke(input) Assertions.assertThat(output.collectToByteArray()) .containsExactly(CONSTANT_FUNCTION, 10 /*count*/, 5) } it("splits each occurrence as separate chunks") { val input = flowOf(byteBufferOf(3,3,3,3,3), byteBufferOf(6,6,6,6,6)) val output = compressor().invoke(input) Assertions.assertThat(output.collectToByteArray()) .containsExactly(CONSTANT_FUNCTION, 5 , 3, CONSTANT_FUNCTION, 5 , 6) } } } }<file_sep>/src/main/kotlin/info/kfgodel/komprension/impl/Komprenser.kt package info.kfgodel.komprension.impl import info.kfgodel.komprension.api.Compressor import info.kfgodel.komprension.api.Decompressor /** * This class is the default implementation of a compressor using Komprension algorithm * Date: 27/6/20 - 16:26 */ class Komprenser { fun compressor(): Compressor = DefaultCompressor() fun decompressor(): Decompressor = DefaultDecompressor() }<file_sep>/src/main/kotlin/info/kfgodel/komprension/impl/comprehension/NoComprehensionHeuristic.kt package info.kfgodel.komprension.impl.comprehension import info.kfgodel.komprension.impl.UNCOMPRESSED_FUNCTION import info.kfgodel.komprension.impl.memory.WorkingMemory import java.nio.ByteBuffer /** * This class represents the lack of comprehension where the input is reproduced by memorizing the original bytes * instead of using a function to represent it. * * Date: 5/7/20 - 16:18 */ class NoComprehensionHeuristic(private val memory: WorkingMemory) : ComprehensionHeuristic { override fun comprehend(): ByteRepresentation? { val input = memory.inputData().slice() // Create a view to the original buffer val output = addHeaderTo(input) return BufferToBufferRepresentation(input, output) } private fun addHeaderTo(input: ByteBuffer): ByteBuffer { val inputSize = input.remaining() val buffer = ByteBuffer.allocate(2 + inputSize) buffer.put(UNCOMPRESSED_FUNCTION) buffer.put(inputSize.toByte()) buffer.put(input) buffer.flip() return buffer } }<file_sep>/src/main/kotlin/info/kfgodel/komprension/impl/enumeration/MemoryChunkStrategy.kt package info.kfgodel.komprension.impl.enumeration import info.kfgodel.komprension.ext.forward import info.kfgodel.komprension.impl.memory.WorkingMemory import java.nio.ByteBuffer /** * This type represents the enumeration of elements of a set where the elements are previously memorized * Date: 5/7/20 - 17:09 */ class MemoryChunkStrategy(private val memory: WorkingMemory) : EnumerationStrategy { override fun enumerate(): ByteBuffer { val input = memory.inputData() // First parameter is size, which we ignore for now val chunkSize = input.get() // Create a view buffer limited to the declared size val originalData = input.slice() originalData.limit(chunkSize.toInt()) // Consume the bytes from input buffer input.forward(chunkSize.toInt()) return originalData // } }
8706f21bc8682227c3f7b9bd656374c666989f78
[ "Markdown", "Maven POM", "Kotlin" ]
29
Kotlin
kfgodel/komprension
66cb58b8b7062235877951b44ba85c41beceef79
1cf29d8790701d7885da1d128201db2e21680554
refs/heads/master
<file_sep>using Microsoft.Win32; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.IO; using System.Data; using Excel = Microsoft.Office.Interop.Excel; using Microsoft.Office.Interop.Excel; namespace UngDungQuanLy { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : System.Windows.Window { public MainWindow() { InitializeComponent(); string excecutable = System.Reflection.Assembly.GetExecutingAssembly().Location; string path = (System.IO.Path.GetDirectoryName(excecutable)); AppDomain.CurrentDomain.SetData("DataDirectory", path); } bool loadTabHangHoa = false; bool loadTabGiaoDich = false; bool loadTabThongKe = false; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// HÀM XỬ LÝ CHO Button "THOÁT" /// <summary> /// Hàm để thoát phần mềm /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnThoat_Click(object sender, RoutedEventArgs e) { MessageBoxResult MBRs = MessageBox.Show("Bạn có muốn thoát", "Xác nhận", MessageBoxButton.YesNo, MessageBoxImage.Question); if (MBRs == MessageBoxResult.Yes) { this.Close(); } else { return; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// CÁC HÀM XỬ LÝ CHO TAB "HÀNG HÓA" /// <summary> /// Reload dữ liệu cho tab Hàng hóa /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TabHangHoa_PreviewMouseDown(object sender, MouseButtonEventArgs e) { if (loadTabHangHoa == false) { loadTabHangHoa = true; loadTabGiaoDich = false; loadTabThongKe = false; TabHangHoa.IsSelected = true; removeAllTabHangHoa(); ShowTabHangHoa(); lockcontrols(); BtnThem.IsEnabled = false; BtnSua.IsEnabled = false; BtnXoa.IsEnabled = false; } } int pageNumber = 1; int recordNumber = 28; /// <summary> /// Hàm dùng để khóa các control /// </summary> void lockcontrols() { TbTenHangHoa.IsEnabled = false; CbLoai.IsEnabled = false; TbThemChungLoai.IsEnabled = false; TbSoLuong.IsEnabled = false; TbGiaNiemyet.IsEnabled = false; TbGiaBanLe.IsEnabled = false; TbGiaThucTe.IsEnabled = false; DPNgayThem.IsEnabled = false; BtnChonHinh.IsEnabled = false; BtnThemChungLoai.IsEnabled = false; } /// <summary> /// Hàm dùng để mở các control /// </summary> void unlockcontrols() { TbTenHangHoa.IsEnabled = true; CbLoai.IsEnabled = true; TbThemChungLoai.IsEnabled = true; TbSoLuong.IsEnabled = true; TbGiaNiemyet.IsEnabled = true; TbGiaBanLe.IsEnabled = true; TbGiaThucTe.IsEnabled = true; DPNgayThem.IsEnabled = true; BtnChonHinh.IsEnabled = true; BtnThemChungLoai.IsEnabled = true; } void removeAllTabHangHoa() { TbTenHangHoa.Text = ""; CbLoai.Text = ""; TbThemChungLoai.Text = ""; TbSoLuong.Text = ""; TbGiaNiemyet.Text = ""; TbGiaBanLe.Text = ""; TbGiaThucTe.Text = ""; DPNgayThem.Text = ""; ImageProduct.Source = null; } private List<HangHoa> LoadRecord(int page,int recordNum) { List<HangHoa> result = new List<HangHoa>(); using (QuanLyCuaHangEntities db = new QuanLyCuaHangEntities()) { result = db.HangHoa.OrderBy(i=>i.Id). Skip((page - 1) * recordNum).Take(recordNum).ToList(); } return result; } void ShowTabHangHoa() { var db = new QuanLyCuaHangEntities(); //Thêm dữ liệu từ sql (Table ChungLoai) vào combobox "Loai" CbLoai.ItemsSource = db.Procedure_LayTatCaTenLoai().ToList(); //Thêm dữ liệu vào 2 combobox "CbLoaiTimKiem" và "CbLoaiSapXep" string[] ListTimKiem = { "Tìm kiếm theo", "All", "Mã hàng hóa", "Loại", "Tên", "Số lượng", "Giá niêm yết", "Giá bán lẻ", "Giá thực tế", "Ngày cập nhật" }; string[] ListSapXep = { "Sắp xếp theo", "Mới nhất", "Số lượng tăng", "Số lượng giảm", "Giá tăng dần", "Giá giảm dần", "Theo tên A->Z", "Theo tên Z->A", "Theo loại A->Z", "Theo loại Z->A" }; CbLoaiTimKiem.ItemsSource = ListTimKiem.ToList(); CbLoaiSapXep.ItemsSource = ListSapXep.ToList(); CbLoaiTimKiem.SelectedIndex = 0; CbLoaiSapXep.SelectedIndex = 0; //Hiển thị danh sách hàng hóa dataGrid.ItemsSource = LoadRecord(pageNumber, recordNumber); } /// <summary> /// Load dữ liệu lên tab Hàng hóa /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TabHangHoa_Loaded(object sender, RoutedEventArgs e) { lockcontrols(); BtnThem.IsEnabled = false; BtnSua.IsEnabled = false; BtnXoa.IsEnabled = false; ShowTabHangHoa(); } string optionUnlockButton = ""; private void BtnThemHangHoa_Click(object sender, RoutedEventArgs e) { BtnThem.IsEnabled = true; BtnSua.IsEnabled = false; BtnXoa.IsEnabled = false; unlockcontrols(); optionUnlockButton = "add"; } private void BtnSuaHangHoa_Click(object sender, RoutedEventArgs e) { BtnThem.IsEnabled = false; BtnSua.IsEnabled = true; BtnXoa.IsEnabled = false; unlockcontrols(); optionUnlockButton = "edit"; } private void BtnXoaHangHoa_Click(object sender, RoutedEventArgs e) { BtnThem.IsEnabled = false; BtnSua.IsEnabled = false; BtnXoa.IsEnabled = true; unlockcontrols(); TbThemChungLoai.IsEnabled = false; BtnThemChungLoai.IsEnabled = false; optionUnlockButton = "delete"; } String pathImage = ""; /// <summary> /// Hàm để chọn hình từ thư mục /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnChonHinh_Click(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "png files(*.png)|*.png|jpg files (*.jpg)|*.jpg|All files(*.*)|*.*"; if (openFileDialog.ShowDialog() == true) { ImageProduct.Source = new BitmapImage(new Uri(openFileDialog.FileName)); pathImage = openFileDialog.FileName; } } /// <summary> /// Hàm dùng để thêm 1 loại hàng hóa mới /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnThemChungLoai_Click(object sender, RoutedEventArgs e) { if (TbThemChungLoai.Text != "") { var db = new QuanLyCuaHangEntities(); LoaiHangHoa chungloai = new LoaiHangHoa { TenLoai = TbThemChungLoai.Text }; db.LoaiHangHoa.Add(chungloai); db.SaveChanges(); CbLoai.ItemsSource = db.Procedure_LayTatCaTenLoai().ToList(); MessageBox.Show("Thêm thành công"); } else { MessageBox.Show("Bạn cần điền tên chủng loại cần thêm!!!"); } } int id;//Id của hàng hóa đang đươc chọn /// <summary> /// Hàm xử lý khi chọn vào 1 dòng trong DataGrid /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { unlockcontrols(); BtnThem.IsEnabled = false; if (optionUnlockButton=="edit") { BtnSua.IsEnabled = true; BtnXoa.IsEnabled = false; } if (optionUnlockButton == "delete") { BtnSua.IsEnabled = false; BtnXoa.IsEnabled = true; TbThemChungLoai.IsEnabled = false; BtnThemChungLoai.IsEnabled = false; } HangHoa hh = dataGrid.SelectedItem as HangHoa; if(hh != null) { id = hh.Id; TbTenHangHoa.Text = hh.Ten; CbLoai.Text = hh.Loai; TbSoLuong.Text = hh.SoLuong.ToString(); TbGiaNiemyet.Text = hh.GiaNiemYet.ToString(); TbGiaBanLe.Text = hh.GiaBanLe.ToString(); TbGiaThucTe.Text = hh.GiaThucTe.ToString(); DPNgayThem.SelectedDate = hh.NgayCapNhat; if (hh.HinhAnh != null) { try { byte[] imgBytes = (byte[])hh.HinhAnh; MemoryStream ms = new MemoryStream(imgBytes, 0, imgBytes.Length); ms.Write(imgBytes, 0, imgBytes.Length); var imageSource = new BitmapImage(); ms.Position = 0; imageSource.BeginInit(); imageSource.StreamSource = ms; imageSource.EndInit(); ImageProduct.Source = imageSource; } catch { ImageProduct.Source = null; } } else { ImageProduct.Source = null; } } } /// <summary> /// Hàm dùng để thêm 1 hàng hóa mới khi bấm vào button "THÊM" /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnThem_Click(object sender, RoutedEventArgs e) { unlockcontrols(); if (TbTenHangHoa.Text != "" && CbLoai.SelectedItem.ToString() != "" && TbSoLuong.Text != "" && TbGiaBanLe.Text != "" && TbGiaNiemyet.Text != "" && DPNgayThem.Text != "") { try { var hangHoa = new HangHoa(); hangHoa.Loai = CbLoai.SelectedItem.ToString(); hangHoa.Ten = TbTenHangHoa.Text; hangHoa.SoLuong = int.Parse(TbSoLuong.Text); hangHoa.GiaNiemYet = int.Parse(TbGiaNiemyet.Text); hangHoa.GiaBanLe = int.Parse(TbGiaBanLe.Text); hangHoa.NgayCapNhat = DPNgayThem.SelectedDate; if (pathImage != "") { //Chuyển image thành dãy bit FileStream fs; fs = new FileStream(pathImage, FileMode.Open, FileAccess.Read); byte[] picbyte = new byte[fs.Length]; fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length)); fs.Close(); hangHoa.HinhAnh = picbyte; pathImage = ""; } var db = new QuanLyCuaHangEntities(); db.HangHoa.Add(hangHoa); db.SaveChanges(); MessageBox.Show("Thêm thành công"); TBlThongBao.Text = ""; dataGrid.ItemsSource = db.HangHoa.ToList(); } catch { TBlThongBao.Text = "Vui lòng nhập đúng định dạng dữ liệu!!!"; } } else { TBlThongBao.Text = "Vui lòng điền đầy đủ thông tin trước khi thêm!!!"; } } private void BtnSua_Click(object sender, RoutedEventArgs e) { unlockcontrols(); if (TbTenHangHoa.Text != "" && CbLoai.SelectedItem.ToString() != "" && TbSoLuong.Text != "" && TbGiaBanLe.Text != "" && TbGiaNiemyet.Text != "" && DPNgayThem.Text != "") { try { var db = new QuanLyCuaHangEntities(); HangHoa hh = dataGrid.SelectedItem as HangHoa;//chọn 1 dòng từ DataGrid id = hh.Id; var hh1 = db.HangHoa.Find(id); hh1.Loai = CbLoai.SelectedItem.ToString(); hh1.Ten = TbTenHangHoa.Text; hh1.SoLuong = int.Parse(TbSoLuong.Text); hh1.GiaNiemYet = int.Parse(TbGiaNiemyet.Text); hh1.GiaBanLe = int.Parse(TbGiaBanLe.Text); hh1.NgayCapNhat = DPNgayThem.SelectedDate; if (pathImage != "") { //Chuyển image thành dãy bit FileStream fs; fs = new FileStream(pathImage, FileMode.Open, FileAccess.Read); byte[] picbyte = new byte[fs.Length]; fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length)); fs.Close(); hh1.HinhAnh = picbyte; pathImage = ""; } MessageBoxResult MBRs = MessageBox.Show("Bạn chắc chắn muốn sửa", "Xác nhận", MessageBoxButton.YesNo, MessageBoxImage.Question); if (MBRs == MessageBoxResult.Yes) { db.SaveChanges(); TBlThongBao.Text = ""; dataGrid.ItemsSource = db.HangHoa.ToList(); MessageBox.Show("Sửa thành công"); } else { return; } } catch { TBlThongBao.Text = "Vui lòng nhập đúng định dạng dữ liệu!!!"; } } else { TBlThongBao.Text = "Vui lòng điền đầy đủ thông tin trước khi sửa!!!"; } } private void BtnXoa_Click(object sender, RoutedEventArgs e) { MessageBoxResult MBRs = MessageBox.Show("Bạn chắc chắn muốn xóa hàng hóa này?", "Xác nhận", MessageBoxButton.YesNo, MessageBoxImage.Question); if (MBRs == MessageBoxResult.Yes) { TbTenHangHoa.Text = ""; CbLoai.Text = ""; TbSoLuong.Text = ""; TbGiaNiemyet.Text = ""; TbGiaBanLe.Text = ""; TbGiaThucTe.Text = ""; DPNgayThem.SelectedDate = null; ImageProduct.Source = null; HangHoa hh = dataGrid.SelectedItem as HangHoa; var db = new QuanLyCuaHangEntities(); db.Procedure_Xoa1HangHoa(id); dataGrid.ItemsSource = db.HangHoa.ToList(); MessageBox.Show("Xóa thành công"); } else { return; } } /// <summary> /// Hàm thực thi việc sắp xếp các hàng hóa theo một thứ tự nào đó /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CbLoaiSapXep_SelectionChanged(object sender, SelectionChangedEventArgs e) { var db = new QuanLyCuaHangEntities(); if (CbLoaiSapXep.SelectedItem.ToString() == "Sắp xếp theo") { dataGrid.ItemsSource = db.HangHoa.ToList(); } else if (CbLoaiSapXep.SelectedItem.ToString() == "Mới nhất") { dataGrid.ItemsSource = db.HangHoa. SqlQuery("SELECT * FROM HangHoa ORDER BY NgayCapNhat DESC").ToList(); } else if (CbLoaiSapXep.SelectedItem.ToString() == "Số lượng tăng") { dataGrid.ItemsSource = db.HangHoa. SqlQuery("SELECT * FROM HangHoa ORDER BY SoLuong ASC").ToList(); } else if (CbLoaiSapXep.SelectedItem.ToString() == "Số lượng giảm") { dataGrid.ItemsSource = db.HangHoa. SqlQuery("SELECT * FROM HangHoa ORDER BY SoLuong DESC").ToList(); } else if (CbLoaiSapXep.SelectedItem.ToString() == "Giá tăng dần") { dataGrid.ItemsSource = db.HangHoa. SqlQuery("SELECT * FROM HangHoa ORDER BY GiaNiemYet ASC").ToList(); } else if (CbLoaiSapXep.SelectedItem.ToString() == "Giá giảm dần") { dataGrid.ItemsSource = db.HangHoa. SqlQuery("SELECT * FROM HangHoa ORDER BY GiaNiemYet DESC").ToList(); } else if (CbLoaiSapXep.SelectedItem.ToString() == "Theo tên A->Z") { dataGrid.ItemsSource = db.HangHoa. SqlQuery("SELECT * FROM HangHoa ORDER BY CONVERT(nvarchar, Ten) ASC").ToList(); } else if (CbLoaiSapXep.SelectedItem.ToString() == "Theo tên Z->A") { dataGrid.ItemsSource = db.HangHoa. SqlQuery("SELECT * FROM HangHoa ORDER BY CONVERT(nvarchar, Ten) DESC").ToList(); } else if (CbLoaiSapXep.SelectedItem.ToString() == "Theo loại A->Z") { dataGrid.ItemsSource = db.HangHoa. SqlQuery("SELECT * FROM HangHoa ORDER BY CONVERT(nvarchar, Loai) ASC").ToList(); } else if (CbLoaiSapXep.SelectedItem.ToString() == "Theo loại Z->A") { dataGrid.ItemsSource = db.HangHoa. SqlQuery("SELECT * FROM HangHoa ORDER BY CONVERT(nvarchar, Loai) DESC").ToList(); } } /// <summary> /// Hàm thực thi việc tìm kiếm /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnTimKiem_Click(object sender, RoutedEventArgs e) { var db = new QuanLyCuaHangEntities(); if (CbLoaiTimKiem.SelectedItem.ToString() == "Mã hàng hóa") { dataGrid.ItemsSource = db.HangHoa.Where(hh => hh.Id.ToString().Contains(TbTimKiem.Text)).ToList(); } else if (CbLoaiTimKiem.SelectedItem.ToString()=="Loại") { dataGrid.ItemsSource = db.HangHoa.Where(hh => hh.Loai.Contains(TbTimKiem.Text)).ToList(); } else if (CbLoaiTimKiem.SelectedItem.ToString()=="Tên") { dataGrid.ItemsSource = db.HangHoa.Where(hh => hh.Ten.Contains(TbTimKiem.Text)).ToList(); } else if (CbLoaiTimKiem.SelectedItem.ToString() == "Số lượng") { dataGrid.ItemsSource = db.HangHoa. Where(hh => hh.SoLuong.ToString().Contains(TbTimKiem.Text)).ToList(); } else if (CbLoaiTimKiem.SelectedItem.ToString() == "Giá niêm yết") { dataGrid.ItemsSource = db.HangHoa. Where(hh => hh.GiaNiemYet.ToString().Contains(TbTimKiem.Text)).ToList(); } else if (CbLoaiTimKiem.SelectedItem.ToString() == "Giá bán lẻ") { dataGrid.ItemsSource = db.HangHoa. Where(hh => hh.GiaBanLe.ToString().Contains(TbTimKiem.Text)).ToList(); } else if (CbLoaiTimKiem.SelectedItem.ToString() == "Giá thực tế") { dataGrid.ItemsSource = db.HangHoa. Where(hh => hh.GiaThucTe.ToString().Contains(TbTimKiem.Text)).ToList(); } else if (CbLoaiTimKiem.SelectedItem.ToString() == "Ngày cập nhật") { dataGrid.ItemsSource = db.HangHoa. Where(hh => hh.NgayCapNhat.ToString().Contains(TbTimKiem.Text)).ToList(); } else { dataGrid.ItemsSource = db.HangHoa.SqlQuery("SELECT * FROM HangHoa").ToList(); } } /// <summary> /// Phân trang /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnTrangTruoc_Click(object sender, RoutedEventArgs e) { if(pageNumber-1>0) { pageNumber--; TBlTrangHienTai.Text = pageNumber.ToString(); dataGrid.ItemsSource = LoadRecord(pageNumber, recordNumber); } } /// <summary> /// Phân trang /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnTrangSau_Click(object sender, RoutedEventArgs e) { int totalRecord = 0; var db = new QuanLyCuaHangEntities(); totalRecord = db.HangHoa.Count(); if(pageNumber - 1 < totalRecord / recordNumber) { pageNumber++; TBlTrangHienTai.Text = pageNumber.ToString(); dataGrid.ItemsSource = LoadRecord(pageNumber, recordNumber); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// CÁC HÀM XỬ LÝ CHO TAB "GIAO DỊCH" private void TabGiaoDich_PreviewMouseDown(object sender, MouseButtonEventArgs e) { if (loadTabGiaoDich == false) { TabGiaoDich.IsSelected = true; loadTabHangHoa = false; loadTabGiaoDich = true; loadTabThongKe = false; var db = new QuanLyCuaHangEntities(); dataGrid1.ItemsSource = db.HangHoa.ToList(); } } void ShowTabGiaoDich() { string[] ListTimKiem = { "Tìm kiếm theo", "All", "Loại", "Tên", "Số lượng", "Giá bán lẻ" }; CbLoaiTimKiem1.ItemsSource = ListTimKiem.ToList(); CbLoaiTimKiem1.SelectedIndex = 0; } private void TabGiaoDich_Loaded(object sender, RoutedEventArgs e) { ShowTabGiaoDich(); var db = new QuanLyCuaHangEntities(); dataGrid1.ItemsSource = db.HangHoa.ToList(); } private void BtnTimKiem1_Click(object sender, RoutedEventArgs e) { var db = new QuanLyCuaHangEntities(); if (CbLoaiTimKiem1.SelectedItem.ToString() == "Loại") { dataGrid1.ItemsSource = db.HangHoa.Where(hh => hh.Loai.Contains(TbTimKiem1.Text)).ToList(); } else if (CbLoaiTimKiem1.SelectedItem.ToString() == "Tên") { dataGrid1.ItemsSource = db.HangHoa.Where(hh => hh.Ten.Contains(TbTimKiem1.Text)).ToList(); } else if (CbLoaiTimKiem1.SelectedItem.ToString() == "Số lượng") { dataGrid1.ItemsSource = db.HangHoa. Where(hh => hh.SoLuong.ToString().Contains(TbTimKiem1.Text)).ToList(); } else if (CbLoaiTimKiem1.SelectedItem.ToString() == "Giá bán lẻ") { dataGrid1.ItemsSource = db.HangHoa. Where(hh => hh.GiaBanLe.ToString().Contains(TbTimKiem1.Text)).ToList(); } else { dataGrid1.ItemsSource = db.HangHoa.SqlQuery("SELECT * FROM HangHoa").ToList(); } } private void BtnLamMoi_Click(object sender, RoutedEventArgs e) { MessageBoxResult MBRs = MessageBox.Show("Bạn có muốn tạo đơn hàng mới", "Xác nhận", MessageBoxButton.YesNo, MessageBoxImage.Question); if (MBRs == MessageBoxResult.Yes) { ShowTabGiaoDich(); var db = new QuanLyCuaHangEntities(); dataGrid1.ItemsSource = db.HangHoa.ToList(); dataGrid2.ItemsSource = null; TbSoHoaDon.Text = ""; DPNgayGiaoDich.Text = ""; TbKhachHang.Text = ""; TbDiaChi.Text = ""; TbSdt.Text = ""; TblTongTien.Text = ""; TbGiam.Text = ""; TblTongCong.Text = ""; TbTienKhachDua.Text = ""; TblTienTraLai.Text = ""; TbSoLuongTab2.Text = ""; TbGiamGiaTab2.Text = ""; TblDaGiaoHang.Background = Brushes.Red; TongTien = 0; STT = 0; int n = datas.Count(); for (int i = n - 1; i >= 0; i--) { datas.Remove(datas[i]); } } else { return; } } class Data { public int id { get; set; } public int stt { get; set; } public String ten { get; set; } public int soLuong { get; set; } public int donGia { get; set; } public int giam { get; set; } public int thanhTien { get; set; } } int TongTien = 0; int STT = 0; List<Data> datas = new List<Data>(); /// <summary> /// Chọn 1 hàng hóa trong kho vào danh sách hàng hóa mà khách hàng định mua /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnChon_Click(object sender, RoutedEventArgs e) { var db = new QuanLyCuaHangEntities(); HangHoa hh = dataGrid1.SelectedItem as HangHoa;//chọn 1 dòng từ DataGrid2 if(hh!=null) { if (hh.SoLuong <= 0) { MessageBox.Show("Đã hết hàng!!!"); } else { STT++; int SOLUONG = 1; int THANHTIEN = int.Parse(hh.GiaBanLe.ToString()) * SOLUONG; datas.Add(new Data() { id = hh.Id, stt = STT, ten = hh.Ten, soLuong = SOLUONG, donGia = int.Parse(hh.GiaBanLe.ToString()), giam = 0, thanhTien = THANHTIEN }); TongTien += THANHTIEN; TblTongTien.Text = TongTien.ToString(); dataGrid2.ItemsSource = null; dataGrid2.ItemsSource = datas; } } } /// <summary> /// Bỏ chọn 1 hàng hóa trong danh sách hàng hóa khách hàng định mua /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnBoChon_Click(object sender, RoutedEventArgs e) { var hh = dataGrid2.SelectedItem as Data; int soThuTu = hh.stt; for(int i = soThuTu - 1; i < datas.Count()-1; i++) { datas[i].ten = datas[i+1].ten; datas[i].soLuong = datas[i+1].soLuong; datas[i].donGia = datas[i+1].donGia; datas[i].giam = datas[i+1].giam; datas[i].thanhTien = datas[i+1].thanhTien; } datas.Remove(datas[datas.Count() - 1]); STT = datas.Count(); dataGrid2.ItemsSource = null; dataGrid2.ItemsSource = datas; } /// <summary> /// Chọn 1 dòng trong dataGrid2 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dataGrid2_SelectionChanged(object sender, SelectionChangedEventArgs e) { var dt = dataGrid2.SelectedItem as Data; if (dt != null) { TbSoLuongTab2.Text = dt.soLuong.ToString(); TbGiamGiaTab2.Text = dt.giam.ToString(); } } /// <summary> /// Hàm dùng để xác nhận chọn số lượng và phần trăm giảm giá cho 1 hàng hóa /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnXacNhan_Click(object sender, RoutedEventArgs e) { var dt = dataGrid2.SelectedItem as Data; if (dt != null) { int ma = dt.stt - 1; var db = new QuanLyCuaHangEntities(); var hh1 = db.HangHoa.Find(datas[ma].id); int soLuong = int.Parse(TbSoLuongTab2.Text); if (hh1.SoLuong > 0) { if (soLuong <= hh1.SoLuong && soLuong > 0) { int giam = int.Parse(TbGiamGiaTab2.Text); datas[ma].soLuong = soLuong; datas[ma].giam = giam; datas[ma].thanhTien = (datas[ma].donGia * (100 - giam) / 100) * soLuong; dataGrid2.ItemsSource = null; dataGrid2.ItemsSource = datas; int tongtien = 0; for (int i = 0; i < datas.Count(); i++) { tongtien += datas[i].thanhTien; } TblTongTien.Text = tongtien.ToString(); } else { MessageBox.Show("Số lượng hàng hóa trong kho không đủ!!! Vui lòng chọn lại số lượng!!!"); } } else { MessageBox.Show("Đã hết hàng"); } } } /// <summary> /// Hàm dùng để tính tổng cộng tiền mà khách hàng phải trả sau khi đã có giảm giá /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnTinhTien1_Click(object sender, RoutedEventArgs e) { try { int tongCong = int.Parse(TblTongTien.Text); int giam = int.Parse(TbGiam.Text); if (giam >= 0 && giam <= 100) { tongCong -= tongCong * giam / 100; TblTongCong.Text = tongCong.ToString(); } else { MessageBox.Show("Vui lòng điền lại thông tin!!!"); } } catch { MessageBox.Show("Vui lòng điền lại thông tin!!!"); } } /// <summary> /// Hàm dùng để tính số tiền phải trả lại cho khách hàng /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnTinhTien2_Click(object sender, RoutedEventArgs e) { try { int tongCong = int.Parse(TblTongCong.Text); int traLai = int.Parse(TbTienKhachDua.Text) - tongCong; TblTongCong.Text = tongCong.ToString(); TblTienTraLai.Text = traLai.ToString(); } catch { MessageBox.Show("Vui lòng điền lại thông tin!!!"); } } /// <summary> /// Hàm xử lý khi click vào button "Giao hàng-thanh toán" /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnThanhToan_Click(object sender, RoutedEventArgs e) { if (datas.Count <= 0) { MessageBox.Show("Vui lòng chọn các hàng hóa muốn bán!!!"); } else { if (DPNgayGiaoDich.Text == "") { MessageBox.Show("Vui lòng chọn ngày giao dịch!!!"); } else { int check = 0; var db = new QuanLyCuaHangEntities(); for (int i = 0; i < datas.Count(); i++) { try { var gd = new GiaoDich(); int shd = 0; if (db.GiaoDich.Count() != 0) { shd = db.Database.SqlQuery<int>("SELECT MAX(SoHoaDon) FROM GiaoDich").FirstOrDefault<int>() + 1; } gd.SoHoaDon = shd; gd.NgayGiaoDich = DPNgayGiaoDich.SelectedDate; gd.TenKhachHang = TbKhachHang.Text; gd.DiaChi = TbDiaChi.Text; gd.Sdt = TbSdt.Text; gd.MaHangHoa = datas[i].id; gd.SoLuong = datas[i].soLuong; gd.DonGia = datas[i].donGia; gd.Giam = datas[i].giam; gd.ThanhTien = datas[i].thanhTien; gd.TenHangHoa = datas[i].ten; db.GiaoDich.Add(gd); //Thay đổi số lượng hàng hóa trong kho var hh = db.HangHoa.Find(datas[i].id); hh.SoLuong -= datas[i].soLuong; check++; } catch { return; } } if (check == datas.Count()) { db.SaveChanges(); dataGrid1.ItemsSource = db.HangHoa.ToList(); MessageBox.Show("Thanh toán thành công"); TblDaGiaoHang.Background = Brushes.Green; } } } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// CÁC HÀM XỬ LÝ CHO TAB "THỐNG KÊ" private void TabThongKe_Loaded(object sender, RoutedEventArgs e) { string[] ListSapXep = { "Sắp xếp theo", "Ngày giảm dần", "Ngày tăng dần" }; CbSapXepTab3.ItemsSource = ListSapXep.ToList(); CbSapXepTab3.SelectedIndex = 0; } private void TabThongKe_PreviewMouseDown(object sender, MouseButtonEventArgs e) { if (loadTabThongKe == false) { TabThongKe.IsSelected = true; loadTabHangHoa = false; loadTabGiaoDich = false; loadTabThongKe = true; dataGrid3.ItemsSource = null; dataGrid4.ItemsSource = null; TblKhoangThoiGian.Text = ""; DPNgayBatDau.Text = ""; DPNgayKetThuc.Text = ""; CbSapXepTab3.SelectedItem = 0; } } private void CbSapXepTab3_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (dataGrid3.ItemsSource != null) { var db = new QuanLyCuaHangEntities(); if (CbSapXepTab3.SelectedItem.ToString() == "Ngày giảm dần") { dataGrid3.ItemsSource = db.GiaoDich. Where(hh => hh.NgayGiaoDich >= DPNgayBatDau.SelectedDate && hh.NgayGiaoDich <= DPNgayKetThuc.SelectedDate). OrderByDescending(hh=>hh.NgayGiaoDich).ToList(); } else if (CbSapXepTab3.SelectedItem.ToString() == "Ngày tăng dần") { dataGrid3.ItemsSource = db.GiaoDich. Where(hh => hh.NgayGiaoDich >= DPNgayBatDau.SelectedDate && hh.NgayGiaoDich <= DPNgayKetThuc.SelectedDate). OrderBy(hh=>hh.NgayGiaoDich).ToList(); } else { dataGrid3.ItemsSource = db.GiaoDich. Where(hh => hh.NgayGiaoDich >= DPNgayBatDau.SelectedDate && hh.NgayGiaoDich <= DPNgayKetThuc.SelectedDate).ToList(); } } } /// <summary> /// Hàm dùng để xuất báo cáo khi click vào button "Xuất báo cáo" /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnXuatBaoCao_Click(object sender, RoutedEventArgs e) { if (DPNgayBatDau.Text == "" || DPNgayKetThuc.Text == "") { MessageBox.Show("Vui lòng chọn khoảng thời gian (từ ngày ... đến ngày ...)"); } else { if(DPNgayKetThuc.SelectedDate<DPNgayBatDau.SelectedDate) { MessageBox.Show("Vui lòng chọn lại khoảng thời gian!"); } else { string ThongBao = "(Từ " + DPNgayBatDau.Text + " Đến " + DPNgayKetThuc.Text + ")"; TblKhoangThoiGian.Text = ThongBao; var db = new QuanLyCuaHangEntities(); dataGrid3.ItemsSource = db.GiaoDich. Where(hh => hh.NgayGiaoDich >= DPNgayBatDau.SelectedDate && hh.NgayGiaoDich <= DPNgayKetThuc.SelectedDate).ToList(); var TongDoanhThu = db.GiaoDich.Where(hh => hh.NgayGiaoDich >= DPNgayBatDau.SelectedDate && hh.NgayGiaoDich <= DPNgayKetThuc.SelectedDate).Sum(hh => hh.ThanhTien); TblTongDoanhThu.Text = TongDoanhThu.ToString(); var TongHangHoa=db.GiaoDich.Where(hh => hh.NgayGiaoDich >= DPNgayBatDau.SelectedDate && hh.NgayGiaoDich <= DPNgayKetThuc.SelectedDate).Sum(hh => hh.SoLuong); TblTongSoHangHoa.Text = TongHangHoa.ToString(); dataGrid4.ItemsSource = db.Procedure_Lay10HangHoaBanChay(DPNgayBatDau.SelectedDate, DPNgayKetThuc.SelectedDate); } } } /// <summary> /// Hàm dùng để xuất bảng báo cáo ra excel /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnXuatExcel_Click(object sender, RoutedEventArgs e) { if (dataGrid3.ItemsSource == null) { MessageBox.Show("Chưa có dữ liệu để xuất!!!"); } else { //Đoạn code xuất ra Excel tham khảo từ: //http://www.yazilimkodlama.com/programlama/wpf-datagrid-icindeki-verileri-excele-aktarma/ //Tạo 1 bảng excel Excel.Application excel = new Excel.Application(); excel.Visible = true; Workbook workbook = excel.Workbooks.Add(System.Reflection.Missing.Value); Worksheet sheet1 = (Worksheet)workbook.Sheets[1]; //Ghi vào tên các cột for (int j = 0; j < dataGrid3.Columns.Count; j++) { Range myRange = (Range)sheet1.Cells[1, j + 1]; sheet1.Cells[1, j + 1].Font.Bold = true; sheet1.Columns[j + 1].ColumnWidth = 15; myRange.Value2 = dataGrid3.Columns[j].Header; } //Ghi dữ liệu vào từng cột for (int i = 0; i < dataGrid3.Columns.Count; i++) { for (int j = 0; j < dataGrid3.Items.Count; j++) { var b = dataGrid3.Columns[i].GetCellContent(dataGrid3.Items[j]) as TextBlock; Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[j + 2, i + 1]; if (b != null) { myRange.Value2 = b.Text; } } } MessageBox.Show("Xuất dữ liệu ra Excel thành công"); } } } } <file_sep>namespace UngDungQuanLy { internal class ImageProduct { } }<file_sep># Project: Ứng dụng quản lý bán hàng linh kiện máy tính ### Mô tả project 1. Ứng dụng bán linh kiện máy tính đơn giản, cho phép xem thông tin hàng hoá, tạo đơn hàng 2. Phiên bản visual studio: Visual studio 2017 3. Ngôn ngữ: C# ### Link video demo: https://www.youtube.com/watch?v=EzmdBKZQwzc&t=53s
ddc0c011639ed4701ed31ec621dda2a517c64187
[ "Markdown", "C#" ]
3
C#
duclm98/Windows-Programming--Store-Management-C-sharp
f30b5a26383682d0411328191ce96b16ce16bf3d
c97f510a8db99d24d15c42e02be55bf6cda7d11d
refs/heads/master
<repo_name>Sasmithav/hackerrank<file_sep>/algorithms/implementation/Bon Appetit.java import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String args[] ) throws Exception { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ //MY SOLUTION Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int k=sc.nextInt(); int i,sum=0,sum1=0; int a[]=new int[n]; for( i=0;i<n;i++){ a[i]=sc.nextInt(); } int b=sc.nextInt(); ArrayList<Integer> arr=new ArrayList<>(); for( i=0;i<n;i++){ arr.add(a[i]); } arr.remove(k); for(i=0;i<arr.size();i++) { sum=sum+arr.get(i); } // System.out.println(sum); int tot=sum/2; if(tot==b) System.out.println("Bon Appetit"); else { int tot1=b-tot; System.out.println(tot1); } //SIMPLE SOLUTION Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int k = scanner.nextInt(); int total = 0; for (int i = 0; i < n; i++) { int price = scanner.nextInt(); if (i != k) total += price; } int charged = scanner.nextInt(); System.out.println(total / 2 == charged ? "Bon Appetit" : charged - (total/2)); } } } } <file_sep>/algorithms/strings/HackerRank in a String.java import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { // Complete the hackerrankInString function below. static String hackerrankInString(String s) { //MY SOLUTION String s1="hackerrank"; // ArrayList<Integer> arr=new ArrayList<>(); int h=0,count=0,i,j; for(i=0;i<s1.length();i++){ for(j=h;j<s.length();j++){ if(s1.charAt(i)==s.charAt(j)){ h=j+1; count++; // arr.add(j); break; } } } if(count==s1.length()) { /* for(i=0;i<arr.size()-1;i++){ if(arr.get(i)>arr.get(i+1)) return "NO"; else System.out.println("yes"); }*/ return "YES"; } else return "NO"; //SIMPLE SOLUTION String str = "hackerrank"; if (s.length() < str.length()) { return "NO"; } int j = 0; for (int i = 0; i < s.length(); i++) { if (j < str.length() && s.charAt(i) == str.charAt(j)) { j++; } } return (j == str.length() ? "YES" : "NO"); } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int q = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int qItr = 0; qItr < q; qItr++) { String s = scanner.nextLine(); String result = hackerrankInString(s); bufferedWriter.write(result); bufferedWriter.newLine(); } bufferedWriter.close(); scanner.close(); } }
25b12d03f3974c59bf9fbe52e42763aaf9e9d055
[ "Java" ]
2
Java
Sasmithav/hackerrank
00275c99f44d04341ebb69052779b093f99e392d
c03d227928e095c3045a8a4c2ea1001f15f8b6b3
refs/heads/main
<repo_name>juliano-echo21/first_server<file_sep>/README.md # firts_server my very first server using node.js and basic concepts from express <file_sep>/response.js exports.success = (req,res,message,status)=>{ res.status(status) .send({ error : "", body : message }); }; exports.error = (req,res,message,status)=>{ res.status(status) .send({ error : message, body : "" }); };<file_sep>/components/message/network.js const express = require('express'); const response = require('../../response'); const controller = require('./controller') const router = express.Router() //another change router .get('/',(req,res)=>{ controller.getMessage(req.query.user) .then( (data)=>{ response.success(req,res,data,200); }) .catch( (err) => { response.error(req,res,err,500); }); }) .post('/',(req,res)=>{ controller.addMessage(req.body.user,req.body.message) .then( (data)=>{ response.success(req,res,data,200); }) .catch( (err) => { response.error(req,res,err,500); }); // res.end() }) .patch('/',(req,res)=>{ controller.updateMessage(req.body.id,req.body.message) .then( (data)=>{ response.success(req,res,data,200) }) .catch( (error)=>{ response.error(req,res,error,500); }) }) .delete('/',(req,res)=>{ controller.deleteMessage(req.body.id) .then( (data)=>{ response.success(req,res,`el mensaje de ${data} ha sido eliminado`,200); }) .catch( (error)=>{ response.error(req,res,error,500); }) }) module.exports = router;
27b80909140150c620a44b6e705755c22edba6f4
[ "Markdown", "JavaScript" ]
3
Markdown
juliano-echo21/first_server
047a0e0c89b523fa153cf533e46b222a603f1f52
135f096e56ed7f6f52adf4bd6f43812387ea2777
refs/heads/master
<repo_name>ty536804/laravel_admin<file_sep>/app/Models/Base/BaseSysAreacode.php <?php namespace App\Models\Base; use Illuminate\Database\Eloquent\Model; class BaseSysAreacode extends Model { protected $table='sys_areacode'; protected $primaryKey='id'; public $timestamps = true; protected $fillable=[ 'aid', // 区域编号 'a_level', // 节点等级 1 省 2市 3区 'gaode_id', // 高德ID 'aname', // 区域名称 'parent_id', // 父节点 'a_status', // 1 有效 0 无效 'root_id', // 根节点ID 'is_show', // 1 前端显示 0 不显示 ]; }//Created at 2020-03-24 06:11:02<file_sep>/app/Http/Controllers/Backend/ArticleController.php <?php namespace App\Http\Controllers\Backend; use App\Http\Controllers\Controller; use App\Http\Requests\Backend\ArticleRequest; use App\Models\Backend\Article; use App\Services\ArticleServices; use App\Tools\ApiResult; use App\Tools\Constant; use Illuminate\Support\Facades\Input; use Yajra\DataTables\Facades\DataTables; class ArticleController extends Controller { // use ApiResult; protected $article; public function __construct(ArticleServices $article) { $this->article = $article; } /** * @description 文章首页 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther caoxiaobin * date: 2020-03-26 */ public function show() { return view("article.index"); } /** * @description 文章列表 * @return \Illuminate\Http\JsonResponse * @throws \Exception * @auther caoxiaobin */ public function articleList() { $list = Article::where('id','>',0); $database = DataTables::eloquent($list); return $database->make(true); } /** * @description 添加/编辑 文章 * @param ArticleRequest $request * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function articleSave(ArticleRequest $request) { if ($request->ajax()) { return $this->article->articleSave($request->all()); } return $this->error("操作失败"); } /** * @description 添加文章详情页面 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther caoxiaobin */ public function articleDetail() { $result = $this->article->articleDetail(Input::get("id")); if ($result->code == Constant::ERROR) { return back()->withErrors("内容不存在"); } return view("article.detail", $result->data); } /** * @description 首页 * @auther caoxiaobin */ public function articleShow() { return view("article.show"); } /** * @description 首页 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther caoxiaobin */ public function articleAdd() { return view("article.show"); } } <file_sep>/database/migrations/article/2020_03_30_094318_create_essay_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateEssayTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('essay', function (Blueprint $table) { $table->id(); $table->integer("banner_position_id")->comment("位置"); $table->string("essay_title")->comment("标题"); $table->text("essay_content")->nullable(true)->comment("内容"); $table->text("essay_img")->nullable(true)->comment("缩率图"); $table->integer("essay_status")->default(1)->comment("状态 1显示 0隐藏"); $table->text("essay_img_info")->nullable(true)->comment("缩率图信息"); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('essay'); } } <file_sep>/app/Services/validations.php <?php \Validator::extend('flow_money', function ($attribute, $value, $parameters) { if (is_numeric($value)) { if ($value <= 0) { return false; } if ($value % 100 == 0) { return true; } } return false; }); Validator::extend('select', function ($attribute, $value, $parameters) { if($value==""){ return false; }elseif (is_numeric($value)) { if ($value > 0) { return true; } }elseif($value!=""){ return true; } return false; }); Validator::extend('password_geshi', function ($attribute, $value, $parameters) { $pattern = '/^(?=.*[0-9])(?=.*[a-zA-Z])/'; if (preg_match($pattern, $value)) { return true; } return false; }); Validator::extend('phone', function ($attribute, $value, $parameters) { $pattern = '/^(0\d{2,3}-\d{7,8})$/'; if (preg_match($pattern, $value)) { return true; } return false; }); //最多2位小数 Validator::extend('money', function ($attribute, $value, $parameters) { $pattern = '/^\d+(\.\d{1,2})?$/'; if (preg_match($pattern, $value)) { return true; } return false; }); Validator::extend('number', function ($attribute, $value, $parameters) { $pattern = '/^[0-9]*$/'; if (preg_match($pattern, $value)) { return true; } return false; }); //登陆账号格式 字母 数字 下划线 减号 4-16位 Validator::extend('loginname', function ($attribute, $value, $parameters) { $pattern = '/^[a-zA-Z0-9_-]{4,16}$/'; if (preg_match($pattern, $value)) { return true; } return false; }); //短信验证码格式 4位数字 Validator::extend('sms_number', function ($attribute, $value, $parameters) { if (is_numeric($value)) { if ($value <= 0) { return false; } if ($value % 5000 == 0) { return true; } } return false; }); //中国手机格式 Validator::extend('zh_mobile', function ($attribute, $value, $parameters) { return preg_match('/^(\+?0?86\-?)?((13\d|14[57]|15[^4,\D]|17[678]|18\d)\d{8}|170[059]\d{7})$/', $value); }); //邮箱验证 Validator::extend('email', function ($attribute, $value, $parameters) { $preg_email='/^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@([a-zA-Z0-9]+[-.])+([a-z]{2,5})$/ims'; return preg_match($preg_email,$value); });<file_sep>/app/Services/UserServices.php <?php namespace App\Services; use App\Models\Admin\SysAdminUser; use App\Tools\ApiResult; use App\Tools\Result; class UserServices { use ApiResult; private $result; public function __construct() { $this->result = new Result(); } /** * @description 修改用户信息 * @param $data * @return Result * @auther caoxiaobin */ public function updateInfo($data) { $login_name = $data['login_name'] ?? ''; $email = $data['email'] ?? ''; $tel = $data['tel'] ?? ''; $id = $data['id'] ?? 0; if ($id <1) { return $this->error("非法请求"); } if (empty(trim($login_name))) { return $this->error("用户名不能为空"); } if (empty(trim($email))) { return $this->error("邮箱不能为空"); } if (empty($tel) || !$this->checkMobile($tel)) { return $this->error("手机号格式不正确"); } $adminUser = $this->getUserInfo($id); if (!$adminUser) { return $this->error("用户不存在"); } $adminUser->fill($data); if ($adminUser->save()) { $AdminUser = new AdminUser(); $AdminUser->setUser($adminUser); return $this->success("修改成功"); } else { return $this->error("修改失败"); } } /** * @description 修改密码 * @param $data * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin * date: 2020-03-24 */ public function editPwd($data) { $id = $data['id'] ?? 0; $oldPWD = $data['pwd'] ?? ''; $newPWD = $data['newpwd'] ?? ''; if (empty(trim($oldPWD))) { return $this->error("旧密码不允许为空"); } if (empty($newPWD) || strlen(trim($newPWD)) <6) { return $this->error("新密码不允许为空,且不允许小于6"); } $userInfo = $this->getUserInfo($id); if (!$userInfo) { return $this->error("用户不存在"); } if ($userInfo->pwd != md5(trim($oldPWD))) { return $this->error("原始密码密码不正确"); } $data['pwd'] = md5(trim($oldPWD)); $userInfo->fill($data); if ($userInfo->save()) { $AdminUser = new AdminUser(); $AdminUser->forget(); return $this->success("修改成功"); } else { return $this->error("修改失败"); } } /** * @description 获取用户信息 * @param $id * @return mixed * @auther caoxiaobin * date: 2020-03-24 */ public function getUserInfo($id) { return SysAdminUser::find($id); } }<file_sep>/database/migrations/article/2020_03_26_081334_create_article_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateArticleTable extends Migration { /** * Run the migrations. * 文章 * @return void */ public function up() { Schema::create('article', function (Blueprint $table) { $table->id(); $table->string("title")->default("")->comment("标题"); $table->string("summary",255)->default("")->comment("摘要"); $table->string("thumb_img")->default("")->comment("缩率图"); $table->string("admin")->default("admin")->comment("编辑者"); $table->string("com")->default("")->comment("来源"); $table->string("is_show")->default("1")->comment("是否展示 1展示 2不展示"); $table->text("content")->comment("内容"); $table->integer("hot")->default(2)->comment("是否热点 1是 2否"); $table->integer("sort")->default(0)->comment("优先级 数字越大,排名越前"); $table->text("thumb_img_info")->comment("缩率图相关信息"); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('article'); } } <file_sep>/app/Http/Controllers/admin/SiteController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\SiteRequest; use App\Services\SiteServices; use App\Tools\ApiResult; class SiteController extends Controller { // use ApiResult; protected $site; public function __construct(SiteServices $site) { $this->site = $site; } /** * @description 站点信息 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther caoxiaobin */ public function show() { $site = $this->site->siteInfo(); return view("admin.site", ['info' => $site]); } /** * @description 添加信息 * @param SiteRequest $request * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function siteSave(SiteRequest $request) { if ($request->ajax()) { return $this->site->siteSave($request->all()); } return $this->error("操作失败"); } } <file_sep>/app/Models/Backend/Base/BaseMessage.php <?php namespace App\Models\Backend\Base; use Illuminate\Database\Eloquent\Model; class BaseMessage extends Model { protected $table='message'; protected $primaryKey='id'; public $timestamps = true; protected $fillable=[ 'mname', // 姓名 'area', // 地区 'tel', // 电话 'content', // 留言内容 'com', // 留言来源页 'client', // 客户端 'ip', // ip地址 'channel', // 留言板块 'created_at', // 'updated_at', // ]; }//Created at 2020-03-27 02:39:13<file_sep>/routes/majic.php <?php use Illuminate\Support\Facades\Route; Route::group(["namespace"=>"Backend","prefix"=>"backend"],function () { Route::group(["prefix" => "banner"], function () { Route::get("show","BannerController@index");//banner列表页面 Route::post("list","BannerController@bannerList");//banner请求ajax Route::post("del","BannerController@bannerDel");//banner删除 Route::post("save","BannerController@bannerSave");//banner保存 Route::get("detail","BannerController@bannerDetail");//banner详情页 }); Route::group(["prefix" => "position"], function() { Route::get("positionList","BannerController@positionList");//轮播图展示位置 Route::post("positionData","BannerController@positionData");//轮播图展示位置ajax Route::post("positionDel","BannerController@positionDel");//删除轮播图展示位置 Route::post("positionEdit","BannerController@positionEdit");//轮播图位置展示编辑 Route::post("positionSave","BannerController@positionSave");//轮播图位置展示保存 }); Route::group(["prefix" => "message"], function () { Route::get("show","MessageController@show");//留言列表页面 Route::get("detail","MessageController@messageDetail");//留言列表页面 Route::post("list","MessageController@messageList");//留言列表ajax Route::post("save","MessageController@messageSave");//提交留言 }); Route::group(["prefix" => "article"], function (){ Route::get("show","ArticleController@show");//文章列表页面 Route::get("detail","ArticleController@articleDetail");//文章页面 Route::post("list","ArticleController@articleList");//文章列表ajax Route::post("save","ArticleController@articleSave");//提交文章 }); Route::group(["prefix" => "essay"], function (){ Route::get("show","EssayController@index");//文章列表页面 Route::get("detail","EssayController@essayDetail");//文章页面 Route::post("save","EssayController@essayAdd");//文章列表ajax Route::post("list","EssayController@easyList");//文章列表ajax Route::get("del","EssayController@essayDel");//删除 Route::get("magic","EssayController@aboutMagic");//文章列表页面 }); });<file_sep>/app/Models/Admin/SysAdminDepartment.php <?php namespace App\Models\Admin; use App\Models\Base\BaseSysAdminDepartment; class SysAdminDepartment extends BaseSysAdminDepartment { /** * @description 部门 一对多 * @return \Illuminate\Database\Eloquent\Relations\HasMany * @auther xiaobin */ public function child(){ return $this->hasMany(SysAdminDepartment::class,'parent_id','id'); } public function children() { return $this->child()->with('children'); } }<file_sep>/app/Models/Admin/SysAdminUser.php <?php namespace App\Models\Admin; use App\Models\Base\BaseSysAdminDepartment; use App\Models\Base\BaseSysAdminPosition; use App\Models\Base\BaseSysAdminUser; class SysAdminUser extends BaseSysAdminUser { /** * @description 获取职位 * @return \Illuminate\Database\Eloquent\Relations\HasOne * @auther xiaobin */ public function position() { return $this->hasOne(BaseSysAdminPosition::class,'id','position_id'); } /** * @description 获取部门 * @return \Illuminate\Database\Eloquent\Relations\HasOne * @auther xiaobin */ public function department() { return $this->hasOne(BaseSysAdminDepartment::class,'id','department_id'); } }//Created at 2020-03-23 03:21:23<file_sep>/app/Providers/AppServiceProvider.php <?php namespace App\Providers; use App\Helpers\Logs; use Carbon\Carbon; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Schema; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Str; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { Schema::defaultStringLength(190); Carbon::setLocale('zh'); require app_path().'/Services/validations.php'; $sql_debug = config('database.sql_debug'); if ($sql_debug) { DB::listen(function ($sql) { if(!Str::startsWith($sql->sql,'explain')){ foreach ($sql->bindings as $i => $binding) { if ($binding instanceof \DateTime) { $sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\''); } else { if (is_string($binding)) { $sql->bindings[$i] = "'$binding'"; } } } $query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql); $query = vsprintf($query, $sql->bindings); $query_key = md5($query); $execute_id = md5($query.time().rand(10000,99999)); $sql_key = md5($sql->sql); Log::debug('运行SQL:' . $query); Log::debug('运行耗时:' . $sql->time . ' ms'); Cache::put($execute_id, $sql->time . "ms", 1); if(Str::startsWith($query,"select")){ try{ $result= DB::select("explain ".$query); foreach ($result as $v){ $v->sql_key = $sql_key; $v->query_key = $query_key; $v->query_sql = $query; $v->query_time= Cache::get($execute_id, '0'); $v->execute_id = $execute_id; $v->application = config('app.name'); $v->msg = "Explain execute successful"; // Log::debug(json_encode($v),['type'=>'SqlExpain'],'sql_explain'); } }catch (\Exception $e){ $v = new \stdClass(); $v->sql_key = $sql_key; $v->query_key = $query_key; $v->query_sql = $query; $v->query_time= Cache::get($execute_id, '0'); $v->executeid = $execute_id; $v->application = config('app.name'); $v->msg = "Explain execute error : ".$e->getMessage(); // Log::debug(json_encode($v),['type'=>'SqlExpain'],'sql_explain'); } } } }); } } /** * Register any application services. * * @return void */ public function register() { // } } <file_sep>/database/migrations/admin/2020_03_23_032313_sys_admin_login_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class SysAdminLoginTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Schema::create('sys_admin_login_log', function (Blueprint $table) { $table->increments('id'); $table->integer('admin_id')->comment('管理员id'); $table->string('login_name',50)->comment('管理员名称'); $table->string('login_role',50)->nullable()->comment('管理员角色'); $table->string('client_ip',50)->nullable()->comment('ip'); $table->string('browser_info',50)->nullable()->comment('登陆浏览器及版本'); $table->string('os_info',50)->nullable()->comment('操作系统信息'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { // Schema::dropIfExists('sys_admin_login_log'); } } <file_sep>/app/Models/Admin/SysAreacode.php <?php namespace App\Models\Admin; use App\Models\Base\BaseSysAreacode; class SysAreacode extends BaseSysAreacode { /** * @description 获取省 * @return mixed * @auther xiaobin */ public function province() { return SysAreacode::select('id','aname')->where("parent_id", '-1')->get(); } }//Created at 2020-03-24 05:48:35<file_sep>/app/Http/Controllers/FileInputUploadController.php <?php namespace App\Http\Controllers; use App\Models\Base\BaseSysMedia; use App\Tools\Result; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\URL; use Intervention\Image\Facades\Image; class FileInputUploadController extends Controller { // private $IMG_TYPE=array(); private $FILE_TYPE=array(); function __construct() { $this->IMG_TYPE = array('jpg','JPG','png','PNG','jpeg','JPEG'); $this->FILE_TYPE = array('xls', 'xlsx','doc','docx','pdf'); } public function download($id){ $file = BaseSysMedia::find($id); if(!empty($file)){ return response()->download(realpath(base_path('public/storage/uploadfile/'))."/".$file->m_url,$file->m_name); }else{ return "下载错误"; } } public function delete(){ $media = BaseSysMedia::find(Input::get("key")); if(!empty($media)){ $media->m_status = -1; $media->save(); } $result = new \stdClass(); $result->code="OK"; return response()->json($result); } /** * http://image.intervention.io/ * @return string * @description */ public function anyUpload() { //如果一个页面有多个文件上传的时候 需要上传文件按钮Id if(Input::has('filename') && Input::get('filename') != ""){ if(isset($_FILES[Input::get('filename')])){ $fileinfo = $_FILES[Input::get('filename')]; }else{ $info = array('code'=>0,'error'=>'发生错误 filename'); return json_encode($info); } }else{ ///默认上传文件按钮ID是 fileupload if(isset($_FILES["fileupload"])){ $fileinfo =$_FILES['fileupload']; }else{ $info = array('code'=>0,'error'=>'发生错误 fileupload'); return json_encode($info); } } $type = Input::get('pictype',0); try{ if(! is_null($type) && $type >0){ if($fileinfo['error']==0){ $media = new BaseSysMedia(); $filename = explode('.',$fileinfo['name']); $extname = strtolower(end($filename)); $path = "/".$type."/".date('Ymd')."/"; if(!file_exists(config('www.uploadfile').$path)){ Log::error(config('www.uploadfile')."$path"); mkdir(config('www.uploadfile').$path,0775,true); } $file_save_path =config('www.uploadfile').$path; $height=0; $width=0; $timerand = time().rand(1000,9999); //如果是图片文件格式 进行缩略处理 if(in_array($extname,$this->IMG_TYPE)){ $img = Image::make($fileinfo['tmp_name']); $height = $img->height(); $width = $img->width(); $newfilename =$timerand."_".$width."X".$height.".".$extname; //方形图 $alias="_square"; $aliasfilename =$timerand."_".$width."X".$height.$alias.".".$extname; if($width>$height){ $x = round(($width - $height) / 2); $img->crop($height,$height,$x,0); if($height>300){ $img->resize(300,300); } $img->save($file_save_path.$aliasfilename); $img->destroy(); }elseif($width<$height){ $y = round(($height - $width) / 2); $img->crop($width,$width,0,$y); if($width>300){ $img->resize(300,300); } $img->save($file_save_path.$aliasfilename); $img->destroy(); }elseif($width==$height){ if($width>300){ $img->resize(300,300); $img->save($file_save_path.$aliasfilename); $img->destroy(); } } //缩略图 if($height > $width && $height>400){ $img = Image::make($fileinfo['tmp_name']); $img->resize(null,400,function ($constraint) {$constraint->aspectRatio();}); $alias="_thumbnail"; $aliasfilename =$timerand."_".$width."X".$height.$alias.".".$extname; $img->save($file_save_path.$aliasfilename); $img->destroy(); }else if($height < $width && $width>400){ $img = Image::make($fileinfo['tmp_name']); $img->resize(400,null, function ($constraint) {$constraint->aspectRatio();}); $alias="_thumbnail"; $aliasfilename =$timerand."_".$width."X".$height.$alias.".".$extname; $img->save($file_save_path.$aliasfilename); $img->destroy(); }elseif($height == $width){ $img = Image::make($fileinfo['tmp_name']); $img->resize(400,400); $alias="_thumbnail"; $aliasfilename =$timerand."_".$width."X".$height.$alias.".".$extname; $img->save($file_save_path.$aliasfilename); $img->destroy(); } $fileinfo['width'] = $width; $fileinfo['height'] = $height; $media->m_width = $fileinfo['width']; $media->m_height = $fileinfo['height']; }else{ $newfilename =$timerand.".".$extname; $media->m_width =0; $media->m_height =0; } move_uploaded_file($fileinfo['tmp_name'],$file_save_path.$newfilename); unset($fileinfo['tmp_name']); unset($fileinfo['error']); $media->uid = Input::has('uid')?Input::get('uid') : 0 ; $media->m_name = $fileinfo['name']; $media->m_url = $path.$newfilename; $media->m_type = $type; $media->m_format = $fileinfo['type']; $media->m_size = $fileinfo['size']; $media->m_metadata =json_encode($fileinfo); $media->save(); //初始化处理 if(in_array($extname,$this->IMG_TYPE)){ $initPreview=["<img src='".asset('storage/uploadfile/').$media->m_url."' style=\"width:auto;height:160px;\" class=\"file-preview-image\" alt=".$media->m_name." title=".$media->m_name.">"]; }else{ $initPreview=["<div class='file-preview-other'><span class='file-other-icon'><i class='glyphicon glyphicon-file'></i></span></div>"]; } $initialPreviewConfig=[ ["caption"=>$media->m_name, // "width"=>'120px', "url"=>URL::action('FileInputUploadController@delete'), "key"=>$media->id ] ]; unset($media->m_metadata); unset($media->updated_at); unset($media->created_at); Log::info(json_encode($media)); $info=array('code'=>1,'initialPreview'=>$initPreview,'initialPreviewConfig'=>$initialPreviewConfig,'msg'=>"上传成功",'data'=>$media); }else{ ///上传文件发生错误 $info = array('code'=>0,'error'=>'发生错误','info'=>$fileinfo);; } }else{ $info = array('code'=>0,'error'=>'文件分类错误'); } }catch (\Exception $e){ Log::error("文件上传发生系统错误=".$e->getMessage().$e->getFile().$e->getLine()); $info = array('code'=>0,'error'=>'文件上传发生错误'.$e->getMessage()); } return json_encode($info); } } <file_sep>/app/Console/Commands/InitDataCommand.php <?php namespace App\Console\Commands; use Illuminate\Console\Command; class InitDataCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'db:init {name}'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $tableName = $this->argument('name'); $func = "init".ucfirst($tableName)."Database"; call_user_func("App\Console\Commands\InitDataCommand::".$func); $this->info( $func ." Compelete!!"); } public function initAdminDatabase() { $this->call("db:seed",['--class' => \SysAdminPowerSeeder::class]); $this->call("db:seed",['--class' => \SysAdminUserSeeder::class]); $this->call("db:seed",['--class' => \SysAreacodeSeeder::class]); } } <file_sep>/app/Services/BannerServices.php <?php namespace App\Services; use App\Models\Admin\SysAreacode; use App\Models\Backend\Banner; use App\Models\Backend\BannerPosition; use App\Tools\ApiResult; use App\Tools\Constant; use App\Tools\Result; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; class BannerServices { use ApiResult; protected $result; protected $admin; public function __construct(AdminUser $admin) { $this->result = new Result(); $this->admin = $admin; } /** * @description 删除banner * @param $id bannerID * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function bannerDel($id) { if ($id < 1) { return $this->error("操作失败"); } $banner = $this->getOneBanner($id); if (!$banner) { return $this->error("操作失败"); } DB::table("banner")->where("id","=",$id)->delete(); Cache::forget("banner_list{$banner->bposition}"); return $this->success("操作成功"); } /** * @description 编辑banner * @param $data post提交的所有数据 * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function bannerSave($data) { $id = $data['id'] ?? 0; $bname = $data['bname'] ?? ""; if (empty($bname)) { return $this->error("名称不能为空"); } $bposition = $data['bposition'] ?? ""; if (empty($bposition)) { return $this->error("显示位置不能为空"); } $target_link = $data['target_link'] ?? ""; if (empty($target_link)) { return $this->error("链接不能为空"); } $imgurl = $data['img_info'] ?? ""; if (empty($imgurl)) { return $this->error("请上传banner图片"); } $picInfo = json_decode($imgurl,true); $picInfo = reset($picInfo); $data['imgurl'] = $picInfo['m_url']; if ($id < 1) { $banner = new Banner(); } else { $banner= $this->getOneBanner($id); } $banner->fill($data); if ($banner->save()) { Cache::forget("banner_list{$data['bposition']}"); return $this->success("操作成功"); } return $this->error("操作失败"); } /** * @description banner位置 * @param $data post提交的所有数据 * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function positionSave($data) { $position_name = $data['position_name'] ?? ""; if (empty($position_name)) { return $this->error("位置名称不能为空"); } $base_url = $data['base_url'] ?? ""; if (empty($base_url)) { return $this->error("基础地址不能为空"); } $id = $data['id'] ?? 0; if ($id < 1 ) { $bannerPosi = new BannerPosition(); } else { $bannerPosi = BannerPosition::find($id); if ($data['is_show'] ==2 && Banner::where("bposition", $id)->exists()) { return $this->error("轮播图取消展示之后放开,关闭"); } } $bannerPosi->fill($data); if ($bannerPosi->save()) { Cache::forget("menu"); return $this->success("操作成功"); } return $this->error("操作失败"); } /** * @description 详情 * @param $id bannerID * @return Result * @auther caoxiaobin */ public function bannerDetail($id) { if ($id < 1) { $banner = new Banner(); } else { $banner = $this->getOneBanner($id); if (!$banner) { $this->result->code = Constant::ERROR; $this->result->msg = "操作失败"; return $this->result; } } $admin_id = $this->admin->getId(); $areaCode = new SysAreacode(); $cities = $areaCode->province(); $position = $this->menu(); $data = [ 'admin_id' => $admin_id, 'info' => $banner, 'cities'=>$cities, 'position' => $position, ]; $this->result->code = Constant::OK; $this->result->msg = "操作成功"; $this->result->data = $data; return $this->result; } /** * @description 获取单个banner * @param $id bannerID * @return mixed * @auther caoxiaobin */ public function getOneBanner($id) { return Banner::find($id); } /** * @description 菜单 * @return mixed * @auther caoxiaobin */ public function menu() { return Cache::remember("menu",Constant::VALID_TIME, function (){ return BannerPosition::where("is_show", 1)->get(); }); } }<file_sep>/app/Services/AdminUser.php <?php namespace App\Services; use App\Models\Admin\SysAdminPower; use App\Tools\Constant; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Session; use Illuminate\Support\Str; class AdminUser { private $id = 0; public $user = ""; /** * @return \Illuminate\Session\SessionManager|\Illuminate\Session\Store|int|mixed */ public function getId() { $this->id = Session::get(Constant::ADMIN_SESSION_ID, '0'); return $this->id; } /** * @param \Illuminate\Session\SessionManager|\Illuminate\Session\Store|int|mixed $id */ public function setId($id): void { $this->id = $id; Session::put(Constant::ADMIN_SESSION_ID, $id); } /** * @return \Illuminate\Session\SessionManager|\Illuminate\Session\Store|mixed|string */ public function getUser() { $this->user = session(Constant::ADMIN_SESSION); return $this->user; } /** * @return \Illuminate\Session\SessionManager|\Illuminate\Session\Store|mixed|string * 获取当前用户的城市 id */ public function getUserCityIds() { $this->user = session(Constant::ADMIN_SESSION); return $this->user->city_id; } /** * @param \Illuminate\Session\SessionManager|\Illuminate\Session\Store|mixed|string $user */ public function setUser($user): void { Session::put(Constant::ADMIN_SESSION, $user); $this->user = $user; } public function forget() { Cache::forget('leftMenu_' . $this->getId()); session::forget(Constant::ADMIN_SESSION_ID); Session::forget(Constant::ADMIN_SESSION); } /** * @return mixed * @description 缓存用户的左侧菜单永久有效, 根据左侧菜单和点击的Action 更改菜单的选中状态 Active */ public function leftMenu() { $actions = explode('\\', \Route::current()->getActionName()); $action = end($actions); $leftMenuCache = Cache::remember('leftMenu_' . $this->getId(), 4800, function () { $leftMenuCache = null; $userInfo = $this->getUser(); if (is_null($userInfo)) { $leftMenuCache = null; } else { $allpower = SysAdminPower::select('id', 'pname', 'icon', 'purl', 'parent_id', 'pindex')->where('status', 1)->orderBy('pindex', 'asc')->get(); $leftMenuCache['allpower'] = $allpower; $mypower = $userInfo->position_power . $userInfo->department->powerid; $routes = $this->getAllroutes(); foreach ($allpower as $power) { if ($routes->has($power->purl) || $power->purl == "#") { $power->active = ""; //构造一个 leftMenu[父节点][子节点] 的数组; 父节点==0 是一级菜单。 父节点非0 二级菜单 if (strpos($mypower, 'ALL') !== false) {//含有所有的权限 $leftMenuCache[$power->parent_id][$power->id] = $power->toArray(); } else { $mypowerid = preg_split("/\\|/", $mypower); foreach ($mypowerid as $id) { if ($power->id == $id) { $leftMenuCache[$power->parent_id][$power->id] = $power->toArray(); } } } } } //遍历leftMenu 去掉 一级菜单中Url=# 并且没有子节点数据 $levelOne = $leftMenuCache[0]; foreach ($levelOne as $k => $v) { if ($v['purl'] == "#" && !array_key_exists($k, $leftMenuCache)) { unset($leftMenuCache[0][$k]); } } } return $leftMenuCache; }); $main_active = 0; $sub_action = 0; if (is_array($leftMenuCache)) { foreach ($leftMenuCache['allpower'] as $power) { //dump($power);die; if (strpos($power->purl, $action) !== false) { //当前Action 处理 菜单激活 $main_active = $power->parent_id; $sub_action = $power->id; } } } //只是处理菜单的Active 状态。 //如果都为0,看Session记录的状态 if ($main_active == 0 && $sub_action == 0) { $main_active = Session::get("ACTIVE_MAINMENU", 0); $sub_action = Session::get("ACTIVE_SUBMENU", 0); } else { Session::put("ACTIVE_MAINMENU", $main_active); Session::put("ACTIVE_SUBMENU", $sub_action); } if ($main_active != 0 && $sub_action != 0) { if (array_key_exists($main_active, $leftMenuCache[0])) { $leftMenuCache[0][$main_active]['active'] = "active"; } if (array_key_exists($main_active, $leftMenuCache) && array_key_exists($sub_action, $leftMenuCache[$main_active])) { $leftMenuCache[$main_active][$sub_action]['active'] = "active"; } } unset($leftMenuCache['allpower']); return $leftMenuCache; } public function getAllroutes() { $allroutes = app()->routes->getRoutes(); $routes = collect(); foreach ($allroutes as $k => $value) { if (isset($value->action['controller'])) { $route = collect([ 'uri' => $value->uri, 'path' => $value->methods[0], 'action' => Str::replaceFirst("App\\Http\\Controllers\\", "", $value->action['controller']), ]); $routes->push($route); } } return $routes->groupBy('action'); } }<file_sep>/app/Http/Controllers/admin/PowerController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\AdminPowerRequest; use App\Models\Admin\SysAdminPower; use App\Services\AdminUser; use App\Tools\Constant; use App\Tools\Result; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Log; use Yajra\DataTables\Facades\DataTables; class PowerController extends Controller { // public $adminUser; function __construct(AdminUser $user) { $this->adminUser = $user; } public function view(Request $request) { $id=$request->get('id',0); if ($id!=0) { $power = SysAdminPower::find($id); } else { $power = new SysAdminPower(); if ($request->pid > 0){ $power->parent_id = $request->pid; $data['pname'] =SysAdminPower::select('id','pname')->where('parent_id',0)->get(); } } $data['id']=$id; $data['pname'] =SysAdminPower::select('id','pname')->where('parent_id',0)->get(); $data['info']=$power; return view("admin.power_view",$data); } public function updateView(Request $request) { $id=$request->get('id',0); $power = SysAdminPower::find($id); $data['pid']=$power->parent_id; $data['pname'] = SysAdminPower::select('id','pname')->where('parent_id',0)->get(); $data['info']=$power; return view("admin.power_update_view",$data); } public function manager(Request $request) { $data['list']=SysAdminPower::where("parent_id",0) ->with('allchild') ->get(); $data['data'] = SysAdminPower::where('id',2) ->select("id","pname","ptype","desc")->get(); Log::error(json_encode($data['data'])); return view("admin.power_manager",$data); } public function list(Request $request) { $id=$request->get('id',0); if($id!=0){ $power = SysAdminPower::find($id); }else{ $power = new SysAdminPower(); } $data['pname'] =SysAdminPower::select('id','pname')->where('parent_id',0)->get(); $data['info']=$power; return view("admin.power_list",$data); } public function getListData() { $list = SysAdminPower::where('id','>',0); $datatable = DataTables::eloquent($list); return $datatable->make(true); } /** * @description 添加权限 * @param Request $request * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function save(Request $request){ $result =new Result(); if ($request->ajax()) { try { if ($request->post('id')>0) { $power = SysAdminPower::find($request->id); } else { $power = new SysAdminPower(); } $power->fill($request->all()); $power->save(); $result->msg = "操作成功"; $result->code = Constant::OK; } catch (\Exception $e) { Log::info("权限添加失败",$e->getMessage()); $result->msg = "操作失败"; } } else { $result->msg = "Invalid Request"; } return response()->json($result); } /** * @description * @param Request $request * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function delete(Request $request){ $result =new Result(); if ($request->ajax()) { try { if($request->id>0){ $parent_id = SysAdminPower::select('parent_id')->where('parent_id',$request->id)->get()->toArray(); if (!$parent_id){ SysAdminPower::find($request->id)->update(['status'=>$request->status]); $result->msg = "操作成功"; $result->code = Constant::OK; }else{ $result->msg = "有子级不可删除"; $result->code = Constant::ERROR; } } } catch (\Exception $e) { $result->msg = "操作失败"; } } else { $result->msg = "Invalid Request"; } return response()->json($result); } } <file_sep>/app/Tools/ApiResult.php <?php namespace App\Tools; trait ApiResult { private function respond($data) { return response()->json($data); } public function error($msg,$code=Constant::ERROR){ return $this->respond(['code'=>$code,'msg'=>$msg]); } public function success($data,$msg="操作成功",$code=Constant::OK){ return $this->respond(['code'=>$code,'msg'=>$msg,'data'=>$data]); } /* * 过滤所有特殊字符的函数 */ public function filterStr($strParam) { $regex = "/\/|\~|\,|\。|\!|\?|\“|\”|\【|\】|\『|\』|\:|\;|\《|\》|\’|\‘|\ |\·|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/"; return preg_replace($regex, "", $strParam); } /** * 过滤表情 * @param $str 内容 * @return mixed */ public function filterEmoji($str) { $str = preg_replace_callback('/./u', function (array $match) { return strlen($match[0]) >= 4 ? '' : $match[0]; }, $str); $res = $this->filterStr($str); return $res; } //验证是否为合法手机号码 public function checkMobile($mobile) { if (strlen($mobile) < 12 && preg_match("/^1{1}\d{10}$/", $mobile)) { return true; } return false; } }<file_sep>/app/Models/Base/BaseSysAdminUser.php <?php namespace App\Models\Base; use Illuminate\Database\Eloquent\Model; class BaseSysAdminUser extends Model { protected $table='sys_admin_user'; protected $primaryKey='id'; public $timestamps = true; protected $fillable=[ 'login_name', // 账号 'nick_name', // 姓名 'email', // 邮箱 'tel', // 电话 'pwd', // 密码 'avatr', // 用户头像 'department_id', // 部门 'position_id', // 职位 角色 'city_id', // 城市id 'status', // 状态 1 正常 -1 锁定 'project_id', // 归属项目 0系统 'created_at', // 'updated_at', // ]; }//Created at 2020-03-23 03:21:01<file_sep>/database/migrations/admin/2020_03_31_055252_create_base_site_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateBaseSiteTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('base_site', function (Blueprint $table) { $table->id(); $table->string("site_title")->comment("网站标题"); $table->text("site_desc")->comment("网站描述"); $table->text("site_keyboard")->comment("网站关键字"); $table->string("site_copyright")->comment("版权"); $table->string("site_tel")->comment("电话"); $table->string("site_email")->comment("邮箱"); $table->string("site_address")->comment("地址"); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('base_site'); } } <file_sep>/app/Helps/Loge.php <?php /** * Created by PhpStorm. * User: caoxiaobin */ namespace App\Helpers; use Closure; use Illuminate\Support\Facades\File; use RuntimeException; use Psr\Log\LoggerInterface; use Illuminate\Log\Events\MessageLogged; use Illuminate\Contracts\Support\Jsonable; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Contracts\Support\Arrayable; class Loge { /** * The underlying logger implementation. * * @var \Psr\Log\LoggerInterface */ protected $logger; /** * The event dispatcher instance. * * @var \Illuminate\Contracts\Events\Dispatcher|null */ protected $dispatcher; protected $is_formatter = false; /** * Create a new log writer instance. * * @param \Psr\Log\LoggerInterface $logger * @param \Illuminate\Contracts\Events\Dispatcher|null $dispatcher * @return void */ public function __construct(LoggerInterface $logger, Dispatcher $dispatcher = null) { $this->logger = $logger; $this->dispatcher = $dispatcher; } /** * Log an emergency message to the logs. * * @param string $message 日志标题 * @param string/array/object $context 日志内容 * @param string $file 指定日志存放的路径 * @return void */ public function emergency($message, $context = '', $file = '') { $this->writeLog(__FUNCTION__, $message, $context, $file); } /** * Log an alert message to the logs. * * @param string $message 日志标题 * @param string/array/object $context 日志内容 * @param string $file 指定日志存放的路径 * @return void */ public function alert($message, $context = '', $file = '') { $this->writeLog(__FUNCTION__, $message, $context, $file); } /** * Log a critical message to the logs. * * @param string $message 日志标题 * @param string/array/object $context 日志内容 * @param string $file 指定日志存放的路径 * @return void */ public function critical($message, $context = '', $file = '') { $this->writeLog(__FUNCTION__, $message, $context, $file); } /** * Log an error message to the logs. * * @param string $message 日志标题 * @param string/array/object $context 日志内容 * @param string $file 指定日志存放的路径 * @return void */ public function error($message, $context = '', $file = '') { $this->writeLog(__FUNCTION__, $message, $context, $file); } /** * Log a warning message to the logs. * * @param string $message 日志标题 * @param string/array/object $context 日志内容 * @param string $file 指定日志存放的路径 * @return void */ public function warning($message, $context = '', $file = '') { $this->writeLog(__FUNCTION__, $message, $context, $file); } /** * Log a notice to the logs. * * @param string $message 日志标题 * @param string/array/object $context 日志内容 * @param string $file 指定日志存放的路径 * @return void */ public function notice($message, $context = '', $file = '') { $this->writeLog(__FUNCTION__, $message, $context, $file); } /** * Log an informational message to the logs. * * @param string $message 日志标题 * @param string/array/object $context 日志内容 * @param string $file 指定日志存放的路径 * @return void */ public function info($message, $context = '', $file = '') { $this->writeLog(__FUNCTION__, $message, $context, $file); } /** * Log a debug message to the logs. * * @param string $message 日志标题 * @param string/array/object $context 日志内容 * @param string $file 指定日志存放的路径 * @return void */ public function debug($message, $context = '', $file = '') { $this->writeLog(__FUNCTION__, $message, $context, $file); } /** * Log a message to the logs. * * @param string $message 日志标题 * @param string/array/object $context 日志内容 * @param string $file 指定日志存放的路径 * @return void */ public function log($message, $context = '', $file = '') { $this->writeLog(__FUNCTION__, $message, $context, $file); } /** * Dynamically pass log calls into the writer. * * @param string $message 日志标题 * @param string/array/object $context 日志内容 * @param string $file 指定日志存放的路径 * @return void */ public function write($message, $context = '', $file = '') { $this->writeLog(__FUNCTION__, $message, $context, $file); } /** * Write a message to the log. * @param $level 错误级别 * @param $message 日志标题 * @param $context 日志内容 * @param $file 指定日志存放的路径 */ protected function writeLog($level, $message, $context, $file) { $filePath = $this->filePath($file); $content = $this->analysisContext($context); $level = $this->getLevel($level, $file); $this->fireLogEvent($level, $message = $this->formatMessage($message), $content->last()); $result = $this->formatContext(debug_backtrace(), $level, $content->first(), $message); // $this->logger->{$level}($message); File::append($filePath, $result.PHP_EOL); } /** * @description 解析传入的内容 * @param $context 可传入的类型为对象 数组(允许多维数组) 字符串 * @return \Illuminate\Support\Collection * @auther caoxiaobin */ private function analysisContext($context) { if (is_object($context)) { if (method_exists($context, 'getMessage')) { $EventContext = $context->getMessage(); $ErrorLine = $context->getLine(); $context = array(); $context['Error'] = $EventContext; $context['ErrorLine'] = $ErrorLine; $EventContext = array(); } else { $context = $EventData = $context->toArray(); $context = $this->newArr($context); $EventContext = $context; } } else if (is_array($context)) { $context = $this->analysisArr($context); $EventContext = $context; } else { if (!empty($context)) { $context = $this->analysisStr($context); $EventContext = $context; } else { $EventContext = []; } } return collect([$context, $EventContext]); } /** * @param $file * @param $level * @return mixed * @description 错误级别 * @auther caoxiaobin */ private function getLevel($level, $file) { if (!empty($file)) { $channelsFile = ucfirst($file); $filePath = config('logging.channels.'.$channelsFile.'.path'); if (isset($filePath)) { $level == config('logging.channels.'.$channelsFile.'.level'); } } return $level; } /** * @description 解析对象传入的数组 * @param $context * @return array * @auther caoxiaobin */ private function newArr($context) { $result = array(); foreach ($context as $key => $value) { if (!is_array($value)) { $result = $this->analysisArr($context); break; } $newArr = array_divide($value); $firstValue = reset($newArr); $lastValue = end($newArr); foreach ($firstValue as $firstKey => $item) { $result[$item] = $lastValue[$firstKey]; } } return $result; } /** * @description 解析数组 * @param $arr * @param array $newArr * @return array * @auther caoxiaobin */ private function analysisArr($arr, $newArr = []) { $resultArr = []; $childArr = collect(); foreach ($arr as $key => $val) { if (!is_array($val)) { $resultArr[ucfirst($key)] = $val; } else { $childArr->push($val); } } $resultArr = array_merge($resultArr, $newArr); if ($childArr->isNotEmpty()) { return $this->analysisArr($childArr->collapse(), $resultArr); } return $resultArr; } /** * @param $str 字符串 * @param array $result * @return array * @description 解析字符串中是否有json串 * @auther caoxiaobin */ public function analysisStr($str, $result = []) { $context = json_decode($str); if ($context == null) { return ['context' => $str]; } $oldResult = $newArr = []; foreach ($context as $key => $item) { $key = str_replace('_', '', $key); if (!stristr($item, '{')) { $oldResult[ucfirst($key)] = $item; } else { $childArr = json_decode($item, true); $newArr = array_merge($newArr, $childArr); } } //info warning if (!empty($newArr)) { return $this->analysisStr(json_encode($newArr), $oldResult); } return array_merge($oldResult, $result); } /** * @description 创建目录,并返回文件存放地址 * @param $file 指定存放的文件名 * @return \Illuminate\Config\Repository|mixed|string * @auther caoxiaobin */ private function filePath($file) { if (!empty($file)) { $channelsFile = ucfirst($file); $filePath = config('logging.channels.'.$channelsFile.'.path'); if (isset($filePath)) { $default_dir = dirname($filePath); $fileName = substr(basename($filePath), 0, strlen(basename($filePath))-4).'.log'; $dirName = dirname(app_path()).'/'.$default_dir; if ($dirName != $default_dir) { $dirName = $default_dir; } $filePath = $dirName.'/'.$fileName; } else { $filePath = config('logging.channels.single.path'); $dirName = dirname($filePath); } } else { $filePath = config('logging.channels.single.path'); $dirName = dirname($filePath); } if (isset($_ENV['WWW_LOGDIR']) && !empty($_ENV['WWW_LOGDIR'])) { $filePath = $_ENV['WWW_LOGDIR']; $dirName = dirname($_ENV['WWW_LOGDIR']); } if(!is_writable($dirName) && is_dir($dirName)) { chmod($dirName,'0777'); } return $filePath; } /** * Register a new callback handler for when a log event is triggered. * * @param \Closure $callback * @return void * * @throws \RuntimeException */ public function listen(Closure $callback) { if (! isset($this->dispatcher)) { throw new RuntimeException('Events dispatcher has not been set.'); } $this->dispatcher->listen(MessageLogged::class, $callback); } /** * Fires a log event. * * @param string $level * @param string $message * @param array $context * @return void */ protected function fireLogEvent($level, $message, array $context = []) { // If the event dispatcher is set, we will pass along the parameters to the // log listeners. These are useful for building profilers or other tools // that aggregate all of the log messages for a given "request" cycle. if (isset($this->dispatcher)) { $this->dispatcher->dispatch(new MessageLogged($level, $message, $context)); } } /** * Format the parameters for the logger. * * @param mixed $message * @return mixed */ protected function formatMessage($message = '') { if (is_array($message)) { return var_export($message, true); } elseif ($message instanceof Jsonable) { return $message->toJson(); } elseif ($message instanceof Arrayable) { return var_export($message->toArray(), true); } return $message; } /** * Get the underlying logger implementation. * * @return \Psr\Log\LoggerInterface */ public function getLogger() { return $this->logger; } /** * Get the event dispatcher instance. * * @return \Illuminate\Contracts\Events\Dispatcher */ public function getEventDispatcher() { return $this->dispatcher; } /** * Set the event dispatcher instance. * * @param \Illuminate\Contracts\Events\Dispatcher $dispatcher * @return void */ public function setEventDispatcher(Dispatcher $dispatcher) { $this->dispatcher = $dispatcher; } /** * Dynamically proxy method calls to the underlying logger. * * @param string $method * @param array $parameters * @return mixed */ public function __call($method, $parameters) { return $this->logger->{$method}(...$parameters); } /** * @param array $error * @param string $level 错误级别 * @param array $context 日志内容 * @param string $message 日志标题 * @return false|string * @description 监听错误文件 * @auther caoxiaobin */ private function formatContext($error, $level, $context, $message) { next($error); next($error); $innerResult = current($error); next($error); $outResult = current($error); if ($level == 'channel') { $level = 'debug'; } $levels = strtoupper($level); $result = [ 'Applicaiton' => config('app.name'), 'Environment' => config('app.model'), 'Message' => $message, 'Model'=>$this->subTit($outResult['class'], "\\"), 'Class'=>$outResult['class'], 'Function'=>$outResult['function'], 'Line'=>$innerResult['line'], 'Args'=> $outResult['args'], 'File'=>isset($innerResult['file']) ? $innerResult['file'] : reset($error)['file'], 'Level'=>$levels, 'BeCalledFile'=>isset($outResult['file']) ? $outResult['file'] : reset($error)['file'], 'BeCalledLine'=>isset($outResult['line']) ? $outResult['line'] : reset($error)['line'], 'Time'=>date('Y-m-d H:i:s') ]; $msg = json_decode($message,true); $newMessage = []; foreach ($msg as $key => $value) { $newMessage['msg_' . $key] = $value; } $result=array_merge($result,$newMessage); if (!empty($context)) { $res = json_encode(array_merge($result, $context)); } else { $res = json_encode($result); } return $res; } /** * 获取类名 * @param $tit * @param $needle * @return bool|string */ private function subTit($tit, $needle) { return substr($tit, strrpos($tit, $needle)+1); } }<file_sep>/app/Http/Requests/Admin/AdminPowerRequest.php <?php namespace App\Http\Requests\Admin; use Illuminate\Foundation\Http\FormRequest; class AdminPowerRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return false; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $id=input ::get('id'); $addRules=[ 'pname' =>'required', 'icon' =>'required', 'pindex' =>'required', 'purl' =>'required', ]; $updateRules=[ 'pname' =>'required', 'icon' =>'required', 'purl' =>'required', 'pindex' =>'required', ]; if ($id > 0){ return $updateRules; }else{ return $addRules; } } public function messages() { return [ 'pname.required'=>'权限名称不能为空', 'icon.required'=>'权限图标不能为空', 'pindex.required'=>'排序不能为空', 'purl.required'=>'权限链接不能为空', ]; } } <file_sep>/routes/web.php <?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', "Frontend\IndexController@index", function () { return view('welcome'); }); Route::group(["namespace"=>"Frontend","prefix"=>"frontend"], function () { Route::get("index","IndexController@index");//首页 Route::get("about","IndexController@about");//关于 Route::get("essay","IndexController@essay");//课程体系 Route::get("learn","IndexController@learn");//教研教学 Route::get("study","IndexController@study");//AI学习平台 Route::get("omoMode","IndexController@omoMode");//OMO模式 Route::get("school","IndexController@school");//全国校区 Route::get("list","IndexController@list");//魔数动态 Route::get("detail","IndexController@detail");//魔数动态详情 }); <file_sep>/app/Services/ArticleServices.php <?php namespace App\Services; use App\Models\Backend\Article; use App\Tools\ApiResult; use App\Tools\Constant; use App\Tools\Result; class ArticleServices { use ApiResult; protected $result; protected $admin; public function __construct(AdminUser $admin) { $this->result = new Result(); $this->admin = $admin; } /** * @description 编辑内容 * @param $request * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function articleSave($request) { $id = $request['id'] ?? 0; if ($id < 1) { $article = new Article(); } else { $article = $this->getOneArticle($id); if (!$article) { return $this->error("内容不存在"); } } $thumb_img = $request["thumb_img_info"] ?? ""; if (!empty($thumb_img)) { $picInfo = json_decode($thumb_img,true); $picInfo = reset($picInfo); $request['thumb_img'] = $picInfo['m_url']; } $article->fill($request); if ($article->save()) { return $this->success("操作成功"); } else { return $this->error("操作失败"); } } /** * @description 详情 * @param $id 文章ID * @return Result 返回结果 * @auther xiaobin */ public function articleDetail($id) { if ($id >=1) { $article = $this->getOneArticle($id); if (!$article) { $this->result->code = Constant::ERROR; $this->result->msg = "操作失败"; return $this->result; } } else { $article = new Article(); } $data['info'] = $article; $data['admin_id'] = $this->admin->getId(); $this->result->msg = "操作成功"; $this->result->code = Constant::OK; $this->result->data = $data; return $this->result; } /** * @description 获取一条信息 * @param $id 文章ID * @return mixed * @auther caoxiaobin */ public function getOneArticle($id) { return Article::find($id); } /** * @description 文章列表 * @param $page 当前页数 * @return float|int * @auther caoxiaobin */ public function articleList($page) { $pageInfo = $this->pageInfo($page); $pageInfo["info"] = Article::where("is_show", 1) ->limit(reset($pageInfo)) ->offset(next($pageInfo)) ->orderBy("hot", "desc") ->orderBy("sort","asc")->get(); return $pageInfo; } /** * @description 获取偏移数 * @param $page 当前页数 * @return float|int * @auther caoxiaobin */ public function pageInfo($page) { $page == $page <=1 ? 1 : $page; $data['pageSize'] = Constant::PAGE_SIZE; $data["offset"] = ($page-1)*Constant::PAGE_SIZE; $count = Article::where("is_show", 1)->count(); $data["count"] = $count; return $data; } }<file_sep>/app/Models/Backend/Banner.php <?php namespace App\Models\Backend; use App\Models\Backend\Base\BaseBanner; class Banner extends BaseBanner { public function place() { return $this->hasOne(BannerPosition::class,"id","bposition"); } }//Created at 2020-03-25 06:31:23<file_sep>/app/Services/SysMediaBuild.php <?php namespace App\Services; use App\Models\Base\BaseSysMedia; class SysMediaBuild { /** * @param $ids * @return string|static * @description 根据IDS得到 数据 */ public function getDataByIds($ids){ $list = BaseSysMedia::whereIn('id',explode("|",$ids)) ->select('id','uid','m_type','m_format','m_name','m_url','m_size','m_width','m_height') ->get(); if($list->count()==0){ return ""; }else { return $list->keyBy('id'); } } public function getListByIds($ids){ $list = BaseSysMedia::whereIn('id',explode("|",$ids)) ->select('id','uid','m_type','m_format','m_name','m_url','m_size','m_width','m_height') ->get(); return $list; } public function getDataByUrls($urls){ $list = BaseSysMedia::whereIn('m_url',explode("|",$urls)) ->select('id','uid','m_type','m_format','m_name','m_url','m_size','m_width','m_height') ->get(); if($list->count()==0){ return ""; }else { return $list->keyBy('id'); } } public function getListByUrls($urls){ $list = BaseSysMedia::whereIn('m_urls',explode("|",$urls)) ->select('id','uid','m_type','m_format','m_name','m_url','m_size','m_width','m_height') ->get(); return $list; } /** * @param $id * @return string * @description 通过文件Id获得文件信息 */ public function buildFileDataById($id){ $list = BaseSysMedia::where('id',$id) ->select('id','uid','m_type','m_format','m_name','m_url','m_width','m_height','m_size') ->get(); if($list->count()==0){ return ""; }else{ return $list->keyBy('id'); } } /** * @param $url * @return string * @description 通过文件URL获得文件信息 */ public function buildFileDataByUrl($url){ $list = BaseSysMedia::where('m_url',$url) ->select('id','uid','m_type','m_format','m_name','m_url','m_width','m_height','m_size') ->get(); if($list->count()==0){ return ""; }else{ return $list->keyBy('id'); } } /** * @param $info * @return string * @description 文件信息中解析出来URL */ public function getUrl($info){ $url = ""; if(!empty($info)) { $info = json_decode($info); foreach ($info as $v) { $url = $v->m_url; break; } } return $url; } /** * @param $info * @return int * @description 文件信息中解析出来ID */ public function getId($info){ $id =""; if(!empty($info)) { $info = json_decode($info); foreach ($info as $v) { $id = $v->id; break; } } return $id; } /** * @param $info * @return array * @description 文件信息中解析出来URL 数组 */ public function getUrls($info){ $info = json_decode($info); $url =array(); foreach($info as $v){ array_push($url,$v->m_url); } return $url; } public function getUrlsStr($info){ $url =""; if(!empty($info)) { $info = json_decode($info); foreach ($info as $v) { $url .= $v->m_url . "|"; } } return $url; } /** * @param $info * @return array * @description 文件信息中解析出来ID 数组 */ public function getIds($info){ $id =array(); if(!empty($info)) { $info = json_decode($info); foreach ($info as $v) { array_push($url, $v->id); } } return $id; } /** * @param $info * @return string * @description 文件信息中解析出来ID 字符串 */ public function getIdsStr($info){ $ids =""; if(!empty($info)){ $info = json_decode($info); foreach($info as $v){ $ids.=$v->id."|"; } } return $ids; } /** * 查询当前用户所有的图片id */ public function getImgIds($uid){ $BaseSysMedia =BaseSysMedia::select('id')->where([ ['uid','=',$uid], ['m_status','=',1] ])->get()->toArray(); foreach ($BaseSysMedia as $k=>$v){ $imgId[] =$v['id']; } $imgId = "|".implode("|",$imgId)."|"; return $imgId; } }<file_sep>/app/Models/Admin/SysMedia.php <?php namespace App\Models\Admin; use App\Models\Base\BaseSysMedia; class SysMedia extends BaseSysMedia { }//Created at 2020-03-24 05:48:22<file_sep>/app/Models/Backend/Base/BaseBannerPosition.php <?php namespace App\Models\Backend\Base; use Illuminate\Database\Eloquent\Model; class BaseBannerPosition extends Model { protected $table='banner_position'; protected $primaryKey='id'; public $timestamps = true; protected $fillable=[ 'position_name', // 位置名称 'base_url', // 跳转地址 'image_size', // 图片大小 长*高*宽 'info', // 备注 'is_show', // 状态 1显示 2隐藏 'created_at', // 'updated_at', // ]; }//Created at 2020-04-01 07:50:29<file_sep>/app/Models/Backend/BannerPosition.php <?php namespace App\Models\Backend; use App\Models\Backend\Base\BaseBannerPosition; class BannerPosition extends BaseBannerPosition { }//Created at 2020-03-25 09:31:37<file_sep>/app/Models/Base/BaseSysAdminDepartment.php <?php namespace App\Models\Base; use Illuminate\Database\Eloquent\Model; class BaseSysAdminDepartment extends Model { protected $table='sys_admin_department'; protected $primaryKey='id'; public $timestamps = true; protected $fillable=[ 'dp_name', // 部门名称 'parent_id', // 父部门 'root_id', // 根部门 'level', // 部门等级 'path', // 部门归属 'powerid', // 部门权限 'status', // 部门状态 1 正常 'created_at', // 'updated_at', // ]; }//Created at 2020-03-23 06:14:37<file_sep>/app/Models/Admin/SysAdminPower.php <?php namespace App\Models\Admin; use App\Models\Base\BaseSysAdminPower; class SysAdminPower extends BaseSysAdminPower { public function child(){ return $this->hasMany(SysAdminPower::class,'parent_id','id'); } public function allchild() { return $this->child()->with('allchild'); } public function parent(){ return $this->hasOne(SysAdminPower::class ,'id','parent_id'); } public function myparent() { return $this->parent()->with('myparent'); } public static function getPathName($id){ $info = SysAdminPower::where('id',$id)->with('myparent')->first(); $pathName = ""; self::getParent($info,$pathName); return $pathName; } private static function getParent($info,&$name){ if(!empty($info->myparent)){ $name=$info->cname."/".$name; self::getParent($info->myparent,$name); }else{ $name=$info->cname."/".$name; } return $name; } public static function getAllChildId($info,&$ids){ if(!empty($info->allchild) && count($info->allchild)!=0 ){ $ids.=$info->id."|"; foreach($info->allchild as $v){ self::getAllChildId($v,$ids); } }else{ $ids.=$info->id."|"; } return $ids; } public function getTree($data, $pId=0) { $tree = []; foreach($data as $k => $v) { if($v->parent_id == $pId) { $childs = $this->getTree($data, $v->id); $v = [ 'id' => $v->id, 'pname' => $v->pname, 'pid' => $v->parent_id, 'child'=> $childs ]; $tree[] = $v; } } return $tree; } }//Created at 2020-03-23 03:33:41<file_sep>/app/Models/Base/BaseSysAdminPower.php <?php namespace App\Models\Base; use Illuminate\Database\Eloquent\Model; class BaseSysAdminPower extends Model { protected $table='sys_admin_power'; protected $primaryKey='id'; public $timestamps = true; protected $fillable=[ 'pname', // 权限名称 'ptype', // 1 左侧菜单 2顶部菜单 'icon', // 权限ICON样式名称 'desc', // 权限描述 'purl', // 权限地址 'parent_id', // 上级地址 'pindex', // 显示排序 'status', // 状态 1 显示 0不显示 'created_at', // 'updated_at', // ]; }//Created at 2020-03-23 03:33:38<file_sep>/app/Models/Backend/Article.php <?php namespace App\Models\Backend; use App\Models\Backend\Base\BaseArticle; class Article extends BaseArticle { }//Created at 2020-03-26 08:25:13<file_sep>/app/Http/Controllers/admin/UserController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\AdminUserRequest; use App\Models\Admin\SysAdminPosition; use App\Models\Admin\SysAdminUser; use App\Models\Base\BaseSysAdminDepartment; use App\Models\Base\BaseSysAdminPosition; use App\Models\Base\BaseSysAdminUser; use App\Services\AdminMethod; use App\Services\AdminUser; use App\Services\UserServices; use App\Tools\Constant; use App\Tools\Result; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Yajra\DataTables\Facades\DataTables; class UserController extends Controller { // private $user; protected $result; public $adminUser; private $adminMethod; public function __construct(AdminUser $admin,UserServices $user,AdminMethod $adminMethod) { $this->user = $user; $this->adminUser = $admin; $this->result = new Result(); $this->adminMethod = $adminMethod; } /** * @description 修改密码 * @param Request $request * @return Result|\Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function change(Request $request) { if ($request->ajax()) { return $this->user->editPwd($request->all()); } else { $result = $this->result->msg = "Invalid Request"; return response()->json($result); } } /** * @description 修改用户信息 * @param Request $request * @return Result|\Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function updateInfo(Request $request) { if ($request->ajax()) { return $this->user->updateInfo($request->all()); } else { $result = $this->result->msg = "Invalid Request"; return response()->json($result); } } public function list(Request $request){ $id=$request->get('id',0); if($id!=0){ $user = BaseSysAdminUser::find($id); }else{ $user = new BaseSysAdminUser(); } $data['city'] =$this->adminMethod->cityNameAll(); $data['city_names'] =$this->adminMethod->cityNameAllJson(); $data['info']=$user; $data['dp_name']= BaseSysAdminDepartment::all('id','dp_name'); $data['pt_name'] =BaseSysAdminPosition::all('id','position_name'); return view('admin.user_list',$data); } /** * @description 管理员列表 * @return \Illuminate\Http\JsonResponse * @throws \Exception * @auther caoxiaobin */ public function getListData(){ $list = SysAdminUser::where('sys_admin_user.id','>',0)->select('sys_admin_user.id','nick_name','email','tel','login_name', 'sys_admin_user.city_id','sys_admin_user.department_id','sys_admin_user.position_id', 'sys_admin_user.status','sys_admin_position.position_name','sys_admin_department.dp_name','sys_areacode.aname as city_name') ->leftjoin('sys_admin_department','sys_admin_department.id','=','sys_admin_user.department_id') ->leftjoin('sys_admin_position','sys_admin_position.id','=','sys_admin_user.position_id') ->leftjoin('sys_areacode','sys_areacode.aid','=','sys_admin_user.city_id'); $datatable =DataTables::eloquent($list); return $datatable->make(true); } /** * @description 添加登录账号 * @param AdminUserRequest $request * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function save(AdminUserRequest $request){ $result =new Result(); if($request->ajax()) { try { if($request->id>0){ $admin_user = SysAdminUser::find($request->id); $admin = SysAdminUser::find($request->id); }else{ $admin_user = new SysAdminUser(); $admin=""; } // if (in_array(10000,explode(',',$request->city_id))){ // if (count(explode(',',$request->city_id)) != 1){ // $result->msg = "添加全国不可选择分城市"; // $result->code = Constant::ERROR; // return response()->json($result); // } // } $admin_user->fill($request->all()); if (empty($request->id) || !empty($request->pwd)){ $admin_user->pwd = md5($request->get('pwd')); }else{ $admin_user->pwd = $<PASSWORD>; } $admin_user->position_id = $request->position_id ?? 0; $admin_user->save(); $result->msg = "操作成功"; $result->code = Constant::OK; } catch (\Exception $e) { Log::info($e->getMessage()."账号添加失败"); $result->msg = "操作失败"; $result->code = Constant::ERROR; } }else{ $result->msg = "Invalid Request"; } return response()->json($result); } /** * @description 禁用账号 * @param Request $request * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function delete(Request $request){ $result =new Result(); if ($request->ajax()) { try { $id = $request->post("id"); if ($id < 1) { $result->msg = "非法操作"; $result->code = Constant::ERROR; return response()->json($result); } $admin = SysAdminUser::find($id); if (!$admin) { $result->msg = "账号不存在"; $result->code = Constant::ERROR; return response()->json($result); } $admin->status = $request->post("status"); $admin->save(); $result->msg = "操作成功"; $result->code = Constant::OK; } catch (\Exception $e) { Log::info("禁用账号失败:".$e->getMessage()); $result->msg = "操作失败"; $result->code = Constant::ERROR; } }else{ $result->msg = "Invalid Request"; $result->code = Constant::ERROR; } return response()->json($result); } /*** * @param Request $request * @return \Illuminate\Http\JsonResponse * @description 添加级联效果 通过部门编号获得 职位信息 这个地方需要重新写 */ public function linkage(Request $request){ $department_id = $request->department_id ? $request->department_id : 1; $position= SysAdminPosition::select('id','position_name')->where('status',1)->where('department_id',$department_id)->get(); return response()->json($position); } } <file_sep>/app/Http/Controllers/Backend/MessageController.php <?php namespace App\Http\Controllers\Backend; use App\Http\Controllers\Controller; use App\Http\Requests\Backend\MessageRequest; use App\Models\Backend\Message; use App\Services\MessageServices; use App\Tools\ApiResult; use Yajra\DataTables\Facades\DataTables; class MessageController extends Controller { // use ApiResult; protected $message; public function __construct(MessageServices $message) { $this->message = $message; } public function show() { return view("message.index"); } /** * @description 留言列表 * @return \Illuminate\Http\JsonResponse * @throws \Exception * @auther caoxiaobin */ public function messageList() { $list = Message::where('id','>',0); $databases = DataTables::eloquent($list); return $databases->make(true); } /** * @description 留言提交 * @param MessageRequest $request * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function messageSave(MessageRequest $request) { if ($request->ajax()) { return $this->message->messageSave($request->all()); } return $this->error("操作失败"); } } <file_sep>/database/seeds/SysAdminUserSeeder.php <?php use Illuminate\Database\Seeder; class SysAdminUserSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { \App\Models\Base\BaseSysAdminUser::truncate(); \App\Models\Base\BaseSysAdminUser::insert( [["id"=>1,"login_name"=>"admin","nick_name"=>"admin","email"=>"<EMAIL>","tel"=>"17000000000","pwd"=>"<PASSWORD>","avatr"=>"","department_id"=>1,"position_id"=>"2","city_id"=>"10000","status"=>1,"project_id"=>0,"created_at"=>"2020-03-24 02:38:50","updated_at"=>"2020-03-24 02:38:50"]] ); } }//Created at 2020-03-24 06:20:03<file_sep>/app/Http/Requests/Admin/AdminUserRequest.php <?php namespace App\Http\Requests\Admin; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Input; class AdminUserRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function rules() { $id = Input::get('id'); $sid = Input::get('sid'); $addRules=[ 'nick_name' =>'required', 'login_name' =>'required|unique:magic_math.sys_admin_user,login_name|regex:/^[0-9a-zA-Z]+$/', 'email' =>'required|unique:magic_math.sys_admin_user,email|regex:/^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/', 'tel' =>'required|unique:magic_math.sys_admin_user,tel|regex:/^1[34578][0-9]\d{4,8}$/', 'pwd' =>'<PASSWORD>|between:5,15', 'city_id'=>'required', ]; $updateRules=[ 'nick_name' =>'required', 'email' =>'required|unique:magic_math.sys_admin_user,email,'.$id.',id|regex:/^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/', 'tel' =>'required|unique:magic_math.sys_admin_user,tel,'.$id.',id|regex:/^1[34578][0-9]\d{4,8}$/', // 'pwd' =>'<PASSWORD>|regex:/^[0-9a-zA-Z_]+$/|between:5,15', 'city_id'=>'required', ]; $setRules=[ 'nick_name' =>'required', 'email' =>'required|unique:magic_math.sys_admin_user,email,'.$id.',id|regex:/^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/', 'tel' =>'required|unique:magic_math.sys_admin_user,tel,'.$id.',id|regex:/^1[34578][0-9]\d{4,8}$/', ]; if ($sid == 5){ return $setRules; } if ($id > 0){ return $updateRules; }else{ return $addRules; } } public function messages() { return [ 'nick_name.required'=>'用户名称不能为空', 'login_name.required'=>'用户账号不能为空', 'login_name.unique'=>'用户账号不能重复', 'login_name.regex'=>'用户账号应为-小写,大写,数字', 'email.required'=>'邮箱名称不能为空', 'email.unique'=>'邮箱名称不能重复', 'email.regex'=>'邮箱格式不正确', 'pwd.required'=>'密码不能为空', 'pwd.regex'=>'密码格式不正确', 'pwd.between'=>'密码在5-15位之间', 'tel.required'=>'手机号不能为空', 'tel.unique'=>'手机号不能重复', 'tel.regex'=>'手机号格式不正确', // 'city_id.required'=>' 必须选择城市', ]; } } <file_sep>/app/Http/Requests/Backend/ArticleRequest.php <?php namespace App\Http\Requests\Backend; use Illuminate\Foundation\Http\FormRequest; class ArticleRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'title' =>'required', 'summary' => 'required', 'thumb_img_info' => 'required', 'admin' => 'required', 'com' => 'required', ]; } public function messages() { return [ 'title.required'=>'标题不能为空', 'summary.required'=>'摘要不能为空', 'thumb_img_info.required'=>'缩率图不能为空', 'admin.required'=>'编辑人员不能为空', 'com.required'=>'文章来源不能为空', ]; } } <file_sep>/app/Models/Base/BaseSysAdminLoginLog.php <?php namespace App\Models\Base; use Illuminate\Database\Eloquent\Model; class BaseSysAdminLoginLog extends Model { protected $table='sys_admin_login_log'; protected $primaryKey='id'; public $timestamps = true; protected $fillable=[ 'admin_id', // 管理员id 'login_name', // 管理员名称 'login_role', // 管理员角色 'client_ip', // ip 'browser_info', // 登陆浏览器及版本 'os_info', // 操作系统信息 'created_at', // 'updated_at', // ]; }//Created at 2020-03-23 03:26:19<file_sep>/app/Models/Admin/SysAdminPosition.php <?php namespace App\Models\Admin; use App\Models\Base\BaseSysAdminPosition; class SysAdminPosition extends BaseSysAdminPosition { }//Created at 2020-03-23 03:25:06<file_sep>/app/Tools/Result.php <?php namespace App\Tools; class Result { public $code; public $msg; public $data; function __construct() { $this->code = Constant::ERROR; $this->msg = "处理失败"; $this->data = []; } }<file_sep>/app/Models/Backend/Essay.php <?php namespace App\Models\Backend; use App\Models\Backend\Base\BaseEssay; class Essay extends BaseEssay { public function posi() { return $this->hasOne(BannerPosition::class, "id","banner_position_id"); } }//Created at 2020-03-30 09:46:34<file_sep>/config/www.php <?php return array( 'assets' => env('WWW_ASSETS',env('APP_URL')), 'uploadfile' => env('WWW_UPLOADFILE', base_path('public/storage/uploadfile/')), 'imgurl' => env('WWW_IMG', ''), 'name' => env('WWW_NAME', '魔法数学'), 'nick' => env('WWW_NICK', 'majic'), 'company' => env('WWW_COMPANY', '易学教育科技有限公司'), );<file_sep>/app/Services/AdminMethod.php <?php namespace App\Services; use App\Models\Base\BaseSysAreacode; use App\Models\Base\BaseSysMedia; use App\Tools\Constant; class AdminMethod extends Constant { /** * 获取图片的所有值 */ public function getImgDefault($img_url) { $imgDefault =[]; if (!empty($img_url)){ $img_url_arr = explode('|',$img_url); foreach ($img_url_arr as $v){ $yuanshi = BaseSysMedia::where('m_url',$v)->first(); if ($yuanshi){ $imgDefault["$yuanshi->id"] = [ "m_width"=>$yuanshi->m_width, "m_height"=>$yuanshi->m_height, "uid"=>$yuanshi->uid, "m_name"=>$yuanshi->m_name, "m_url"=>$yuanshi->m_url, "m_type"=>$yuanshi->m_type, "m_format"=>$yuanshi->m_format, "m_size"=>$yuanshi->m_size, "id"=>$yuanshi->id, ]; } } } return json_encode($imgDefault); } /** * @name 一天中 所有刻 * @return array * @example 00:15 00:30 00:45 01:00 */ public function moment($begin = "2018-01-01 00:00:00",$end = "2018-01-01 24:00:00"){ $begintime = strtotime($begin); $endtime = strtotime($end); for ($start = $begintime; $start <= $endtime; $start += 900) { $moment[] = date("H:i", $start); unset($moment[0]); unset($moment[96]); } return $moment; } /** * 获取所有已开通的城市id 包含全国 */ public function cityNameAll() { $provinces = BaseSysAreacode::where([['parent_id',-1],['a_status','=','1']])->select('aid','aname')->get()->toArray(); $data = collect(); $data->push([ 'aid'=>10000, 'aname'=>'全国' ]); if(!empty($provinces)) { $cites = BaseSysAreacode::where('a_status',1)->whereIn('parent_id',array_column($provinces,'aid'))->select('parent_id','aname','aid')->get()->toArray(); foreach ($provinces as $province) { foreach ($cites as $city){ if($city['parent_id'] == $province['aid']){ $data->push($city); } } } } return $data->toArray(); } public function cityNameAllJson() { $city= $this->cityNameAll(); $city_list =[]; foreach ($city as $k=>$v){ $city_list[$v['aname']] =$v['aid']; } $city_names = json_encode(array_flip($city_list),JSON_UNESCAPED_UNICODE); return $city_names; } /** * 获取所有已开通的城市id */ public function cityName() { $provinces = BaseSysAreacode::where([['parent_id',-1],['a_status','=','1']])->select('aid','aname')->get()->toArray(); $data = collect(); if(!empty($provinces)) { $cites = BaseSysAreacode::where('a_status',1)->whereIn('parent_id',array_column($provinces,'aid'))->select('parent_id','aname','aid')->get()->toArray(); foreach ($provinces as $province) { foreach ($cites as $city){ if($city['parent_id'] == $province['aid']){ $data->push($city); } } } } return $data->toArray(); } /** * 获取所有的城市id */ public function citysNames() { $provinces = BaseSysAreacode::where([['parent_id',-1]])->select('aid','aname')->get()->toArray(); $data = collect(); if(!empty($provinces)) { $cites = BaseSysAreacode::whereIn('parent_id',array_column($provinces,'aid'))->select('parent_id','aname','aid')->get()->toArray(); foreach ($provinces as $province) { foreach ($cites as $city){ if($city['parent_id'] == $province['aid']){ $data->push($city); } } } } return $data->toArray(); } /** * 获取所有的城市id 名称 */ public function citysIdNames() { foreach ($this->cityNameAll() as $v){ $res[$v['aid']] =$v['aname']; } return $res; } /** * start 开始时间 * end 结束时间 * 获取开始到结束时间 中间的所有月份 */ function showMonthRange($start, $end) { $end = date('Ym', strtotime($end)); $range = []; $i = 0; do { $month = date('Ym', strtotime($start . ' + ' . $i . ' month')); $range[] = $month; $i++; } while ($month < $end); return $range; } /** * 查询数组中所有的子级 * $array 需要传输的的数组 * $parent_id 从父id 0开始 */ public function get_categories_tree_array($array,$parent_id=0,$new_array=[]){ foreach ($array as $key=>$val){ if($val->parent_id==$parent_id){ $new_array[]=$val; if(!($val->service)){ $new_array[count($new_array)-1]['service']=collect(); } unset($array[$key]); $this->get_categories_tree_array($array,$val['id'],$new_array[count($new_array)-1]['service']); } } return ($new_array); } /** * 获取当前用户的城市 * All 是全国 */ public function getAdminCity(){ $city =new AdminUser(); $city = explode(',',$city->getUser()->city_id); if (in_array(10000,$city)){ $city_id = $this->cityName(); }else{ $city_id = BaseSysAreacode::whereIn('aid',$city)->select('aid','aname','parent_id')->get()->toArray(); } return $city_id; } public function getAdminCityAll(){ $city =new AdminUser(); $city = explode(',',$city->getUser()->city_id); if (in_array(10000,$city)){ $city_id = $this->cityNameAll(); }else{ $city_id = BaseSysAreacode::whereIn('aid',$city)->select('aid','aname','parent_id')->get()->toArray(); } return $city_id; } /** * @name 计算时间差 * @param $startdate * @param $enddate * @return float|string * @val 返回 列 1天1小时1分钟 * $val $startdate 开始时间 $enddate 结束时间 */ function timeDifference($startdate,$enddate){ if (empty($startdate) || empty($startdate) || ($enddate < $startdate)){ return "错误时间"; } $date=floor((strtotime($enddate)-strtotime($startdate))/86400); $hour=floor((strtotime($enddate)-strtotime($startdate))%86400/3600); $minute=floor((strtotime($enddate)-strtotime($startdate))%86400/60%60); // $second=floor((strtotime($enddate)-strtotime($startdate))%86400%60); $date = $date."天".$hour."小时".$minute."分钟"; return $date; } }<file_sep>/app/Models/Base/BaseSysAdminPosition.php <?php namespace App\Models\Base; use Illuminate\Database\Eloquent\Model; class BaseSysAdminPosition extends Model { protected $table='sys_admin_position'; protected $primaryKey='id'; public $timestamps = true; protected $fillable=[ 'position_name', // 职位名称 'department_id', // 归属部门 'desc', // 职位描述 'powerid', // 职位权限 'status', // 职位状态 1 正常 'city_id', // 城市id 'created_at', // 'updated_at', // ]; }//Created at 2020-03-23 03:33:28<file_sep>/app/Services/SiteServices.php <?php namespace App\Services; use App\Models\Admin\Site; use App\Tools\ApiResult; use App\Tools\Constant; use Illuminate\Support\Facades\Cache; class SiteServices { use ApiResult; /** * @description 添加站点 * @param $request * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin * date: 2020-04-01 */ public function siteSave($request) { $id = $request->post("id", 0); if ($id < 1) { $site = new Site(); } else { $site = Site::find($id); } $site->fill($request->all()); if ($site->save()) { Cache::forget("site_info"); return $this->success("操作成功"); } else { return $this->error("操作失败"); } } /** * @description 存入缓存 * @return mixed * @auther caoxiaobin */ public function siteInfo() { return Cache::remember("site_info",Constant::VALID_TIME, function () { return Site::first(); }); } }<file_sep>/app/Models/Admin/SysAdminLoginLog.php <?php namespace App\Models\Admin; use App\Models\Base\BaseSysAdminLoginLog; class SysAdminLoginLog extends BaseSysAdminLoginLog { }//Created at 2020-03-23 03:25:31<file_sep>/app/Services/EssayServices.php <?php namespace App\Services; use App\Models\Backend\BannerPosition; use App\Models\Backend\Essay; use App\Tools\ApiResult; use App\Tools\Constant; use App\Tools\Result; use Illuminate\Support\Facades\Cache; class EssayServices { use ApiResult; protected $admin; protected $result; public function __construct(AdminUser $admin) { $this->admin = $admin; $this->result = new Result(); } /** * @description 获取详情 * @param $id * @return Result * @auther caoxiaobin */ public function essayDetail($id) { if ($id < 1) { $info = new Essay(); } else { $info = $this->essayOne($id); } $position = BannerPosition::where('is_show',1)->get(); $data = [ 'admin_id' => $this->admin->getId(), 'info' => $info, 'position' => $position, ]; $this->result->code = Constant::OK; $this->result->msg = "操作成功"; $this->result->data = $data; return $this->result; } /** * @description 新增/编辑内容 * @param $data * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function essaySave($data) { $id = $data['id'] ?? 0; if ($id < 1) { $essay = new Essay(); } else { $essay = $this->essayOne($id); } $essay_img_info = $data['essay_img_info']; $picList = []; if (!empty($essay_img_info)) { $picInfo = json_decode($data['essay_img_info'],true); foreach ($picInfo as $pic) { array_push($picList, $pic['m_url']); } $data['essay_img'] = implode(",",$picList); } $essay->fill($data); if ($essay->save()) { Cache::forget("essay_list{$essay->banner_position_id}"); return $this->success("操作成功"); } return $this->error("操作失败"); } /** * @description 删除某篇文章 * @param $id * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function essayDel($id) { if ($id < 1) { return $this->error("操作失败"); } $essay = $this->essayOne($id); if (!$essay) { return $this->error("内容不存在"); } $essay->essay_status = 0; if ($essay->save()) { Cache::forget("essay_list{$essay->banner_position_id}"); return $this->success("操作成功"); } return $this->error("操作失败"); } /** * @description 通过ID获取一条记录 * @param $id 文章ID * @return mixed * @auther caoxiaobin */ public function essayOne($id) { return Essay::find($id); } }<file_sep>/app/Http/Controllers/Frontend/IndexController.php <?php namespace App\Http\Controllers\Frontend; use App\Http\Controllers\Controller; use App\Services\ArticleServices; use App\Services\BannerServices; use App\Services\FrontendServices; use App\Services\SiteServices; use Illuminate\Support\Facades\Input; class IndexController extends Controller { // protected $frontend; protected $article; protected $position; public function __construct(FrontendServices $frontend,ArticleServices $article,BannerServices $position) { $this->frontend = $frontend; $this->article = $article; $this->position = $position; } /** * @description 首页信息 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther caoxiaobin */ public function index() { $site = new SiteServices(); $data["banner"] = $this->frontend->banner(1); $data["essay"] = $this->frontend->essay(1); $data['menuList'] = $this->position->menu(); $data["site"] = $site->siteInfo(); return view("welcome", $data); } /** * @description 关于魔数 * @auther caoxiaobin */ public function about() { $data["banner"] = $this->frontend->banner(2); $data["essay"] = $this->frontend->essay(2); return view("index.about"); } /** * @description 课程体系 * @auther caoxiaobin */ public function essay() { $data["banner"] = $this->frontend->banner(3); $data["essay"] = $this->frontend->essay(3); return view("index.essay"); } /** * @description 教研教学 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther caoxiaobin */ public function learn() { $data["banner"] = $this->frontend->banner(4); $data["essay"] = $this->frontend->essay(4); return view("index.essay"); } /** * @description AI学习平台 * @auther caoxiaobin */ public function study() { $data["banner"] = $this->frontend->banner(5); $data["essay"] = $this->frontend->essay(5); return view("index.study"); } /** * @description OMO模式 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther caoxiaobin */ public function omoMode() { $data["banner"] = $this->frontend->banner(6); $data["essay"] = $this->frontend->essay(6); return view("index.mode"); } /** * @description 全国校区 * @auther caoxiaobin */ public function school() { $data["banner"] = $this->frontend->banner(7); $data["essay"] = $this->frontend->essay(7); return view("index.school"); } /** * @description 魔数动态 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther caoxiaobin */ public function list() { $articleList = $this->article->articleList(Input::get("id")); return view("index.list", $articleList); } /** * @description 魔数动态详情 * @auther caoxiaobin */ public function detail() { $detail = $this->article->getOneArticle(Input::get("id")); if (!$detail) { return back()->with(["内容不存在"]); } return view("index.detail"); } } <file_sep>/database/migrations/message/2020_03_26_081834_create_message_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateMessageTable extends Migration { /** * Run the migrations. * 留言 * @return void */ public function up() { Schema::create('message', function (Blueprint $table) { $table->id(); $table->string("mname",100)->comment("姓名"); $table->string("area",100)->comment("地区"); $table->string("tel",20)->comment("电话"); $table->text("content")->comment("留言内容"); $table->string("com")->comment("留言来源页"); $table->string("client")->comment("客户端"); $table->string("ip",50)->comment("ip地址"); $table->integer("channel")->comment("留言板块"); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('message'); } } <file_sep>/app/Http/Controllers/admin/AdminController.php <?php namespace App\Http\Controllers\Admin; use App\Helpers\Logs; use App\Http\Controllers\Controller; use App\Models\Admin\SysAdminUser; use App\Models\Base\BaseSysAdminUser; use App\Services\AdminUser; use App\Services\MessageServices; use App\Services\SysMediaBuild; use App\Tools\Constant; use App\Tools\Result; use Illuminate\Http\Request; use Illuminate\Support\Facades\Session; class AdminController extends Controller{ private $uid=0; private $fb; private $user; protected $message; public function __construct(SysMediaBuild $fb,AdminUser $user,MessageServices $message) { $this->adminUser = $user; $this->fb = $fb; $this->user = $user; $this->message = $message; } public function index() { $data = $this->message->totalMessage(); return view('master.home', $data); } /** * 主页 */ public function main(){ return view('master.home'); } /** * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @description 登陆 */ public function loginViews(){ return view('admin.login'); } /** * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @description 退出 */ public function login(Request $request) { $result =new Result(); if($request->ajax()) { try { $login_name = $request->post("login_name"); $user = BaseSysAdminUser::where('login_name',$login_name)->where('status',1)->first(); if(!empty($login_name) && !empty($user)){ if($user->pwd == md5($request->post('pwd'))){ unset($user->pwd); // Log::error("Login= ".json_encode($user)); $this->adminUser->setId($user->id); $userInfo = SysAdminUser::where('id',$user->id)->with('department')->with('position')->first(); unset($userInfo->pwd); $this->adminUser->setUser($userInfo); $result->code = Constant::OK; $result->msg = "登录成功!"; // Log::error("Login ID =".$this->adminUser->getId()); }else{ $result->msg = "密码不正确"; } }else{ $result->msg = "账号不存在"; } } catch (\Exception $e) { Logs::error('操作失败',$e); $result->msg = "操作失败:".$e->getMessage(); } }else{ $result->msg = "Invalid Request"; } return response()->json($result); } /** * 退出登录 * @return array */ public function logout(){ $this->adminUser->forget(); return view("admin.login"); } /** * @param Request $request * @return \Illuminate\Http\JsonResponse * @description 更新资料 */ public function anyUpdate(Request $request){ $result =new Result(); if($request->ajax()) { try { $account = BaseSysAdminUser::find($this->uid); if(!empty($account)){ $pwd = $request->get("pwd"); $newpwd = $request->get('newpwd'); $flag = true; if($pwd!="" && $newpwd!=""){ if($account->password == md5($pwd)){ $account->password=md5($newpwd); }else{ $flag = false; $result->msg = "操作失败:原密码输入错误"; } } if($flag){ $account->avata = $this->fb->getUrl($request->get('img')); $account->uname = $request->get('uname'); $account->save(); $result->code = Constant::OK; $result->msg = "操作成功"; } }else{ $result->msg = "操作失败:参数缺失"; } } catch (\Exception $e) { $result->msg = "操作失败:".$e->getMessage(); } }else{ $result->msg = "Invalid Request"; } return response()->json($result); } /** * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @description 登陆成功主页 */ public function getIndex(){ Session::forget("ACTIVE_MAINMENU"); Session::forget("ACTIVE_SUBMENU"); if(Session::has(Constant::$SESSION_USER)){ return view('admin.index'); }else{ return view('admin.login'); } } public function getDoc(){ return view('admin.doc'); } public function getWelcome(){ return view('admin.welcome'); } } <file_sep>/app/Http/Requests/Admin/SiteRequest.php <?php namespace App\Http\Requests\Admin; use Illuminate\Foundation\Http\FormRequest; class SiteRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ // "site_title" => "required", "site_desc" => "required", "site_keyboard" => "required", "site_copyright" => "required", "site_tel" => "required", "site_email" => "required", "site_address" => "required", ]; } public function messages() { return [ "site_title.required" => "网站标题不能为空", "site_desc.required" => "网站描述不能为空", "site_keyboard.required" => "网站关键字不能为空", "site_copyright.required" => "网站版权不能为空", "site_tel.required" => "联系电话不能为空", "site_email.required" => "联系邮箱不能为空", "site_address.required" => "联系地址不能为空", ]; } } <file_sep>/database/migrations/admin/2020_03_23_033211_sys_admin_power_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class SysAdminPowerTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('sys_admin_power', function (Blueprint $table) { $table->increments('id'); $table->string('pname',"50")->comment("权限名称"); $table->integer('ptype')->default('1')->comment("1 左侧菜单 2顶部菜单"); $table->string('icon',"50")->default('')->comment("权限ICON样式名称"); $table->string('desc',"50")->default('')->comment("权限描述"); $table->string('purl',100)->comment("权限地址"); $table->integer('parent_id')->default('0')->comment("上级地址"); $table->integer('pindex')->default('0')->comment("显示排序"); $table->integer('status')->default('1')->comment("状态 1 显示 0不显示"); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('sys_admin_power'); } } <file_sep>/database/migrations/admin/2020_03_24_054654_sys_media_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class SysMediaTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('sys_media', function (Blueprint $table) { $table->increments('id'); $table->integer('uid')->default('0')->comment('所有者'); $table->integer('m_type')->default('10000')->comment('媒体文件分类'); $table->string('m_format',50)->default('image/jpeg')->comment('媒体文件格式'); $table->string('m_name',100)->comment('媒体文件分类原名'); $table->string('m_url',150)->comment('媒体文件存储地址'); $table->integer('m_size')->default('0')->comment('文件大小'); $table->integer('m_width')->default('0')->comment('文件宽度'); $table->integer('m_height')->default('0')->comment('文件高度'); $table->integer('m_qiniu')->default('0')->comment('七牛文件同步状态'); $table->text('m_metadata')->comment('文件原始数据'); $table->integer('m_status')->default('1')->comment('文件状态'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('sys_media'); } } <file_sep>/database/migrations/banner/2020_03_25_092940_create_banner_position_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateBannerPositionTable extends Migration { /** * Run the migrations. * banner 位置 * @return void */ public function up() { Schema::create('banner_position', function (Blueprint $table) { $table->id(); $table->string('position_name')->comment("位置名称"); $table->string('image_size')->comment("图片大小 长*高*宽"); $table->string('info')->nullable()->comment("备注"); $table->integer('is_show')->comment("状态 1显示 2隐藏"); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('banner_position'); } } <file_sep>/app/Models/Backend/Base/BaseBanner.php <?php namespace App\Models\Backend\Base; use Illuminate\Database\Eloquent\Model; class BaseBanner extends Model { protected $table='banner'; protected $primaryKey='id'; public $timestamps = true; protected $fillable=[ 'province', // 省 'city', // 市 'area', // 区 'bname', // 名称 'bposition', // 位置 1 首页 'imgurl', // 图片地址 'target_link', // 跳转链接 'begin_time', // 显示开始时间 'end_time', // 显示结束时间 'is_show', // 状态 1显示 2隐藏 'image_size', // 图片大小 长*高*宽 'info', // 备注 'img_info', // 图片详细 'created_at', // 'updated_at', // ]; }//Created at 2020-03-27 02:19:18<file_sep>/app/Models/Base/BaseSysMedia.php <?php namespace App\Models\Base; use Illuminate\Database\Eloquent\Model; class BaseSysMedia extends Model { protected $table='sys_media'; protected $primaryKey='id'; public $timestamps = true; protected $fillable=[ 'uid', // 所有者 'm_type', // 媒体文件分类 'm_format', // 媒体文件格式 'm_name', // 媒体文件分类原名 'm_url', // 媒体文件存储地址 'm_size', // 文件大小 'm_width', // 文件宽度 'm_height', // 文件高度 'm_qiniu', // 七牛文件同步状态 'm_metadata', // 文件原始数据 'm_status', // 文件状态 'created_at', // 'updated_at', // ]; }//Created at 2020-03-24 05:48:09<file_sep>/app/Helps/Logs.php <?php /** * Created by PhpStorm. * User: caoxiaobin * Time: 2:27 PM */ namespace App\Helpers; use Illuminate\Support\Facades\Facade; /** * @method static void emergency(string $message, array $context = [],$file='') * @method static void alert(string $message, array $context = [],$file='') * @method static void critical(string $message, array $context = [],$file='') * @method static void error(string $message, array $context = [],$file='') * @method static void warning(string $message, array $context = [],$file='') * @method static void notice(string $message, array $context = [],$file='') * @method static void info(string $message, array $context = [],$file='') * @method static void debug(string $message, array $context = [],$file='') * @method static void log($level, string $message, array $context = [],$file='') * @method static \Psr\Log\LoggerInterface stack(array $channels, string $channel = null) * fuck * @see \Illuminate\Log\Logger */ class Logs extends Facade { protected static function getFacadeAccessor() { return Loge::class; } } <file_sep>/app/Tools/Constant.php <?php namespace App\Tools; class Constant { const OK = "10000"; const ERROR = "20000"; const SUCCESS = "SUCCESS"; const FAIL ="ERROR"; const ADMIN_SESSION = "Admin_Session"; const ADMIN_SESSION_ID = "Admin_Session_ID"; const SESSION_MENU = 'SessionMenu'; const SERVICE_CATEGORIES='service_categories'; const PAGE_SIZE = 10;//每页显示数量 const VALID_TIME = 86400*30;//有效时间 }<file_sep>/database/migrations/admin/2020_03_23_030852_sys_admin_user_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class SysAdminUserTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Schema::create('sys_admin_user', function (Blueprint $table) { $table->increments('id'); $table->string("login_name",30)->comment("账号"); $table->string("nick_name",30)->comment("姓名"); $table->string("email",50)->comment("邮箱"); $table->string("tel",50)->comment("电话"); $table->string('pwd',50)->comment("密码"); $table->string("avatr","100")->nullable($value=true)->comment("用户头像"); $table->integer('department_id')->comment("部门"); $table->string('position_id',150)->nullable()->comment("职位 角色"); $table->text('city_id')->comment("城市id"); $table->integer('status')->default('1')->comment("状态 1 正常 -1 锁定"); $table->integer('project_id')->default('0')->comment("归属项目 0系统"); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { // Schema::dropIfExists('sys_admin_user'); } } <file_sep>/app/Models/Backend/Base/BaseEssay.php <?php namespace App\Models\Backend\Base; use Illuminate\Database\Eloquent\Model; class BaseEssay extends Model { protected $table='essay'; protected $primaryKey='id'; public $timestamps = true; protected $fillable=[ 'banner_position_id', // 位置 'essay_title', // 标题 'essay_content', // 内容 'essay_img', // 缩率图 'essay_status', // 状态 1显示 0隐藏 'essay_img_info', // 缩率图信息 'created_at', // 'updated_at', // ]; }//Created at 2020-03-31 02:35:56<file_sep>/database/migrations/admin/2020_03_24_054353_sys_areacode_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class SysAreacodeTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('sys_areacode', function(Blueprint $table) { $table->increments('id'); $table->integer('aid')->comment('区域编号'); $table->integer('a_level')->default(0)->comment('节点等级 1 省 2市 3区'); $table->integer('gaode_id')->default(0)->comment('高德ID'); $table->string('aname', 100)->comment('区域名称'); $table->integer('parent_id')->default(0)->comment('父节点'); $table->integer('a_status')->default(1)->comment('1 有效 0 无效'); $table->integer('root_id')->default(0)->comment('根节点ID'); $table->integer('is_show')->default(1)->comment('1 前端显示 0 不显示'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('sys_areacode', function (Blueprint $table) { // }); } } <file_sep>/database/migrations/banner/2020_03_25_062552_create_banner_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateBannerTable extends Migration { /** * Run the migrations. * banner * @return void */ public function up() { Schema::create('banner', function (Blueprint $table) { $table->id(); $table->string('province')->default(0)->comment("省"); $table->string('city')->default(0)->comment("市"); $table->string('area',150)->default("")->comment("区"); $table->string('bname',50)->comment("名称"); $table->integer("bposition")->comment("位置 1 首页"); $table->string("imgurl",150)->comment("图片地址"); $table->string('target_link',150)->default("#")->comment("跳转链接"); $table->string('begin_time',50)->nullable(true)->comment("显示开始时间"); $table->string('end_time',50)->nullable(true)->comment("显示结束时间"); $table->integer('is_show')->default(1)->comment("状态 1显示 2隐藏"); $table->string('image_size')->nullable(true)->comment("图片大小 长*高*宽"); $table->string('info')->nullable(true)->default("")->comment("备注"); $table->text('img_info')->comment("图片详细"); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('banner'); } } <file_sep>/app/Models/Backend/Message.php <?php namespace App\Models\Backend; use App\Models\Backend\Base\BaseMessage; class Message extends BaseMessage { }//Created at 2020-03-26 08:25:29<file_sep>/app/Http/Requests/Admin/AdminPositionRequest.php <?php namespace App\Http\Requests\Admin; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Input; class AdminPositionRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $id=Input::get('id'); // Log::error('======inputs====',json_encode(Input::all())); $addRules=[ 'position_name' =>'required|unique:magic_math.sys_admin_position,position_name', 'department_id' =>'required', 'desc' =>'required', ]; $updateRules=[ 'position_name' =>'required|unique:magic_math.sys_admin_position,position_name,'.$id.',id', 'department_id' =>'required', 'desc' =>'required', ]; if ($id > 0){ return $updateRules; }else{ return $addRules; } } public function messages() { return [ 'position_name.required'=>'职位名称不能为空', 'position_name.unique'=>'职位名称不能重复', 'department_id.required'=>'归属部门不能为空', 'desc.required'=>'职位描述不能为空', ]; } } <file_sep>/app/Http/Controllers/Backend/BannerController.php <?php namespace App\Http\Controllers\Backend; use App\Http\Controllers\Controller; use App\Models\Admin\SysAreacode; use App\Models\Backend\Banner; use App\Models\Backend\BannerPosition; use App\Services\AdminUser; use App\Services\BannerServices; use App\Tools\ApiResult; use App\Tools\Constant; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Yajra\DataTables\Facades\DataTables; class BannerController extends Controller { // use ApiResult; protected $banner; protected $admin; public function __construct(BannerServices $banner,AdminUser $admin) { $this->banner = $banner; $this->admin = $admin; } /** * @description banner列表 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther caoxiaobin */ public function index() { $areaCode = new SysAreacode(); $cities = $areaCode->province(); return view("banner.index", ['cities'=> $cities]); } /** * @description banner列表 * @return \Illuminate\Http\JsonResponse * @throws \Exception * @auther caoxiaobin */ public function bannerList() { $list = Banner::where([['id','>',0]])->with('place')->orderBy('is_show','desc'); $datatable = DataTables::eloquent($list); return $datatable->make(true); } /** * @description 添加banner详情页 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther caoxiaobin */ public function bannerDetail() { $banner = $this->banner->bannerDetail(Input::get('id')); if (!$banner->code == Constant::ERROR) { return back()->withErrors(['图片不存在']); } return view("banner.detail", $banner->data); } /** * @description banner操作 * @param Request $request * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function bannerSave(Request $request) { if ($request->ajax()) { return $this->banner->bannerSave($request->all()); } return $this->error("操作失败"); } /** * @description 图片删除 * @param Request $request * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function bannerDel(Request $request) { if ($request->ajax()) { return $this->banner->bannerDel($request->post("id",0)); } return $this->error("操作失败"); } /** * @description 轮播图展示位置 * @auther caoxiaobin */ public function positionList() { return view("banner.list"); } /** * @description 轮播图展示位置ajax * @return \Illuminate\Http\JsonResponse * @throws \Exception * @auther caoxiaobin */ public function positionData() { $list = BannerPosition::where('id','>',0); $datatable = DataTables::eloquent($list); return $datatable->make(true); } /** * @description 轮播图展示位置添加/编辑 * @param Request $request * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function positionSave(Request $request) { if ($request->ajax()) { return $this->banner->positionSave($request->all()); } return $this->error("操作失败"); } } <file_sep>/app/Console/Commands/YSeederCommand.php <?php namespace App\Console\Commands; use Carbon\Carbon; use Illuminate\Console\Command; use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Composer; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\File; class YSeederCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'seeder:create {name} {db?}'; /** * The console command description. * * @var string */ protected $description = '根据表名 导出Seed 文件 导出后需要执行 composer dump-autoload'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } protected $connName = "magic_math"; /** * Execute the console command. * * @return mixed */ public function handle() { if($this->hasArgument('db')){ $this->connName = $this->argument('db'); } $model = $this->getTemplate(); $modelName=""; $filePath = "./database/seeds/"; if($this->hasArgument('modelname')){ $modelName = ucfirst($this->argument('modelname'))."\\"; $filePath = "./database/seeds/".ucfirst($this->argument('modelname'))."/"; } $tableName = $this->argument('name'); $list = $this->getData($tableName); $className = $this->getClassName($tableName); $model = str_replace('MODEL_NAME',$modelName,$model); $model = str_replace('CLASS_NAME',$className,$model); $model = str_replace('INSERTS',$this->getSeedStr($list),$model); try{ if(!File::isDirectory($filePath)){ File::makeDirectory($filePath); } File::put($filePath."/".$className."Seeder.php",$model); $this->line($model); $this->info($filePath."/".$className."Seeder.php Seeder Created!!"); }catch (\Exception $e){ $this->error($e->getMessage()); } File::append($filePath."/".$className."Seeder.php","//Created at ".Carbon::now()->toDateTimeString()); //重新执行 $composer = new Composer(new Filesystem()); $composer->dumpAutoloads(); } //=== //=== protected function getTemplate(){ $model = <<<EOF <?php use Illuminate\Database\Seeder; class CLASS_NAMESeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { \App\Models\MODEL_NAMEBase\BaseCLASS_NAME::truncate(); \App\Models\MODEL_NAMEBase\BaseCLASS_NAME::insert( INSERTS ); } } EOF; return $model; } protected function getClassName($table){ $tableString = ''; $tableName = explode('_', $table); foreach ($tableName as $v) { $tableString .= ucfirst($v); } return ucfirst($tableString); } /** * Get the Data * @param string $table * @return Array */ protected function getData($table, $max=0, $exclude = null, $orderBy = null, $direction = 'ASC') { $result = DB::connection($this->connName)->table($table); if (!empty($exclude)) { $allColumns = DB::connection($this->connName)->getSchemaBuilder()->getColumnListing($table); $result = $result->select(array_diff($allColumns, $exclude)); } if($orderBy) { $result = $result->orderBy($orderBy, $direction); } if ($max) { $result = $result->limit($max); } return $result->get(); } protected function getSeedStr($list){ $str = json_encode($list,JSON_UNESCAPED_UNICODE); $str= str_replace('{','[',$str); $str= str_replace('}',']',$str); $str= str_replace('],[','],'.PHP_EOL.'[',$str); $str= str_replace('":','"=>',$str); return $str; } } <file_sep>/app/Models/Backend/Base/BaseArticle.php <?php namespace App\Models\Backend\Base; use Illuminate\Database\Eloquent\Model; class BaseArticle extends Model { protected $table='article'; protected $primaryKey='id'; public $timestamps = true; protected $fillable=[ 'title', // 标题 'summary', // 摘要 'thumb_img', // 缩率图 'admin', // 编辑者 'com', // 来源 'is_show', // 是否展示 1展示 2不展示 'content', // 内容 'hot', // 是否热点 1是 2否 'sort', // 优先级 数字越大,排名越前 'thumb_img_info', // 缩率图相关信息 'created_at', // 'updated_at', // ]; }//Created at 2020-03-27 02:18:57<file_sep>/app/Http/Requests/AdminDepartmentRequest.php <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class AdminDepartmentRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return false; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $addRules=[ 'dp_name' =>'required|unique:sys_admin_department,dp_name', ]; return $addRules; } public function messages() { return [ 'dp_name.required'=>'部门名称不能为空', 'dp_name.unique'=>'部门名称不能重复', ]; } } <file_sep>/README.md ## INIT shell ``` composer install mkdir -p storage/logs storage/app/public storage/framework/cache/data storage/framework/sessions storage/framework/views chmod -R 777 storage cp .env.example .env php artisan storage:link php artisan key:generate cd ./public/storage mkdir uploadfile ueditor php artisan migrate --database=majaic_math php artisan db:init ``` ## nginx.conf ``` user nobody; worker_processes 4; error_log /data/logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /data/logs/access.log main; sendfile on; client_max_body_size 100m; keepalive_timeout 65; #gzip on; fastcgi_connect_timeout 300; fastcgi_send_timeout 300; fastcgi_read_timeout 300; fastcgi_buffer_size 64k; fastcgi_buffers 4 64k; fastcgi_busy_buffers_size 128k; fastcgi_temp_file_write_size 128k; include /opt/local/etc/nginx/vhosts/*.conf; } ``` ## admin.conf ``` server { listen 80; server_name admin.com; root /laravel_admin/public; index index.html index.htm index.php; charset utf-8; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { include fastcgi_params; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } ```<file_sep>/app/Models/Admin/Site.php <?php namespace App\Models\Admin; use App\Models\Admin\Base\BaseBaseSite; class Site extends BaseBaseSite { }//Created at 2020-03-31 05:58:14<file_sep>/database/migrations/admin/2020_03_23_060317_sys_admin_department_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class SysAdminDepartmentTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('sys_admin_department', function (Blueprint $table) { $table->increments('id'); $table->string('dp_name',30)->nullable($value="")->comment('部门名称'); $table->integer('parent_id')->default('0')->comment("父部门"); $table->integer('root_id')->default('0')->comment("根部门"); $table->integer('level')->default('1')->comment("部门等级"); $table->string('path')->default('|')->comment("部门归属"); $table->text('powerid')->comment("部门权限"); $table->integer('status')->default('1')->comment("部门状态 1 正常"); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('sys_admin_department'); } } <file_sep>/app/Services/MessageServices.php <?php namespace App\Services; use App\Models\Backend\Message; use App\Tools\ApiResult; use Carbon\Carbon; class MessageServices { use ApiResult; /** * @description 留言提交 * @param $request * @return mixed * @auther caoxiaobin */ function messageSave($request) { $message = new Message(); $data['ip'] = $request->getClientIp(); $message->fill($data); if ($message->save()) { return $this->success("留言成功"); } return $this->error("留言失败"); } /** * @description 统计当日留言数量 * @return mixed * @auther caoxiaobin */ function totalMessage() { $dayParam = [ ['created_at', '>=', Carbon::now()->startOfDay()], ['created_at', '<=', Carbon::now()->endOfDay()] ]; $countDay = $this->countMessage($dayParam); $yesterday = date("Y-m-d", strtotime("-1day")); $yesterdayParam = [ ['created_at', '>=', $yesterday." 00:00:00"], ['created_at', '<=', $yesterday." 23:59:59"] ]; $countYesterday = $this->countMessage($yesterdayParam); return [ "day" => $countDay, "yesterday" => $countYesterday ]; } /** * @description 比例 * @param $val * @param $val2 * @return int * @auther caoxiaobin * date: 2020-04-01 */ public function rate($val, $val2) { if ($val == 0 && $val2 ==0) { return 0; } if ($val ==0) { return 0; } } /** * @description 获取某日的总数 * @param $param * @return mixed * @auther caoxiaobin */ public function countMessage($param) { return Message::where($param)->count(); } }<file_sep>/app/Http/Middleware/AdminAuth.php <?php namespace App\Http\Middleware; use App\Models\Admin\SysAdminPower; use App\Services\AdminUser; use Closure; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Facades\URL; use Illuminate\Support\Str; class AdminAuth { public function handle($request, Closure $next) { $actions =Str::replaceFirst("App\Http\Controllers\\","",\Route::current()->getActionName()); $adminUser = new AdminUser(); $uid = $adminUser->getId(); if(!$uid){ Redirect::guest($request->url()); return Redirect::to(URL::action("Admin\AdminController@loginViews")); } $power = SysAdminPower::where('purl',$actions)->first(); // Log::error("==power=".json_encode($power)); // Log::error("==userinfo=".json_encode($adminUser->getUser())); if(!empty($power)){ if(!empty($adminUser->getUser())){ Cache::put('landingRouting', $request->url(), 1); if(!Str::contains($adminUser->getUser()->position_power.$adminUser->getUser()->department->powerid,"|".$power->id."|")){ Redirect::guest($request->url()); return Redirect::to(URL::action("Admin\AdminController@loginViews")); } }else{ Log::error("权限和用户信息Session获取失败"); Redirect::guest($request->url()); return Redirect::to(URL::action("Admin\AdminController@loginViews")); } } return $next($request); } }<file_sep>/app/Console/Commands/ModelUpdateCommand.php <?php namespace App\Console\Commands; use Carbon\Carbon; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\File; class ModelUpdateCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'model:create {name} {dirname} {db?}'; /** * The console command description. * * @var string */ protected $description = '根据表明生成model'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { // $model = <<<EOF <?php namespace NAMESPACE; use Illuminate\Database\Eloquent\Model; class MODEL_NAME extends Model { DB_CONN protected \$table='TABLE_NAME'; protected \$primaryKey='ID'; public \$timestamps = true; protected \$fillable=[ FIELDS ]; } EOF; $filePath = "./app/Models"; if(!empty($this->argument('dirname'))){ $filePath = "./app/Models/".ucfirst($this->argument("dirname")); } $nameSpace = str_replace("/","\\",ucfirst(substr($filePath,2))); $tableName = $this->argument('name'); $temp = explode('_',$tableName); $modelName = ""; foreach ($temp as $name){ $modelName .=ucfirst($name); } $model = str_replace('MODEL_NAME',"Base".$modelName,$model); $model = str_replace('TABLE_NAME',$tableName,$model); $model = str_replace('NAMESPACE',$nameSpace,$model); try{ if(!empty($this->argument('db'))){ $conn = DB::connection($this->argument('db')); // $cols= $conn->select("SHOW COLUMNS FROM `".$tableName."`"); $cols= $conn->select(" SHOW FULL FIELDS FROM `".$tableName."`"); $model = str_replace('DB_CONN',"protected \$connection='".$this->argument('db')."';",$model); }else{ // $cols= \DB::select("SHOW COLUMNS FROM `".$tableName."`"); $cols= DB::select(" SHOW FULL FIELDS FROM `".$tableName."`"); $model = str_replace('DB_CONN',"",$model); } $fields = ""; foreach ($cols as $col){ if($col->Key == 'PRI'){ $model = str_replace('ID',$col->Field,$model); }else{ $fields .=" '".$col->Field."', // ".$col->Comment."\n"; } } $model = str_replace('FIELDS',$fields,$model); // $this->info(json_encode($this->arguments())); if(!File::isDirectory($filePath)){ File::makeDirectory($filePath); } File::put($filePath."/Base$modelName.php",$model); $this->line($model); $this->info($filePath."/$modelName"." Model Created!!"); }catch (\Exception $e){ $this->error($e->getMessage()); } File::append($filePath."/Base$modelName.php","//Created at ".Carbon::now()->toDateTimeString()); } } <file_sep>/routes/admin.php <?php use Illuminate\Support\Facades\Route; Route::get('/admin', "Admin\AdminController@loginViews", function () { return view('admin/login'); }); Route::get('/login', "Admin\AdminController@loginViews", function () { return view('admin/login'); }); //不用登陆验证的 登陆注册 Route::group(['namespace' => 'Admin','prefix' => 'admin'], function () { Route::get('login', 'AdminController@loginViews'); //后台登陆页面 Route::post('loginc', 'AdminController@login'); //后台登陆逻辑 Route::get('logout', 'AdminController@logout')->name('admin.logout'); //退出 }); //后台管理 Route::group(['prefix' => 'admin','namespace' => 'Admin'], function () { //用户 Route::group(['prefix' => 'user'], function () { Route::get('view', 'UserController@view'); Route::get('list', 'UserController@list'); Route::post('delete', 'UserController@delete'); Route::post('listdata', 'UserController@getListData'); Route::post('save', 'UserController@save'); Route::post('linkage', 'UserController@Linkage'); Route::post("change","UserController@change"); Route::post("update","UserController@updateInfo"); }); //权限 Route::group(['prefix' => 'power'], function () { Route::get('manager','PowerController@manager'); Route::get('view','PowerController@view'); Route::get('updateview','PowerController@updateView'); // Route::get('two-view','PowerController@addTwoMenus'); Route::get('list','PowerController@list'); Route::post('listdata','PowerController@getListData'); Route::post('delete','PowerController@delete'); Route::post('save','PowerController@save'); Route::post('search','PowerController@searchUrl'); }); //部门 Route::group(['prefix' => 'dept'], function () { Route::get('list','DepartmentController@list'); Route::post('update','DepartmentController@update'); Route::post('delete','DepartmentController@delete'); Route::post('save','DepartmentController@save'); Route::get('powertreedata','DepartmentController@powerTreeData'); Route::post('save','DepartmentController@save'); }); //职位 Route::group(['prefix' => 'posi'], function () { Route::get('view','PositionController@view'); Route::post('update','PositionController@update');//职位添加/修改 Route::get('list1','PositionController@list1'); Route::get('list','PositionController@list'); Route::post('listdata','PositionController@getListData'); Route::post('save','PositionController@save'); Route::post('add','PositionController@positionAdd'); }); //管理员资料管理 // Route::group(['prefix' => 'self'], function () { // Route::get('set','UserController@set'); // Route::post('save','UserController@set_save'); // }); // Route::group(['prefix' => 'site'], function () { Route::get('show','SiteController@show'); Route::post('save','SiteController@siteSave'); }); }); //首页管理 Route::group(['middleware'=>'adminAuth','namespace' => 'Admin','prefix' => 'admin'], function (){ Route::any('admin','AdminController@index'); Route::get('index','AdminController@index');//首页 Route::get('main','AdminController@main'); //首页body展示 Route::get('cs','AdminController@leftMenu'); //测试代码 }); //文件上传 Route::group(['prefix'=>'files'],function(){ Route::post('upload','FileInputUploadController@anyUpload'); Route::post('del','FileInputUploadController@delete'); Route::get('download/{id}','FileInputUploadController@download'); });<file_sep>/app/Models/Admin/Base/BaseBaseSite.php <?php namespace App\Models\Admin\Base; use Illuminate\Database\Eloquent\Model; class BaseBaseSite extends Model { protected $table='base_site'; protected $primaryKey='id'; public $timestamps = true; protected $fillable=[ 'site_title', // 网站标题 'site_desc', // 网站描述 'site_keyboard', // 网站关键字 'site_copyright', // 版权 'site_tel', // 电话 'site_email', // 邮箱 'site_address', // 地址 'created_at', // 'updated_at', // ]; }//Created at 2020-03-31 05:58:07<file_sep>/app/Http/Controllers/admin/DepartmentController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Requests\AdminDepartmentRequest; use App\Models\Admin\SysAdminDepartment; use App\Models\Admin\SysAdminPower; use App\Models\Base\BaseSysAdminPower; use App\Services\AdminUser; use App\Tools\Constant; use App\Tools\Result; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Log; class DepartmentController extends Controller { // public $adminUser; function __construct(AdminUser $user) { $this->adminUser = $user; } public function list(){ //部门SysAdminDepatment $department = SysAdminDepartment::where([['parent_id',0],['status',1]])->with(['children'=>function($query){ $query->where('status',1); }])->get(); $top_department = json_encode($department->toArray()); $all = SysAdminDepartment::all()->keyBy('id'); //权限 $power = SysAdminPower::where('parent_id',0)->with('allchild')->get(); return view('admin.department_list',['department'=>$department,'power'=>$power,'all'=>$all,'top_department'=>$top_department]); } public function view(Request $request) { $id=$request->get('id',0); if (empty($request->level)) { $data['level'] = 0; } else { $data['level'] =$request->level; } if (empty($request->parent_id)) { $data['parent_id'] = 0; } else { $data['parent_id'] =$request->parent_id; } if ($id!=0) { $department = SysAdminDepartment::find($id); $department->powerid = explode('|',$department->powerid); } else { $department = new SysAdminDepartment(); if ($request->pid>0) { $data['dp_name'] = SysAdminDepartment::all('id','dp_name'); $department->pid = $request->pid; } } $power_name = BaseSysAdminPower::all('id','pname','parent_id'); $data['power_name'] = $power_name; $data['info'] = $department; $powerid = $department->powerid ? array_filter($department->powerid) : ''; $data['powerid'] = $powerid; $sysAdminPower_model = new SysAdminPower(); $getTree = $sysAdminPower_model->getTree($power_name); $data['department_rule'] = $getTree; return view("admin.department_view",$data); } public function update(Request $request) { $result =new Result(); if ($request->ajax()) { try { $id = Input::get('id'); $department = new SysAdminDepartment(); if (!empty($request->powerid) && empty($id)){ if (empty($request->position_name)){ $result->code=Constant::ERROR; $result->msg="请选择部门"; return response()->json($result); } } if (!empty($id)) { if (!empty($request->dp_name)) { $po_name_arr = $department->where('id','!=',$id)->pluck('dp_name')->toArray(); if (in_array($request->dp_name,$po_name_arr)){ $result->msg="部门名称不能重复"; return response()->json($result); } } else { if (empty($request->powerid)) { $result->code = Constant::ERROR; $result->msg = "请正确操作"; return response()->json($result); } } $dept = SysAdminDepartment::find($request->id); if (!empty($dept)) { $dept->fill($request->all()); $dept->save(); $result->code=Constant::OK; $result->msg="操作成功"; } } else { if (!empty($request->dp_name)) { $po_name_arr = $department->pluck('dp_name')->toArray(); if (in_array($request->dp_name,$po_name_arr)){ $result->msg="部门名称不能重复"; return response()->json($result); } } if (empty($request->dp_name) && empty($request->powerid)){ $result->code=Constant::ERROR; $result->msg="请正确操作"; return response()->json($result); } $dept = new SysAdminDepartment(); $dept->fill($request->all()); $dept->save(); $result->code=Constant::OK; $result->msg="操作成功"; } } catch (\Exception $e) { $result->msg = "操作失败"; } } else { $result->msg = "Invalid Request"; } return response()->json($result); } public function save(AdminDepartmentRequest $request) { Log::error("====================".json_encode(Input::all())); $result =new Result(); if ($request->ajax()) { try { if($request->id>0){ $power = SysAdminDepartment::find($request->id); }else{ $power = new SysAdminDepartment(); } Log::error("====================".json_encode($request->powerid)); $power->fill(Input::all()); $power->powerid='|'; $power->save(); Log::error("=========power===========".json_encode($power)); Log::error("=========level===========".json_encode($request->level)); if ($request->level == 0){ $power->root_id = $power->id; $power->path = "|".$power->id."|"; $power->level = 1; } else { if (empty($request->parent_id)) { $result->msg = "请从左侧选择父级"; $result->code = Constant::ERROR; return response()->json($result); } $parent = SysAdminDepartment::find($request->parent_id); Log::error("=========parent===========".json_encode($parent)); $power->root_id = $parent->root_id; $power->path = $parent->path.$power->id."|"; $power->level = $parent->level+1; } $power->save(); $result->msg = "操作成功"; $result->code = Constant::OK; } catch (\Exception $e) { $result->msg = "操作失败"; } } else { $result->msg = "Invalid Request"; } return response()->json($result); } /** * @param Request $request * @return \Illuminate\Http\JsonResponse * @description */ public function delete(Request $request) { $result =new Result(); if ($request->ajax()) { try { if ($request->id>0) { SysAdminDepartment::find($request->id)->update(['status'=> 0]); } $result->msg = "操作成功"; $result->code = Constant::OK; } catch (\Exception $e) { $result->msg = "操作失败"; } } else { $result->msg = "Invalid Request"; } return response()->json($result); } } <file_sep>/app/Http/Controllers/Backend/EssayController.php <?php namespace App\Http\Controllers\Backend; use App\Http\Controllers\Controller; use App\Models\Backend\Essay; use App\Services\BannerServices; use App\Services\EssayServices; use App\Tools\ApiResult; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Yajra\DataTables\Facades\DataTables; class EssayController extends Controller { // use ApiResult; protected $banner; protected $essay; public function __construct(BannerServices $banner,EssayServices $essay) { $this->banner = $banner; $this->essay = $essay; } /** * @description 首页 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther xiaobin */ public function index() { return view("essay.index"); } /** * @description 详情页 * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View * @auther caoxiaobin */ public function essayDetail() { $result = $this->essay->essayDetail(Input::get("id")); return view("essay.detail", $result->data); } /** * @description 添加文章/图片 * @param Request $request * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function essayAdd(Request $request) { if ($request->ajax()) { return $this->essay->essaySave($request->all()); } return $this->error("操作失败"); } /** * @description * @auther caoxiaobin */ public function easyList() { $input = Input::all(); $id = $input['id'] ?? 1; $list = Essay::where([['id','>',0], ['essay_status','=',1], ['banner_position_id','=',$id]])->with('posi'); $datatable = DataTables::eloquent($list); return $datatable->make(true); } /** * @description 删除信息 * @param Request $request * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function essayDel(Request $request) { if ($request->ajax()) { return $this->essay->essayDel($request->get("id", 0)); } else { return $this->error("操作失败"); } } /** * @description 关于魔数 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther caoxiaobin */ public function aboutMagic() { return view("essay.magic"); } /** * @description 课程体系 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther caoxiaobin */ public function course() { return view("essay.course"); } /** * @description 教学 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther caoxiaobin */ public function research() { return view("essay.Research"); } /** * @description AI学习平台 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther caoxiaobin */ public function learn() { return view("essay.learn"); } /** * @description OMO模式 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther caoxiaobin */ public function omoMode(){ return view("essay.omo_mode"); } /** * @description 全国校区 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther caoxiaobin */ public function all( ) { return view("essay.all"); } /** * @description 加盟授权 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther caoxiaobin */ public function join(){ return view("essay.join"); } /** * @description APP下载 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther caoxiaobin */ public function appDown(){ return view("essay.down"); } } <file_sep>/app/Http/Controllers/admin/PositionController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\AdminPositionRequest; use App\Models\Admin\SysAdminDepartment; use App\Models\Admin\SysAdminPosition; use App\Models\Admin\SysAdminPower; use App\Models\Base\BaseSysAdminDepartment; use App\Models\Base\BaseSysAdminPosition; use App\Services\AdminUser; use App\Tools\ApiResult; use App\Tools\Constant; use App\Tools\Result; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Yajra\DataTables\Facades\DataTables; class PositionController extends Controller { // use ApiResult; public $adminUser; function __construct(AdminUser $user) { $this->adminUser = $user; } public function view(Request $request){ $id=$request->get('id',0); if($id!=0){ $power = BaseSysAdminPosition::find($id); $power->powerid = explode('|',$power->powerid); }else{ $power = new BaseSysAdminPosition(); } $dp_name =BaseSysAdminDepartment::all('id','dp_name'); $power_name = SysAdminPower::all('id','pname','parent_id'); $sysAdminPower_model = new SysAdminPower(); $getTree = $sysAdminPower_model->getTree($power_name); $powerid = $power->powerid ? array_filter($power->powerid) : ''; $data = [ 'info' => $power, 'dp_name' => $dp_name, 'power_name' => $power_name, 'position_rule' => $getTree, 'powerid' => $powerid, ]; return view("admin.position_view",$data); } /** * @description 职位列表 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @auther caoxiaobin */ public function list(){ $position = BaseSysAdminPosition::all()->keyBy('id'); $department = SysAdminDepartment::where('parent_id',0)->with('children')->get(); $all = BaseSysAdminDepartment::all()->keyBy('id'); //权限 $power = SysAdminPower::where('parent_id',0)->with('allchild')->get(); return view('admin.position_list',['position'=>$position,'department'=>$department,'power'=>$power,'all'=>$all]); } public function getListData(){ $list = BaseSysAdminPosition::select('sys_admin_position.*','sys_admin_department.dp_name') ->leftjoin('sys_admin_department','sys_admin_department.id','=','sys_admin_position.department_id')->where('sys_admin_position.id','>',0); $datatable = DataTables::eloquent($list); Log::error("base信息=======".json_encode($datatable)); return $datatable->make(true); } public function powerName($powerid){ $power_names =""; foreach ($powerid as $k=>$v){ $power_name =SysAdminPower::find($v); $power_names .=$power_name->pname.","; } return $power_names; } public function save(AdminPositionRequest $request){ // Log::error("====input===>",json_encode(Input::all())); $result =new Result(); if($request->ajax()) { try { if($request->id>0){ $power = BaseSysAdminPosition::find($request->id); }else{ $power = new BaseSysAdminPosition(); } $power->fill($request->all()); $power->powerid = '|'; $power->save(); $result->msg = "操作成功"; $result->code = Constant::OK; } catch (\Exception $e) { $result->msg = "操作失败"; } }else{ $result->msg = "Invalid Request"; } return response()->json($result); } /** * @description 添加职位 * @param AdminPositionRequest $request * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function update(AdminPositionRequest $request){ $result =new Result(); if($request->ajax()) { if (SysAdminPosition::where("position_name", $request->post("position_name"))->count()>1) { return $this->error("职位名称不允许重复"); } try { $id = $request->get('id',0); if ($id < 1) { $dept = new BaseSysAdminPosition(); } else { $dept = SysAdminPosition::find($id); } $request["powerid"]= "|"; $dept->fill($request->all()); $dept->save(); $result->code=Constant::OK; $result->msg="操作成功"; } catch (\Exception $e) { $result->msg = "操作失败"; Log::info("职位添加失败",[$e->getMessage()]); $result->code=Constant::ERROR; } }else{ $result->code=Constant::ERROR; $result->msg = "Invalid Request"; } return response()->json($result); } /** * @description 职位权限 * @param Request $request * @return \Illuminate\Http\JsonResponse * @auther caoxiaobin */ public function positionAdd(Request $request) { if ($request->ajax()) { $id = $request->post("id", 0); if ($id < 1) { return $this->error("选择职位"); } $powerid = $request->post("powerid",""); if (empty($powerid)) { return $this->error("选择职位"); } $dept = SysAdminPosition::find($id); if (!$dept) { return $this->error("当前职位已删除,刷新页面"); } $dept->powerid = $powerid; if ($dept->save()) { return $this->success("操作成功"); } else { return $this->error("操作失败"); } } else { return $this->error("非法操作"); } } public function delete(Request $request){ $result =new Result(); if($request->ajax()) { try { if($request->id>0){ BaseSysAdminPosition::find($request->id)->update(['status'=>0]); } $result->msg = "操作成功"; $result->code = Constant::OK; } catch (\Exception $e) { $result->msg = "操作失败"; } }else{ $result->msg = "Invalid Request"; } return response()->json($result); } } <file_sep>/app/Services/FrontendServices.php <?php namespace App\Services; use App\Models\Backend\Banner; use App\Models\Backend\Essay; use App\Tools\Constant; use Illuminate\Support\Facades\Cache; class FrontendServices { /** * @description 获取某个导航下的所有banner * @param $id int 导航ID * @return mixed * @auther caoxiaobin */ public function banner($id) { return Cache::remember("banner_list{$id}", Constant::VALID_TIME, function () use($id) { $param = [ ['is_show', '=', 1], ['bposition', '=', $id], ]; return Banner::select("bposition", "bname", "imgurl", "target_link")->where($param)->get(); }); } /** * @description 获取某个导航下面的相关信息 * @param $id int 导航ID * @return mixed * @auther caoxiaobin */ public function essay($id) { return Cache::remember("essay_list{$id}", Constant::VALID_TIME, function () use($id) { $param = [ ['essay_status', '=', 1], ['banner_position_id', '=', $id] ]; return Essay::where($param)->get(); }); } }
f7e9625649ceceb58737c698ab6c77ae6ac3a49e
[ "Markdown", "PHP" ]
83
PHP
ty536804/laravel_admin
c12768049c1d730b41eaf28015f3127508c3b68b
c029341f7a8240a38e10b5af39d8a0f0ebcc1826
refs/heads/master
<repo_name>sagodi97/idg-files-updater<file_sep>/README.md # idg-files-updater Update XSLT, XML and GatewayScript (JS) files to a Datapower Gateway easily. ## Features - Straightforward CLI - Watch entire folders and update (upload files) on file save <file_sep>/messagesBuilder.js module.exports = { setFile: ({ base64File: base64File, dpFilePath: dpFilePath }) => { return `<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Body> <dp:request xmlns:dp="http://www.datapower.com/schemas/management"> <dp:set-file name="${dpFilePath}"> ${base64File} </dp:set-file> </dp:request> </soapenv:Body> </soapenv:Envelope>`; }, flushStylesheetsCache: () => { return `<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"> <env:Body> <dp:request domain="OAB_MEDIATION_BASIC_DEV" xmlns:dp="http://www.datapower.com/schemas/management"> <dp:do-action> <FlushStylesheetCache> <XMLManager>default</XMLManager> </FlushStylesheetCache> </dp:do-action> </dp:request> </env:Body> </env:Envelope>`; } }; <file_sep>/app.js /* * * * * IDGFilesUpdater by <NAME> * * * * */ const commander = require("commander"); const fs = require("fs"); const soma = require("./soma"); const chokidar = require("chokidar"); const ppath = require("path"); commander .option("-H, --host <host ip>", "set host") .option("-p, --port [port]", "specify a port", 5550) .option("-A, --auth <username:password>", "set the basic authentication") .option("-e, --endpoint [endpoint]", "set endpoint other than default (/service/mgmt/current)") .option( "-D, --dpg-location [datapower path]", "specify location of directory to upload files in datapower (default is local:///)", "local:///" ) .parse(process.argv); //Host validators const hostRegex = RegExp("^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]).)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9])$"); const ipRegex = RegExp("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"); const host = commander.host; const port = commander.port; const endpoint = commander.endpoint ? commander.endpoint : "/service/mgmt/current"; const auth = commander.auth; const dpgLocation = commander.dpgLocation; if (!host || (!hostRegex.test(host) || !ipRegex.test(host))) { console.log("Please specify a valid host (use -H)"); process.exit(1); } else if (!auth) { console.log("Please provide valid credentials (use -A)"); process.exit(1); } const options = { hostname: host, port: port, path: endpoint, method: "POST", rejectUnauthorized: false, headers: { "Content-Type": "application/xml", Authorization: `Basic ${Buffer.from(auth).toString("base64")}` }, timeout: 3000 }; watcher = chokidar.watch("mediation/", ["**/*.js", "**/*.xsl", "**/*.xml"], { persistent: true, ignoreInitial: true }); watcher .on("add", path => { console.log(`Add event on ${path}`); try { file = fs.readFileSync(path, { encoding: "utf8" }); } catch (error) { console.error("Problem occured opening the file:\n\n" + error); return; } soma.upload(options, file, dpgLocation + ppath.basename(path)); }) .on("change", path => { console.log(`Change event on ${path}`); try { file = fs.readFileSync(path, { encoding: "utf8" }); } catch (error) { console.error("Problem occured opening the file:\n\n" + error); return; } console.log("=========FILE READ========="); soma.upload(options, file, dpgLocation + ppath.basename(path)); soma.flushCache(options); }) .on("unlink", path => { console.log(`File ${path} has been removed`); }); <file_sep>/soma.js const https = require("https"); const msgBuilder = require("./messagesBuilder"); module.exports = { //UPLOADS NEW AND UPDATE upload: (options, file, dpFilePath) => { const req = https.request(options, res => { if (res.statusCode != 200) { res.on("data", d => { process.stdout.write(d); }); } else if (res.statusCode === 200) { console.log(`Succesfully set file: ${dpFilePath}`); } }); req.on("error", error => { console.error(error); }); req.on("timeout", () => { req.abort(); console.error(`Request to ${options.hostname} timed out after ${options.timeout / 1000} seconds`); }); req.write(msgBuilder.setFile({ base64File: Buffer.from(file).toString("base64"), dpFilePath: dpFilePath })); req.end(); }, flushCache: options => { const req = https.request(options, res => { if (res.statusCode != 200) { res.on("data", d => { process.stdout.write(d); }); } else if (res.statusCode === 200) { console.log(`Stylesheet cache flushed`); } }); req.on("error", error => { console.error(error); }); req.on("timeout", () => { req.abort(); console.error(`Request to ${options.hostname} timed out after ${options.timeout / 1000} seconds`); }); req.write(msgBuilder.flushStylesheetsCache()); req.end(); } };
865a9d0c07078da4fcb860eb1f5e350ceb337748
[ "Markdown", "JavaScript" ]
4
Markdown
sagodi97/idg-files-updater
8e4068ef6e69902297e3499e9aa4e6dd29a3a96d
7ee3058f73dd62c45214eb87cdd8866ac3dd8f4e
refs/heads/master
<repo_name>allman007/allman-project<file_sep>/config.js module.exports = { mongoURI:'mongodb+srv://allman:allman@cluster0-sddze.mongodb.net/allmanProject?retryWrites=true&w=majority' // mongoURI:'mongodb://localhost/project' }
80262e14f72ca80a72f35ee592a4428e32a0c27b
[ "JavaScript" ]
1
JavaScript
allman007/allman-project
33ca22dd51f92ed0c72d97d577fc5f63f526b89a
966800e84309072654885dea9049c494dcbad317
refs/heads/master
<file_sep>package pages; import com.codeborne.selenide.SelenideElement; import data.DataGenerator; import org.openqa.selenium.Keys; import static com.codeborne.selenide.Condition.text; import static com.codeborne.selenide.Selenide.$; public class MoneyTransferPage { private SelenideElement amountField = $("[type=text]"); private SelenideElement fromCardField = $("[type=tel]"); private SelenideElement Button = $("[data-test-id=action-transfer]"); public void transferMoney(int amount, String id){ amountField.doubleClick().sendKeys(Keys.BACK_SPACE); amountField.doubleClick().sendKeys(Keys.BACK_SPACE); amountField.setValue(Integer.toString(amount)); fromCardField.setValue(id); Button.click(); } public void lookForMessage(){ $("[denied_message]").shouldHave(text("Недостаточно средств!")); } } <file_sep>package pages; import com.codeborne.selenide.ElementsCollection; import com.codeborne.selenide.SelenideElement; import static com.codeborne.selenide.Condition.text; import static com.codeborne.selenide.Selenide.$; import static com.codeborne.selenide.Selenide.$$; public class DashboardPage { private ElementsCollection cards = $$(".list__item"); public DashboardPage() { } public int extractCardBalance(String text) { String [] words = text.split(" "); int balance = Integer.parseInt(words[5]); return balance; } public int getCardBalance(String id) { String [] characters = id.split(""); String lastFourNumbers = "**** **** **** 000"+characters[15];; String text = $$("[data-test-id]").find(text(lastFourNumbers)).text(); return extractCardBalance(text); } public MoneyTransferPage chooseACardToAddAmountTo(String id) { String [] characters = id.split(""); String lastFourNumbers = "**** **** **** 000"+characters[15]; SelenideElement card = $$("[data-test-id]").find(text(lastFourNumbers)); card.$("[class=button__text]").click(); return new MoneyTransferPage(); } public MoneyTransferPage moneyTransfer(DashboardPage dashboardPage, String id){ MoneyTransferPage moneyTransferPage = dashboardPage.chooseACardToAddAmountTo(id); return moneyTransferPage; } public void checkRightEnter(){ $("[data-test-id=dashboard]").shouldHave(text("Личный кабинет".trim())); } } <file_sep>[![Build status](https://ci.appveyor.com/api/projects/status/jtvr5ymlop38k90c/branch/master?svg=true)](https://ci.appveyor.com/project/YurtaevaSofia/netology-aqa-6-1/branch/master)
2c5541ba19d6a4fa7b12397c14adbe7d6f96868d
[ "Markdown", "Java" ]
3
Java
YurtaevaSofia/Netology_AQA_6.1
cfb9124fb2cf4b52e13c2c27d107b282c5da609b
3ac3514d3b45be492eb713aa7f3b821fe0ea7f7e
refs/heads/master
<file_sep>using ECommerce.Models; using ECommerce.Models.ApplicationDBContext; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Security.Cryptography; using System.Text; using AutoMapper; namespace ECommerce.Controllers { public class UserController : ApiController { private readonly ApplicationDBContext _applicationDBContext; public UserController() { _applicationDBContext = new ApplicationDBContext(); } [Route("api/User/Create")] [HttpPost] public void RegisterUser([FromBody]User user) { if (user != null) { user.Password = <PASSWORD>(user.Password); _applicationDBContext.Users.Add(user); _applicationDBContext.SaveChanges(); } } [Route("api/User/Login")] [HttpPost] public User Login([FromBody]User user) { if (user != null) { if (_applicationDBContext.Users.Count(u => u.EmailId == user.EmailId && u.Password == <PASSWORD>(user.Password)) > 0) { return user; } } return null; } [Route("api/User/Update")] [HttpPut] public User Update([FromBody]User user, int id) { User dbUser = _applicationDBContext.Users.SingleOrDefault(u => u.User_Id == id); if(dbUser != null) { Mapper.Map<User, User>(user, dbUser); _applicationDBContext.SaveChanges(); } return dbUser; } [Route("api/User/Delete")] [HttpDelete] public void DeleteUser(int id) { User user = _applicationDBContext.Users.SingleOrDefault(u => u.User_Id == id); if (user != null) { _applicationDBContext.Users.Remove(user); _applicationDBContext.SaveChanges(); } } [NonAction] public string CreateHash(string inputPassword) { return Convert.ToBase64String(SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(inputPassword))); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace ECommerce.Models { public class Product { [Key] [Required(AllowEmptyStrings = false, ErrorMessage = "Product Id is Required")] public int Product_id { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "Product Name is Required")] public string Product_Name { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "Product Price is Required")] public decimal Price { get; set; } public decimal Offer { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "Product Manufacturing Date is Required")] public DateTime Mfg_date { get; set; } public DateTime Expiry_date { get; set; } public int Best_before_months { get; set; } public int Product_category_id { get; set; } public ProductCategory ProductCategory { get; set; } } }<file_sep>using AutoMapper; using ECommerce.Models; using ECommerce.Models.ApplicationDBContext; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace ECommerce.Controllers { public class ProductController : ApiController { private readonly ApplicationDBContext _applicationDBContext; public ProductController() { _applicationDBContext = new ApplicationDBContext(); } // GET api/values [Route("api/Products")] [HttpGet] public IEnumerable<Product> Products() { IEnumerable<Product> products = _applicationDBContext.Products; return products; } [Route("api/Product/{id:int}")] [HttpGet] // GET api/values/5 public Product Product(int id) { Product product = _applicationDBContext.Products.SingleOrDefault(p => p.Product_id == id); return product; } [Route("api/Product/Create")] [HttpPost] // POST api/values public void CreateProduct([FromBody]Product product) { if(product != null) { _applicationDBContext.Products.Add(product); _applicationDBContext.SaveChanges(); } } [HttpPut] [Route("api/Product/Update/{id:int}")] // PUT api/values/5 public void UpdateProduct(int id, [FromBody]Product product) { Product dbproduct = _applicationDBContext.Products.SingleOrDefault(p => p.Product_id == id); Mapper.Map<Product, Product>(product, dbproduct); _applicationDBContext.SaveChanges(); } [Route("api/Product/delete/{id:int}")] [HttpDelete] // DELETE api/values/5 public void DeleteProduct(int id) { Product dbproduct = _applicationDBContext.Products.SingleOrDefault(p => p.Product_id == id); _applicationDBContext.Products.Remove(dbproduct); } [HttpGet] [Route("api/Product/Categories")] public IEnumerable<ProductCategory> GetCategories() { return _applicationDBContext.ProductCategories; } } }
85ae8f1264d5a54256170ac844451abfeaee0414
[ "C#" ]
3
C#
DeveshSapkale/ECommerceAPI
976e0037ec4c6e80ecbf298450afdd57bb47fd7d
60188b5980c480c3eed1efb4fe66c5e72ff99a65
refs/heads/main
<file_sep><?php session_start(); if(!isset($_SESSION['user_id'])) { $msg = "Je moet eerst inloggen!"; header("Location: ../login.php?msg=$msg"); } $username = $_POST['username']; $password = $_POST['<PASSWORD>']; //Query om de gegevens van het account op te halen (/ te controleren of de username correct is) require_once 'conn.php'; $query = "SELECT * FROM users WHERE username = :username"; $statement = $conn->prepare($query); $statement->execute([ ":username" => $username ]); $user = $statement->fetch(PDO::FETCH_ASSOC); //Er wordt gekeken of de query resultaat oplevert if($statement->rowCount() < 1){ die("Error: acccount bestaat niet."); } //Controleren of het wachtwoord correct is if(!password_verify($password, $user['password'])) { die("Error: Wachtwoord is onjuist."); } //Gebruiker opslaan d.m.v. de user_id van te gebruiker op te slaan in de sessie $_SESSION['user_id'] = $user['id']; header("Location: ../index.php"); ?><file_sep><!-- TODO (BIJ HET GEBRUIKEN VAN DIT REGISTER FORMULIER OP ANDERE COMPUTER): - Zet in de database na username een kolom email, dan kan er namelijk een email insert worden. --> <?php $username = $_POST['username']; $email = $_POST['email']; $password = $_POST['password']; $password_check = $_POST['password_check']; if(isset($_SESSION['user_id'])){ die("Kan niet registeren - je bent al ingelogd!"); } //filter_var() bekijkt of de email bestaat - https://www.php.net/manual/en/filter.filters.validate.php if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){ die("Email is ongeldig!"); } if($password != $password_check){ die("Wachtwoorden zijn niet gelijk aan elkaar!"); } require_once 'conn.php'; //eenmalig, omdat de volgende query dit ook herkent $sql = "SELECT * FROM users WHERE username = :email"; $statement = $conn->prepare($sql); $statement->execute([ ":email" => $email ]); $user = $statement->fetch(PDO::FETCH_ASSOC); if($statement->rowCount() > 0){ die("Error: Bepaalde gegevens zijn al in gebruik!"); } if(empty($password)){ die("Wachtwoord mag niet leeg zijn"); } $hash = password_hash($password, PASSWORD_DEFAULT); $query = "INSERT INTO users(username, email, password) VALUES(:username, :email, :hash)"; $statement = $conn->prepare($query); $statement->execute([ ":username" => $username, ":email" => $email, ":hash" => $hash ]); //Stuur naar login: header("Location: $base_url/login.php"); exit; ?><file_sep><?php //Session starten ophalen user_id of gebruiker herkennen session_start(); //Kijken of er iemand is ingelogd --> zo niet wordt degene terug gestuurd login.php (pagina's beveiligen) if(isset($_SESSION['user_id'])) { $msg = "Je bent al ingelogd!"; header("Location: index.php?msg=$msg"); exit; } ?> <!doctype html> <html lang="nl"> <head> <title>StoringApp</title> <?php require_once 'head.php'; ?> </head> <body> <?php require_once 'header.php'; ?> <div class="container"> <!-- Melding Login Pagina --> <?php if(isset($_GET['msg'])) { echo "<div class='msg'>" . $_GET['msg'] . "</div>"; } ?> <form action="backend/loginController.php" method="POST"> <div class="form-group"> <label for="username">Username:</label> <input type="text" name="username"> </div> <div class="form-group"> <label for="<PASSWORD>">Password:</label> <input type="<PASSWORD>" name="<PASSWORD>"> </div> <input type="submit" value="Inloggen"> </form> </div> </body> </html> <file_sep><?php //Session starten ophalen user_id of gebruiker herkennen session_start(); //Kijken of er iemand is ingelogd --> zo niet wordt degene terug gestuurd login.php (pagina's beveiligen) if(isset($_SESSION['user_id'])) { $msg = "Je bent al ingelogd!"; header("Location: index.php?msg=$msg"); exit; } ?> <!doctype html> <html lang="nl"> <head> <title>StoringApp</title> <?php require_once 'head.php'; ?> </head> <body> <?php require_once 'header.php'; ?> <div class="container"> <form action="backend/registerController.php" method="POST"> <div class="form-group"> <label for="username">Username:</label> <input type="text" name="username"> </div> <div class="form-group"> <label for="email">Email:</label> <input type="email" name="email"> </div> <div class="form-group"> <label for="password">Password:</label> <input type="<PASSWORD>" name="<PASSWORD>"> </div> <div class="form-group"> <label for="password">Password Check:</label> <input type="password" name="<PASSWORD>_check"> </div> <input type="submit" value="Registreren"> </form> </div> </body> </html><file_sep><?php //Session starten ophalen user_id of gebruiker herkennen session_start(); //Kijken of er iemand is ingelogd --> zo niet wordt degene terug gestuurd login.php (pagina's beveiligen) if(!isset($_SESSION['user_id'])) { $msg = "Je moet eerst inloggen!"; header("Location: ../login.php?msg=$msg"); exit; } ?> <!doctype html> <html lang="nl"> <head> <title>StoringApp / Meldingen</title> <?php require_once '../head.php'; ?> </head> <body> <?php require_once '../header.php'; ?> <div class="container"> <h1>Meldingen</h1> <a href="create.php">Nieuwe melding &gt;</a> <?php if(isset($_GET['msg'])) { echo "<div class='msg'>" . $_GET['msg'] . "</div>"; } ?> <?php require_once '../backend/conn.php'; if(empty($_GET['type'])) { $query = "SELECT * FROM meldingen"; $stmt = $conn->prepare($query); $stmt->execute(); } else { $query = "SELECT * FROM meldingen WHERE type = :type"; $stmt = $conn->prepare($query); $stmt->execute([ ":type" => $_GET['type'] ]); } $meldingen = $stmt->fetchAll(PDO::FETCH_ASSOC); ?> <!-- Aantal meldingen + Filter --> <div class="flex"> <p>Aantal meldingen: <strong><?php echo count($meldingen); ?></strong></p> <!-- Bonusopdracht - inline php gebruiken!! 1. Waarbij je eerst met een if-statement kijkt of de type is gekozen/ingesteld - if(isset($_GET['type'])): 2. Daarna met $_GET het type ophaald en dan de geselecteerde optie laat zien d.m.v. de echo 3. Als laatste komt een else-statement waar je kijkt als je niks hebt gekozen in de dropdown door alleen de select en option met values te gebruiken. Link: - https://www.php.net/manual/en/language.basic-syntax.phpmode.php --> <?php if(isset($_GET['type'])): ?> <form action="" action="GET"> <select name="type"> <option value="">- kies een type - </option> <option value="achtbaan" <?php if($_GET['type'] == 'achtbaan') echo 'selected="selected"';?>>Achtbaan</option> <option value="draaiend" <?php if($_GET['type'] == 'draaiend') echo 'selected="selected"';?>>Draaiend</option> <option value="kinder" <?php if($_GET['type'] == 'kinder') echo 'selected="selected"';?>>Kinder</option> <option value="horeca" <?php if($_GET['type'] == 'horeca') echo 'selected="selected"';?>>Horeca</option> <option value="show" <?php if($_GET['type'] == 'show') echo 'selected="selected"';?>>Show</option> <option value="water" <?php if($_GET['type'] == 'water') echo 'selected="selected"';?>>Water</option> <option value="overig" <?php if($_GET['type'] == 'overig') echo 'selected="selected"';?>>Overig</option> </select> <input type="submit" value="filter"> </form> <?php else: ?> <form action="" action="GET"> <select name="type"> <option value="">- kies een type - </option> <option value="achtbaan">Achtbaan</option> <option value="draaiend">Draaiend</option> <option value="kinder">Kinder</option> <option value="horeca">Horeca</option> <option value="show">Show</option> <option value="water">Water</option> <option value="overig">Overig</option> </select> <input type="submit" value="filter"> </form> <?php endif; ?> </div> <table> <tr> <th>Attractie</th> <th>Type</th> <th>Melder</th> <th>Overige info</th> <th>Aanpassen</th> <!-- <th>Prioriteit</th> <th>Capaciteit</th> <th>Gemeld op</th> --> </tr> <?php foreach($meldingen as $melding): ?> <tr> <td><?php echo $melding['attractie'] ?></td> <td><?php echo ucfirst($melding['type']) ?></td> <!-- Opdracht 6 - 2. --> <td><?php echo $melding['melder'] ?></td> <td><?php echo $melding['overige_info'] ?></td> <td><?php echo "<a href='edit.php?id={$melding['id']}'>"; ?>aanpassen</a></td> <!-- <td> <?php if($melding['prioriteit'] == True){ echo "Ja"; } else{ echo "Nee"; } ?> </td> <td><?php echo $melding['capaciteit'] ?></td> <td><?php echo $melding['gemeld_op'] ?></td> --> </tr> <?php endforeach; ?> </table> </div> </body> </html>
3684b3cb470698530c571913626d7b51643ef914
[ "PHP" ]
5
PHP
BoazWelsenis/storingapp
55fd556c5aa1e48911b480b84f8d6ff4049de1c8
0db1a7eed08064a6647dd8d0555296342b3f68ae
refs/heads/master
<file_sep>#!/bin/sh ROOT=/home/$USER/Pictures CONFIG=/home/$USER/.config FEHBG=/home/$USER/.fehbg #List subdirectories and get subdirectory SUBDIR=$(ls -l $ROOT | awk {'print $1" "$9'} | grep d | awk {'print $2'} | dmenu) WALLPAPER=$(sxiv -to $ROOT/$SUBDIR) ln -sf $WALLPAPER $CONFIG/wallpaper exec $FEHBG
969c6f351bd8543cc1f5c69607fd64eb50f69bee
[ "Shell" ]
1
Shell
BigBucksx/Wallpaper-for-dwm
1c915e3f79c786ad770704dd0507c2c06ca40f69
314782286d20bc2e99ca54632eb20e06ead07afd
refs/heads/master
<repo_name>ling-yl/money_app<file_sep>/app/src/main/java/com/example/myapplication/set_activity.kt package com.example.myapplication import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.FirebaseDatabase import kotlinx.android.synthetic.main.activity_set_activity.* import kotlinx.android.synthetic.main.activity_set_goods_money.* import kotlinx.android.synthetic.main.activity_set_goods_money.submit import java.util.* class set_activity : AppCompatActivity() { var uid=FirebaseAuth.getInstance().currentUser?.uid override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_set_activity) //設定活動資訊 submit.setOnClickListener { val aname = ac_name.text.toString() val alocation = ac_location.text.toString() val adatetime = ac_datetime.text.toString() val aintroduction = ac_introduction.text.toString() val abonus = ac_bonus.text.toString() //隨機產生字串 /*val str = "abcdefghigklmnopkrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789" val random = Random() var sf = StringBuffer() for (i in 0..5) { var number = random.nextInt(62) //0~61 sf.append(str[number]) }*/ val userid = uid.toString(); val rannum = (Math.random() * 99).toInt() //val activityid = sf.toString() + userid + rannum //活動id if (aname.isEmpty() || alocation.isEmpty() || adatetime.isEmpty() || aintroduction.isEmpty() || abonus.isEmpty()) { Toast.makeText(this, "有格子未填寫", Toast.LENGTH_SHORT).show() } else { val uid = FirebaseAuth.getInstance().uid ?: "" //val ref = FirebaseDatabase.getInstance().getReference("/activity/$activityid") val activityid = FirebaseDatabase.getInstance().getReference("/activity").push().key val activity = Activity( activityid, aname, alocation, adatetime, abonus.toInt(), aintroduction, uid.toString() ).toMap() FirebaseDatabase.getInstance().getReference("/activity//${activityid}").setValue(activity) Toast.makeText(applicationContext, "新增成功", Toast.LENGTH_SHORT).show() /*ref.updateChildren(activity).addOnSuccessListener { Log.d("setactivity", "real time database access success") //var key = FirebaseDatabase.getInstance().getReference("/record").push().key //FirebaseDatabase.getInstance().getReference("/record/${key}").setValue(activity) // Write a message to the database //val database = FirebaseDatabase.getInstance() //取得Firebase連結 //val myRef = database.getReference("activity") //Firebase入面邊個目錄 //myRef.child(userid).setValue(activity) //FirebaseDatabase.getInstance().reference.child("activity").setValue(activity) *//*myRef.child(userid).setValue(activity).addOnSuccessListener { Log.d("add activity","real time database access success") }*//* //FirebaseDatabase.getInstance().getReference("/record").setValue(activity) Toast.makeText(applicationContext, "新增成功", Toast.LENGTH_SHORT).show() } */ //在user資料表也加入活動id user/activity/活動id //val myref = FirebaseDatabase.getInstance().getReference("/user/$uid/activity/${activityid}") //val shop=Activity("shop").toMap() FirebaseDatabase.getInstance().getReference("/user/$uid/activity/${activityid}").setValue("shop") /*myref.updateChildren(shop).addOnSuccessListener{ Log.d("setuseractivity", "real time database access success") }*/ val intent = Intent(this@set_activity,activity_list::class.java) intent.flags= Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(intent) } } } } <file_sep>/app/src/main/java/com/example/myapplication/Activity2.java package com.example.myapplication; import java.util.Map; import java.util.HashMap; public class Activity2 extends Activity{ public String get_bonus; public String shop_id; public String user_id; public Activity2(String get_bonus){ this.get_bonus=get_bonus; } public Activity2(){ } public Map<String, Object> toMap() { HashMap<String, Object> result = new HashMap<>(); result.put("get_bonus",get_bonus); result.put("shop_id",shop_id); return result; } public String get_Bonus() { return get_bonus; } public String user_id() { return user_id; } public String shop_id() { return shop_id; } } <file_sep>/app/src/main/java/com/example/myapplication/activity_info.kt package com.example.myapplication import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import com.google.zxing.integration.android.IntentIntegrator import kotlinx.android.synthetic.main.activity_info.* class activity_info : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_info) var uid=FirebaseAuth.getInstance().currentUser?.uid val user = FirebaseAuth.getInstance().currentUser!!.uid var snap = false //val myref = FirebaseDatabase.getInstance().getReference("/user_join") val alert = AlertDialog.Builder(this) val get_aid:String = intent.getStringExtra("aid") val get_name:String = intent.getStringExtra("name") val get_introduction:String = intent.getStringExtra("introduction") val get_datetime:String = intent.getStringExtra("datetime") val get_location:String = intent.getStringExtra("location") val get_bonus:String = intent.getStringExtra("bonus") val get_shop_id:String = intent.getStringExtra("shop_id") activity_name.setText(get_name) activity_introduction.setText(get_introduction) activity_date.setText(get_datetime) activity_address.setText(get_location) val ref = FirebaseDatabase.getInstance().getReference("/user/$uid") ref.addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val snap = dataSnapshot.getValue(User::class.java) if (snap?.isuser.toString()=="false" ) { //如果是商家 val btn:Button= findViewById(R.id.activity_attend) btn.text="發送參與獎勵" activity_bonus.setText("獎勵金額:"+get_bonus) //給活動獎勵 btn.setOnClickListener{ FirebaseDatabase.getInstance().getReference("/activity/${get_aid}").addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val data2 = dataSnapshot.getValue(Activity::class.java) if(data2!!.bonus.toInt()>snap!!.cash.toInt()){ //如果餘額不足 Toast.makeText(applicationContext, "餘額不足!", Toast.LENGTH_SHORT).show() } else{ val intent = Intent(this@activity_info,show_QR_code::class.java) intent.putExtra("uid",snap?.uid) intent.putExtra("is_user", snap?.isuser) intent.putExtra("user_name", snap?.username) startActivity(intent) } } override fun onCancelled(databaseError: DatabaseError) {} }) } //回活動列表 go_back.setOnClickListener{ val intent = Intent(this@activity_info,activity_list::class.java) intent.flags=Intent.FLAG_ACTIVITY_CLEAR_TOP startActivity(intent) } } else{ //如果是使用者 //目的:檢查有沒有報名 val check_join = FirebaseDatabase.getInstance().getReference("/user/$uid/activity") check_join.addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val csnap = dataSnapshot.child(get_aid).exists() if(!csnap) //如果沒報名 { val myref = FirebaseDatabase.getInstance().getReference("/user_join/$uid") //按下報名之後 activity_attend.setOnClickListener{ alert.setTitle("活動報名") alert.setMessage("確定要報名活動?") alert.setPositiveButton("確定") { dialog, which -> val key = FirebaseDatabase.getInstance().getReference("/user_join").push().key val activity_join=Activity(get_aid,uid,get_bonus).toMap() val record_id=Activity(key.toString()).toMap() //新增至參與紀錄 FirebaseDatabase.getInstance().getReference("/user_join/${key}").setValue(activity_join) FirebaseDatabase.getInstance().getReference("/user_join/${key}/get_bonus").setValue("no") //新增至使用者內的參與紀錄 FirebaseDatabase.getInstance().getReference("/user/${uid}/activity/$get_aid").setValue(record_id) activity_bonus.setText("領取活動獎勵") //顯示領取活動獎勵 activity_attend.setText("取 消 報 名") val intent = Intent(this@activity_info,activity_info::class.java) intent.flags=Intent.FLAG_ACTIVITY_CLEAR_TOP intent.putExtra("aid",get_aid) intent.putExtra("name",get_name) intent.putExtra("introduction",get_introduction) intent.putExtra("datetime",get_datetime) intent.putExtra("location",get_location) intent.putExtra("bonus",get_bonus) intent.putExtra("shop_id",get_shop_id) startActivity(intent) Toast.makeText(applicationContext, "報名成功", Toast.LENGTH_SHORT).show() } alert.show() } } else{ //如果有報名 //目的:確認有沒有領過獎勵 val check_bonus = FirebaseDatabase.getInstance().getReference("/user/$uid/activity/$get_aid") //取得紀錄id check_bonus.addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val bsnap = dataSnapshot.getValue(Activity::class.java) val check_get_bonus = FirebaseDatabase.getInstance().getReference("/user_join/${bsnap?.record_id}") check_get_bonus.addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val gbsnap = dataSnapshot.getValue(Activity2::class.java) if(gbsnap?.get_bonus=="yes") //已經領過獎勵 { activity_attend.setText("已 完 成 報 到") activity_bonus.setText("獎勵已領取!") } else{ //未領取獎勵 activity_bonus.setText("領取活動獎勵") //顯示領取活動獎勵 activity_attend.setText("取 消 報 名") //按下領取活動獎勵之後 val activity_bonus : TextView = findViewById(R.id.activity_bonus) activity_bonus.setOnClickListener{ open_scanner() } val jref = FirebaseDatabase.getInstance().getReference("/user/$uid/activity/$get_aid") jref.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val jsnap = dataSnapshot.getValue(Activity::class.java) //按下取消報名之後 activity_attend.setOnClickListener{ alert.setTitle("取消活動報名") alert.setMessage("確定要取消報名活動?") alert.setPositiveButton("確定") { dialog, which -> //移除使用者的參與紀錄 FirebaseDatabase.getInstance().getReference("/user/$uid/activity/$get_aid").removeValue() //移除參與記錄的資料 FirebaseDatabase.getInstance().getReference("/user_join/${jsnap?.record_id}").removeValue() activity_bonus.setText("") //顯示領取活動獎勵 activity_attend.setText("報 名") val intent = Intent(this@activity_info,activity_info::class.java) intent.flags=Intent.FLAG_ACTIVITY_CLEAR_TOP intent.putExtra("aid",get_aid) intent.putExtra("name",get_name) intent.putExtra("introduction",get_introduction) intent.putExtra("datetime",get_datetime) intent.putExtra("location",get_location) intent.putExtra("bonus",get_bonus) intent.putExtra("shop_id",get_shop_id) startActivity(intent) Toast.makeText(applicationContext, "取消報名成功", Toast.LENGTH_SHORT).show() } alert.show() } } override fun onCancelled(databaseError: DatabaseError) {} }) } } override fun onCancelled(databaseError: DatabaseError) {} }) } override fun onCancelled(databaseError: DatabaseError) {} }) } } override fun onCancelled(databaseError: DatabaseError) {} }) //回活動列表 go_back.setOnClickListener{ val intent = Intent(this@activity_info,participate::class.java) //intent.flags=Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(intent) } } } override fun onCancelled(databaseError: DatabaseError) {} }) } //目的:領取參與獎勵 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?){ super.onActivityResult(requestCode, resultCode, data) var uid=FirebaseAuth.getInstance().currentUser?.uid val get_shop_id:String = intent.getStringExtra("shop_id") val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data) if (result.contents == null || result== null ) {return} val data=result.contents.split(";") if (data[0]=="false"){ //QRCODE的第一格欄位是商家 代表要領取參與獎勵 val ref = FirebaseDatabase.getInstance().getReference("/user/${data[2]}") //取userid以下的資料 ref.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val snap = dataSnapshot.getValue(User::class.java) val get_aid:String = intent.getStringExtra("aid") val aref = FirebaseDatabase.getInstance().getReference("/activity/$get_aid") //取活動id以下的資料 aref.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val asnap = dataSnapshot.getValue(Activity::class.java) val get_name:String = intent.getStringExtra("name") val jref = FirebaseDatabase.getInstance().getReference("/user/$uid/activity/$get_aid") //取得參與紀錄id jref.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val jsnap = dataSnapshot.getValue(Activity::class.java) val gref = FirebaseDatabase.getInstance().getReference("/user_join/${jsnap?.record_id}") //取得user_join/record_id gref.addListenerForSingleValueEvent(object : ValueEventListener{ override fun onDataChange(dataSnapshot: DataSnapshot) { val gsnap = dataSnapshot.getValue(Activity2::class.java) val alert = AlertDialog.Builder(this@activity_info) if(gsnap?.get_bonus.toString()=="yes"){ //代表領過獎勵 /*alert.setMessage("已經領過獎勵了!") alert.setPositiveButton("確定") { dialog, which -> } alert.show()*/ } else{ //還沒領過獎勵 alert.setMessage("是否要領取「"+get_name+"」的參與獎勵:${asnap?.bonus}元?") alert.setPositiveButton("確定") { dialog, which -> val wsref = FirebaseDatabase.getInstance().getReference("/user/${gsnap?.uid}") //目的:取得使用者的cash wsref.addListenerForSingleValueEvent(object : ValueEventListener{ override fun onDataChange(dataSnapshot: DataSnapshot) { val wsnap = dataSnapshot.getValue(User::class.java) FirebaseDatabase.getInstance().getReference("/user_join/${jsnap?.record_id}").child("get_bonus").setValue("yes") //在get_bonus設yes,代表已領過獎勵 val new_cash:Int=wsnap!!.cash.toInt().plus(asnap!!.bonus.toInt()) //取得使用者新的餘額 FirebaseDatabase.getInstance().getReference("/user/${gsnap?.uid}").child("cash").setValue(new_cash) } override fun onCancelled(databaseError: DatabaseError) {} }) val sref = FirebaseDatabase.getInstance().getReference("/user/${get_shop_id}") //取得廠商的資料 sref.addListenerForSingleValueEvent(object : ValueEventListener{ override fun onDataChange(dataSnapshot: DataSnapshot) { val ssnap = dataSnapshot.getValue(User::class.java) val new_shop_cash:Int=ssnap!!.cash.toInt().minus(asnap!!.bonus.toInt()) //取得商家新的餘額 FirebaseDatabase.getInstance().getReference("/user/${get_shop_id}").child("cash").setValue(new_shop_cash) //在廠商的user/user_id/下新增pay_bonus_user_join_record/${jsnap?.record_id}:"pay_bonus" FirebaseDatabase.getInstance().getReference("/user/${get_shop_id}/activity/pay_bonus_record/${jsnap?.record_id}").setValue("pay_bonus") activity_attend.setText("已 完 成 報 到") Toast.makeText(applicationContext, "成功領取獎勵!", Toast.LENGTH_SHORT).show() } override fun onCancelled(databaseError: DatabaseError) {} }) } alert.show() } } override fun onCancelled(databaseError: DatabaseError) {} }) } override fun onCancelled(databaseError: DatabaseError) {} }) } override fun onCancelled(databaseError: DatabaseError) {} }) } override fun onCancelled(databaseError: DatabaseError) {} }) } } fun open_scanner(){ val integrator= IntentIntegrator(this) integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE) integrator.setPrompt("Scan a barcode") integrator.setCameraId(0) // 前鏡頭 integrator.setBeepEnabled(false) // 拍照聲音 integrator.setBarcodeImageEnabled(true) integrator.setOrientationLocked(false) // 部翻轉 integrator.initiateScan() } } <file_sep>/app/src/main/java/com/example/myapplication/buy_record.kt package com.example.myapplication import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.ArrayAdapter import android.widget.ListView import android.widget.Toast import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import java.util.* class buy_record : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_buy_record) val user = FirebaseAuth.getInstance().currentUser val uid = user?.uid var array = ArrayList<String>() FirebaseDatabase.getInstance().getReference("/user/${uid}/record").addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { dataSnapshot.children.forEach { Log.d("text","${it.key}") val type=it.value FirebaseDatabase.getInstance().getReference("/record/${it.key}").addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { Log.d("data","${dataSnapshot}") val data = dataSnapshot.getValue(record::class.java) Log.d("data","${data}") if (type=="get") { if(data?.states=="cash") { Log.d("data1","${data?.money}") array.add("從「${data?.payname}」獲得${data?.money}元紅包") } else{ Log.d("data2","${data?.money}") array.add("販賣「${data?.good_name}」給「${data?.payname}」,獲得${data?.money}元") } } else { if(data?.states=="cash") { Log.d("data3","${data?.money}") array.add("付給「${data?.getname}」${data?.money}元紅包") } else{ Log.d("data4","${data?.money}") array.add("購買「${data?.good_name}」,付給「${data?.getname}」${data?.money}元") } } val adapter = ArrayAdapter(this@buy_record,R.layout.list_item, array) val listView:ListView = findViewById(R.id.list) listView.setAdapter(adapter) } override fun onCancelled(databaseError: DatabaseError) {} }) } } override fun onCancelled(databaseError: DatabaseError) {} }) //取得活動交易紀錄 //目的:找出會員領參與獎金的紀錄 FirebaseDatabase.getInstance().getReference("/user/${uid}/activity").addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { dataSnapshot.children.forEach { Log.d("text","${it.key}") val type=it.value if(type!=="shop"){ //如果是使用者 //取得活動id FirebaseDatabase.getInstance().getReference("/activity/${it.key}").addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { Log.d("text","${it.key}") Log.d("data","${dataSnapshot}") val data = dataSnapshot.getValue(Activity::class.java) Log.d("data","${data}") //取得record_id FirebaseDatabase.getInstance().getReference("/user/${uid}/activity/${data?.aid}").addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { Log.d("data","${dataSnapshot}") val data2 = dataSnapshot.getValue(Activity::class.java) Log.d("data","${data}") //去user_join FirebaseDatabase.getInstance().getReference("/user_join/${data2?.record_id}").addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { Log.d("data","${dataSnapshot}") val data3 = dataSnapshot.getValue(Activity2::class.java) Log.d("data","${data}") //如果有領取獎勵了 if(data3?.get_bonus=="yes"){ Log.d("data1","${data?.name}") array.add("參加「${data?.name}」獲得${data?.bonus}元參與獎勵") } val adapter = ArrayAdapter(this@buy_record,R.layout.list_item, array) val listView:ListView = findViewById(R.id.list) listView.setAdapter(adapter) } override fun onCancelled(databaseError: DatabaseError) {} }) } override fun onCancelled(databaseError: DatabaseError) {} }) } override fun onCancelled(databaseError: DatabaseError) {} }) } /*if(type=="shop"){ //如果是商家 }*/ } } override fun onCancelled(databaseError: DatabaseError) {} }) //取得活動交易紀錄 //目的:找出廠商發送獎金的紀錄 FirebaseDatabase.getInstance().getReference("/user/${uid}").addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val data = dataSnapshot.getValue(User::class.java) if(data?.isuser=="false"){ //如果是商家 FirebaseDatabase.getInstance().getReference("/user/${uid}/activity/pay_bonus_record").addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { dataSnapshot.children.forEach { Log.d("text","${it.key}") val type=it.value //去user_join取得aid與uid FirebaseDatabase.getInstance().getReference("/user_join/${it.key}").addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val data2 = dataSnapshot.getValue(Activity2::class.java) val data3 = dataSnapshot.getValue(Activity::class.java) if(data2?.get_bonus=="yes"){ //如果會員已領取獎勵 //去activity取得bonus FirebaseDatabase.getInstance().getReference("/activity/${data3?.aid}").addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val data4 = dataSnapshot.getValue(Activity::class.java) Log.d("data","${data4?.record_id}") array.add("支付給「${data?.username}」參與「${data4?.name}」的獎勵${data4?.bonus}元") } override fun onCancelled(databaseError: DatabaseError) {} }) } val adapter = ArrayAdapter(this@buy_record,R.layout.list_item, array) val listView:ListView = findViewById(R.id.list) listView.setAdapter(adapter) } override fun onCancelled(databaseError: DatabaseError) {} }) } } override fun onCancelled(databaseError: DatabaseError) {} }) } } override fun onCancelled(databaseError: DatabaseError) {} }) } } <file_sep>/app/src/main/java/com/example/myapplication/first_choose.kt package com.example.myapplication import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_first_choose.* class first_choose : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_first_choose) choose_user.setOnClickListener { val intent = Intent(this,register::class.java) startActivity(intent) } choose_shop.setOnClickListener { val intent = Intent(this,register::class.java) intent.putExtra("shop","shop") startActivity(intent) } } } <file_sep>/app/src/main/java/com/example/myapplication/activity_list.kt package com.example.myapplication import android.content.Intent import android.os.Bundle import android.util.Log import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.ListView import androidx.appcompat.app.AppCompatActivity import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import kotlinx.android.synthetic.main.activity_info.* import kotlinx.android.synthetic.main.activity_list.* import kotlinx.android.synthetic.main.content_activity_list.* import java.util.* class activity_list : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_list) setSupportActionBar(toolbar) fab.setOnClickListener{ val intent = Intent(this@activity_list,set_activity::class.java) intent.flags= Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(intent) } val user = FirebaseAuth.getInstance().currentUser val uid = user?.uid var array = ArrayList<String>() val shop_id=uid var array_aid= ArrayList<String>() var array_name= ArrayList<String>() var array_introduction= ArrayList<String>() var array_datetime= ArrayList<String>() var array_location= ArrayList<String>() var array_bonus= ArrayList<String>() var array_shop_id= ArrayList<String>() //取得user/activity FirebaseDatabase.getInstance().getReference("/user/${uid}/activity").addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { dataSnapshot.children.forEach{ Log.d("text","${it.key}") //it.key.toString()>activity id val type=it.value //type.toString()>shop FirebaseDatabase.getInstance().getReference("/activity/${it.key}").addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { var value = dataSnapshot.getValue(Activity::class.java) array.add("${value?.name}") array_aid.add("${value?.aid}") array_name.add("${value?.name}") array_introduction.add("${value?.introduction}") array_datetime.add("${value?.datetime}") array_location.add("${value?.location}") array_bonus.add("${value?.bonus}") array_shop_id.add("${value?.uid}") val adapter = ArrayAdapter(this@activity_list,R.layout.list_item, array) val listView:ListView = findViewById(R.id.list) listView.setAdapter(adapter) list.setOnItemClickListener{ adapterView: AdapterView<*>, view1: View, i: Int, l: Long -> val intent = Intent(this@activity_list,activity_info::class.java) intent.flags=Intent.FLAG_ACTIVITY_CLEAR_TOP intent.putExtra("aid","${array_aid[i]}") intent.putExtra("name","${array_name[i]}") intent.putExtra("introduction","${array_introduction[i]}") intent.putExtra("datetime","${array_datetime[i]}") intent.putExtra("location","${array_location[i]}") intent.putExtra("bonus","${array_bonus[i]}") intent.putExtra("shop_id","${array_shop_id[i]}") startActivity(intent) } } override fun onCancelled(databaseError: DatabaseError) {} }) } } override fun onCancelled(databaseError: DatabaseError) {} }) } } <file_sep>/app/src/main/java/com/example/myapplication/set_activity.java /* package com.example.myapplication; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class set_activity extends AppCompatActivity { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_set_activity); Button submit=(Button)findViewById(R.id.submit); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { performAdd(); } }); } public void performAdd(){ EditText ac_name=(EditText)findViewById(R.id.ac_name); EditText ac_location=(EditText)findViewById(R.id.ac_location); EditText ac_datetime=(EditText)findViewById(R.id.ac_datetime); EditText ac_introduction=(EditText)findViewById(R.id.ac_introduction); EditText ac_bonus=(EditText)findViewById(R.id.ac_bonus); String name=ac_name.getText().toString(); String location=ac_location.getText().toString(); String datetime=ac_datetime.getText().toString(); String introduction=ac_introduction.getText().toString(); String bonus=ac_bonus.getText().toString(); String usera=user.getUid().toString(); //取得userid FirebaseDatabase db = FirebaseDatabase.getInstance(); //取得Firebase連結 DatabaseReference ContactsRef = db.getReference("activity"); activity get_ac=new activity(name,location,datetime,introduction,bonus,usera); ac_bonus.setText(get_ac.toString()); //ContactsRef.child("1").setValue(get_ac); } } */ <file_sep>/app/src/main/java/com/example/myapplication/main_page.kt package com.example.myapplication import androidx.appcompat.app.AppCompatActivity import java.util.* import java.text.* import android.content.Intent import android.os.Bundle import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.* import com.google.zxing.integration.android.IntentIntegrator import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.activity_main_page.* import android.widget.Toast import androidx.appcompat.app.AlertDialog class main_page : AppCompatActivity() { var time = Calendar.getInstance() var format = SimpleDateFormat ("yyyy-MM-dd hh:mm:ss") var now_time = format.format(time.time) var give_cash=0 var uid=FirebaseAuth.getInstance().currentUser?.uid var have_cash=0 var current_user_name="" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main_page) if(uid==null)//如果未登入 就回主選單 { val intent= Intent(this,first_choose::class.java) intent.flags=Intent.FLAG_ACTIVITY_NEW_TASK.or(Intent.FLAG_ACTIVITY_CLEAR_TASK) startActivity(intent) }//登入狀態判斷是商家還是會員 else{ val ref = FirebaseDatabase.getInstance().getReference("/user/$uid") ref.addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val snap = dataSnapshot.getValue(User::class.java) Picasso.get().load(snap?.profileImgUri).into(user_picture) if (snap?.isuser.toString()=="false"&& snap?.give_cash==null ) // 如果是商家而且沒有設定過價格 { val intent = Intent(this@main_page,set_goods_money::class.java) intent.flags=Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(intent) } else if (snap?.isuser.toString()=="false"){ // 如果是商家 顯示內容會有更改 give_cash=snap!!.give_cash have_cash= snap!!.cash current_user_name=snap!!.username set_shop(snap!!) } else if(snap?.isuser.toString()=="true"&& snap?.give_cash==null){ // 如果是使用者而且沒有設定過紅包價格 val intent = Intent(this@main_page,user_set_redcash::class.java) intent.flags=Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(intent) } else{ have_cash=snap!!.cash current_user_name=snap!!.username set_user(snap!!) } } override fun onCancelled(databaseError: DatabaseError) {} }) } //活動列表 user_participate.setOnClickListener{ val intent = Intent(this,participate::class.java) startActivity(intent) } //紀錄 user_record.setOnClickListener { val intent = Intent(this,buy_record::class.java) startActivity(intent) } //登出 user_logout.setOnClickListener { val alert = AlertDialog.Builder(this) alert.setMessage("是否登出?") alert.setPositiveButton("是") { dialog, which -> FirebaseAuth.getInstance().signOut() val intent = Intent(this,first_choose::class.java) intent.flags=Intent.FLAG_ACTIVITY_NEW_TASK.or(Intent.FLAG_ACTIVITY_CLEAR_TASK) startActivity(intent) Toast.makeText(applicationContext, "成功登出", Toast.LENGTH_SHORT).show() } alert.show() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data) if (result.contents == null || result== null ) {return} val alert = AlertDialog.Builder(this) alert.setTitle("交易訊息") alert.setNegativeButton("取消"){dialog,which -> Toast.makeText(applicationContext,"取消交易",Toast.LENGTH_SHORT).show() } val data=result.contents.split(";") if (data[0]=="true")//QRCODE的第一格欄位是使用者 代表要送紅包 { if (have_cash<give_cash) { alert.setMessage("您的錢不夠哦") alert.setPositiveButton("確定") { dialog, which -> Toast.makeText(applicationContext, "請先充值", Toast.LENGTH_SHORT).show() } alert.show() } else { val ref = FirebaseDatabase.getInstance().getReference("/user/${data[2]}") ref.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val snap = dataSnapshot.getValue(User::class.java) alert.setMessage("是否要送給「${data[1]}」${give_cash}元的紅包?") alert.setPositiveButton("YES") { dialog, which -> val key = FirebaseDatabase.getInstance().getReference("/record").push().key val cash =snap!!.cash.toInt() FirebaseDatabase.getInstance().getReference("/user/${uid}").child("cash").setValue(have_cash-give_cash) FirebaseDatabase.getInstance().getReference("/user/${data[2]}").child("cash").setValue(cash+give_cash) val record=record(data[2],data[1],uid,current_user_name,"cash",give_cash,now_time) FirebaseDatabase.getInstance().getReference("/record/${key}").setValue(record) FirebaseDatabase.getInstance().getReference("/user/${uid}/record/${key}").setValue("pay") FirebaseDatabase.getInstance().getReference("/user/${data[2]}/record/${key}").setValue("get") Toast.makeText(applicationContext, "交易完成", Toast.LENGTH_SHORT).show() } alert.show() } override fun onCancelled(databaseError: DatabaseError) {} }) } } else//QRCODE的第一格欄位是商家 代表要購買物品 { val ref = FirebaseDatabase.getInstance().getReference("/user/${data[2]}") ref.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val snap = dataSnapshot.getValue(User::class.java) if (have_cash<snap!!.goods_cash) { alert.setMessage("您的錢不夠哦") alert.setPositiveButton("確定") { dialog, which -> Toast.makeText(applicationContext, "請先充值", Toast.LENGTH_SHORT).show() } alert.show() } else { alert.setMessage("是否要跟${snap.username}購買「${snap.goods_name}」花費${snap.goods_cash}?") alert.setPositiveButton("YES") { dialog, which -> val key = FirebaseDatabase.getInstance().getReference("/record").push().key val cash = snap.cash.toInt() FirebaseDatabase.getInstance().getReference("/user/${uid}").child("cash").setValue(have_cash- snap.goods_cash) FirebaseDatabase.getInstance().getReference("/user/${data[2]}").child("cash").setValue(cash+ snap.goods_cash) val record=record(data[2],snap.username,uid,current_user_name,"goods", snap.goods_cash,now_time,snap.goods_name) FirebaseDatabase.getInstance().getReference("/record/${key}").setValue(record) FirebaseDatabase.getInstance().getReference("/user/${uid}/record/${key}").setValue("pay") FirebaseDatabase.getInstance().getReference("/user/${data[2]}/record/${key}").setValue("get") Toast.makeText(applicationContext, "交易完成", Toast.LENGTH_SHORT).show() } alert.show() } } override fun onCancelled(databaseError: DatabaseError) {} }) } } fun open_scanner(){ val integrator= IntentIntegrator(this) integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE) integrator.setPrompt("Scan a barcode") integrator.setCameraId(0) // 前鏡頭 integrator.setBeepEnabled(false) // 拍照聲音 integrator.setBarcodeImageEnabled(true) integrator.setOrientationLocked(false) // 部翻轉 integrator.initiateScan() } fun set_shop(snap:User){ user_name.text = "商家名稱 : "+snap?.username.toString() user_cash.text = "商家餘額 : "+snap?.cash.toString() user_redcash.text = "送 紅 包" user_goods.text = "販 售 商 品" user_participate.text="活 動 列 表" user_redcash.setOnClickListener { open_scanner() } user_goods.setOnClickListener { val intent = Intent(this@main_page,show_QR_code::class.java) intent.putExtra("uid",snap.uid) intent.putExtra("is_user", snap.isuser) intent.putExtra("user_name", snap.username) startActivity(intent) } user_participate.setOnClickListener{ val intent = Intent(this@main_page,activity_list::class.java) //intent.flags=Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(intent) } } fun set_user(snap: User){ user_name.text = "用戶名稱 : "+snap?.username.toString() user_cash.text = "用戶餘額 : "+snap?.cash.toString() user_redcash.setOnClickListener { /*val intent = Intent(this@main_page,show_QR_code::class.java) intent.putExtra("uid",snap.uid) intent.putExtra("is_user", snap.isuser) intent.putExtra("user_name", snap.username) startActivity(intent)*/ val intent = Intent(this@main_page,redcash::class.java) intent.putExtra("uid",snap.uid) intent.putExtra("user_name", snap.username) startActivity(intent) } user_goods.setOnClickListener { open_scanner() } } } <file_sep>/app/src/main/java/com/example/myapplication/participate.kt package com.example.myapplication import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.ListView import android.widget.TextView import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import kotlinx.android.synthetic.main.activity_participate.* import kotlinx.android.synthetic.main.content_activity_list.* import java.util.ArrayList class participate : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_participate) val user = FirebaseAuth.getInstance().currentUser val uid = user?.uid var array = ArrayList<String>() var array_aid= ArrayList<String>() var array_name= ArrayList<String>() var array_introduction= ArrayList<String>() var array_datetime= ArrayList<String>() var array_location= ArrayList<String>() var array_bonus= ArrayList<String>() var array_shop_id= ArrayList<String>() //取得activity FirebaseDatabase.getInstance().getReference("/activity").addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { dataSnapshot.children.forEach{ Log.d("text","${it.key}") //it.key.toString()>activity id val type=it.value //type.toString()>shop FirebaseDatabase.getInstance().getReference("/activity/${it.key}").addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { var value = dataSnapshot.getValue(Activity::class.java) array.add("${value?.name}") array_aid.add("${value?.aid}") array_name.add("${value?.name}") array_introduction.add("${value?.introduction}") array_datetime.add("${value?.datetime}") array_location.add("${value?.location}") array_bonus.add("${value?.bonus}") array_shop_id.add("${value?.uid}") val adapter = ArrayAdapter(this@participate,R.layout.list_item, array) val listView: ListView = findViewById(R.id.list) listView.setAdapter(adapter) val list: ListView =findViewById(R.id.list) list.setOnItemClickListener{ adapterView: AdapterView<*>, view1: View, i: Int, l: Long -> val intent = Intent(this@participate,activity_info::class.java) intent.flags=Intent.FLAG_ACTIVITY_CLEAR_TASK intent.putExtra("aid","${array_aid[i]}") intent.putExtra("name","${array_name[i]}") intent.putExtra("introduction","${array_introduction[i]}") intent.putExtra("datetime","${array_datetime[i]}") intent.putExtra("location","${array_location[i]}") intent.putExtra("bonus","${array_bonus[i]}") intent.putExtra("shop_id","${array_shop_id[i]}") startActivity(intent) } } override fun onCancelled(databaseError: DatabaseError) {} }) } } override fun onCancelled(databaseError: DatabaseError) {} }) } } <file_sep>/app/src/main/java/com/example/myapplication/set_goods_money.kt package com.example.myapplication import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Toast import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.activity_main_page.* import kotlinx.android.synthetic.main.activity_set_goods_money.* class set_goods_money : AppCompatActivity() { var uid=FirebaseAuth.getInstance().currentUser?.uid override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_set_goods_money) //設定商品價格 submit.setOnClickListener { val pay_cash=pay_cash.text.toString() val goods_name = goods_name.text.toString() val goods_cash = goods_cash.text.toString() if(pay_cash.isEmpty() || goods_name.isEmpty() || goods_cash.isEmpty()) { Toast.makeText(this,"有格子未填寫", Toast.LENGTH_SHORT).show() } else{ val uid = FirebaseAuth.getInstance().uid?:"" val ref = FirebaseDatabase.getInstance().getReference("/user/$uid") val user = User(pay_cash.toInt(),goods_name,goods_cash.toInt()).toMap() ref.updateChildren(user).addOnSuccessListener { Log.d("setmoney","real time database access success") } val intent = Intent(this,main_page::class.java) intent.flags= Intent.FLAG_ACTIVITY_NEW_TASK.or(Intent.FLAG_ACTIVITY_CLEAR_TASK) startActivity(intent) } } } } <file_sep>/app/src/main/java/com/example/myapplication/show_QR_code.kt package com.example.myapplication import android.graphics.Bitmap import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.google.zxing.BarcodeFormat import com.google.zxing.qrcode.QRCodeWriter import kotlinx.android.synthetic.main.activity_show__qr_code.* class show_QR_code : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_show__qr_code) val is_user = intent.getStringExtra("is_user") val uid = intent.getStringExtra("uid") val user_name = intent.getStringExtra("user_name") leave.setOnClickListener { finish() } val qrcode = QRCodeWriter() val code = qrcode.encode("${is_user};${user_name};${uid}",BarcodeFormat.QR_CODE,250,250) val width = code.width val height = code.height val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565) for (x in 0 until width) { for (y in 0 until height) { bitmap.setPixel(x, y, if ( code.get(x, y)) Color.BLACK else Color.WHITE) } } show_QR_code.setImageBitmap(bitmap) } }<file_sep>/README.md # 樂幣交易系統 ## 功能 ### 客戶端 - 登入/註冊:如使用者尚未建立帳號即點選註冊按鈕進行註冊的動作,若使用者已擁有帳號即可直接輸入帳號密碼來進行登入的動作。 - 會員頁面:使用者登入後的第一個畫面,提供使用者紅包餘額與用戶名稱等相關資訊。 - 收/送紅包:進入此頁面之後使用者可選擇是要進行收紅包還是送紅包的動作。 - 購買商品:使用者可使用樂幣兌換商品。 - 參加活動:使用者可透過活動列表來選擇想要參加的活動並報名。 - 查詢紀錄:使用者可觀看自己所擁有的樂幣的交易紀錄。 ### 廠商端 - 登入/註冊:如廠商尚未建立帳號即點選註冊按鈕進行註冊的動作,若廠商已擁有帳號即可直接輸入帳號密碼來進行登入的動作。 - 廠商頁面:廠商登入後的第一個畫面,提供使廠商紅包餘額與用戶名稱等相關資訊。 - 送紅包:提供廠商贈與使用者樂幣的功能。 - 販售商品:廠商可在此頁面查看與新增要販售給使用者的商品。 - 活動列表:廠商可在此新增活動給使用者參加。 - 查詢紀錄:廠商可經由此頁面查看自己所擁有的樂幣的交易紀錄。 <file_sep>/app/src/main/java/com/example/myapplication/redcash.kt package com.example.myapplication import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AlertDialog import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import com.google.zxing.integration.android.IntentIntegrator import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.activity_main_page.* import kotlinx.android.synthetic.main.activity_main_page.user_redcash import kotlinx.android.synthetic.main.activity_redcash.* import java.text.SimpleDateFormat import java.util.* class redcash : AppCompatActivity() { var time = Calendar.getInstance() var format = SimpleDateFormat ("yyyy-MM-dd hh:mm:ss") var now_time = format.format(time.time) var give_cash=0 var uid= FirebaseAuth.getInstance().currentUser?.uid var have_cash=0 var current_user_name="" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_redcash) val ref = FirebaseDatabase.getInstance().getReference("/user/$uid") ref.addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val snap = dataSnapshot.getValue(User::class.java) //收紅包(從廠商/從會員) user_redcash.setOnClickListener{ val intent = Intent(this@redcash,show_QR_code::class.java) intent.putExtra("uid",snap?.uid) intent.putExtra("is_user", snap?.isuser) intent.putExtra("user_name", snap?.username) startActivity(intent) } //送紅包 user_send_redcash.setOnClickListener{ open_scanner() } } override fun onCancelled(databaseError: DatabaseError) {} }) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data) if (result.contents == null || result== null ) {return} val data=result.contents.split(";") val alert = AlertDialog.Builder(this@redcash) val ref = FirebaseDatabase.getInstance().getReference("/user/$uid") ref.addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val snap1 = dataSnapshot.getValue(User::class.java) if (data[0]=="true")//QRCODE的第一格欄位是使用者 代表要送紅包 { //val alert = AlertDialog.Builder(this@redcash) if(snap1!!.cash.toInt()<snap1!!.give_cash.toInt()){ alert.setMessage("您的錢不夠哦") alert.setPositiveButton("確定") { dialog, which -> Toast.makeText(applicationContext, "送紅包失敗", Toast.LENGTH_SHORT).show() } alert.show() } else { val ref = FirebaseDatabase.getInstance().getReference("/user/${data[2]}") ref.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val snap = dataSnapshot.getValue(User::class.java) alert.setMessage("是否要送給「${snap?.username}」${snap?.give_cash}元的紅包?") alert.setPositiveButton("YES") { dialog, which -> val key = FirebaseDatabase.getInstance().getReference("/record").push().key val cash =snap!!.cash.toInt() FirebaseDatabase.getInstance().getReference("/user/${uid}/cash").setValue(snap1?.cash.toInt()-snap?.give_cash.toInt()) //送的人 FirebaseDatabase.getInstance().getReference("/user/${data[2]}/cash").setValue(snap!!.cash.toInt()+snap!!.give_cash.toInt()) val record=record(data[2],data[1],uid,snap1?.username,"cash",snap?.give_cash.toInt(),now_time) FirebaseDatabase.getInstance().getReference("/record/${key}").setValue(record) FirebaseDatabase.getInstance().getReference("/user/${uid}/record/${key}").setValue("pay") FirebaseDatabase.getInstance().getReference("/user/${data[2]}/record/${key}").setValue("get") Toast.makeText(applicationContext, "交易完成", Toast.LENGTH_SHORT).show() val intent = Intent(this@redcash,main_page::class.java) startActivity(intent) } alert.show() } override fun onCancelled(databaseError: DatabaseError) {} }) } } else{ } } override fun onCancelled(databaseError: DatabaseError) {} }) //會員送給另一個會員紅包 /* else//QRCODE的第一格欄位是商家 代表要購買物品 { val ref = FirebaseDatabase.getInstance().getReference("/user/${data[2]}") ref.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val snap = dataSnapshot.getValue(User::class.java) if (have_cash<snap!!.goods_cash) { alert.setMessage("您的錢不夠哦") alert.setPositiveButton("確定") { dialog, which -> Toast.makeText(applicationContext, "請先充值", Toast.LENGTH_SHORT).show() } alert.show() } else { alert.setMessage("是否要跟${snap.username}購買「${snap.goods_name}」花費${snap.goods_cash}?") alert.setPositiveButton("YES") { dialog, which -> val key = FirebaseDatabase.getInstance().getReference("/record").push().key val cash = snap.cash.toInt() FirebaseDatabase.getInstance().getReference("/user/${uid}").child("cash").setValue(have_cash- snap.goods_cash) FirebaseDatabase.getInstance().getReference("/user/${data[2]}").child("cash").setValue(cash+ snap.goods_cash) val record=record(data[2],snap.username,uid,current_user_name,"goods", snap.goods_cash,now_time,snap.goods_name) FirebaseDatabase.getInstance().getReference("/record/${key}").setValue(record) FirebaseDatabase.getInstance().getReference("/user/${uid}/record/${key}").setValue("pay") FirebaseDatabase.getInstance().getReference("/user/${data[2]}/record/${key}").setValue("get") Toast.makeText(applicationContext, "交易完成", Toast.LENGTH_SHORT).show() } alert.show() } } override fun onCancelled(databaseError: DatabaseError) {} }) }*/ } fun open_scanner(){ val integrator= IntentIntegrator(this) integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE) integrator.setPrompt("Scan a barcode") integrator.setCameraId(0) // 前鏡頭 integrator.setBeepEnabled(false) // 拍照聲音 integrator.setBarcodeImageEnabled(true) integrator.setOrientationLocked(false) // 部翻轉 integrator.initiateScan() } }
92188ba0a849e076ed153e9c5b609614fbd11b6f
[ "Markdown", "Java", "Kotlin" ]
13
Kotlin
ling-yl/money_app
1556c0b78900fabe748f3a3d739fedb7ac057445
c80d2a8e39206019948db2e6f80b9db11d03ba95
refs/heads/master
<repo_name>neonux1987/endless<file_sep>/src/main/java/com/ndts/endless/Dao/MongoDB/Converters/RoleReadConverter.java package com.ndts.endless.Dao.MongoDB.Converters; import org.bson.Document; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.ReadingConverter; import com.ndts.endless.Entities.Roles.Admin; import com.ndts.endless.Entities.Roles.User; import com.ndts.endless.Entities.Roles.Parents.Role; /** * Converts the data of role from database to the proper role object * since can not instantiate from Role because it's abstract * @author <NAME> * */ @ReadingConverter public class RoleReadConverter implements Converter<Document,Role> { @Override public Role convert(Document doc) { Role role = null; String roleName = (String) doc.get("role"); if(roleName.equalsIgnoreCase("Admin")){ role = new Admin(); } if(roleName.equalsIgnoreCase("User")){ role = new User(); } return role; } } <file_sep>/src/main/java/com/ndts/endless/Entities/Roles/Parents/Role.java package com.ndts.endless.Entities.Roles.Parents; import com.ndts.endless.Enums.RoleType; import com.ndts.endless.Jackson.Converters.RoleJsonDeserializer; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; /** * role parent * @author <NAME> * */ @JsonDeserialize(using = RoleJsonDeserializer.class) public abstract class Role { private String role; public Role() { } public Role(RoleType role) { this.role = role.getLabel(); } public String getRole() { return role; } public void setRole(RoleType role) { this.role = role.getLabel(); } @Override public String toString() { return "Role [role=" + role + "]"; } } <file_sep>/src/main/java/com/ndts/endless/RestApi/CustomErrorController.java package com.ndts.endless.RestApi; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.ServletWebRequest; import com.ndts.endless.Entities.ErrorResponse; @RestController public class CustomErrorController implements ErrorController{ @Autowired private ErrorAttributes errorAttributes; private static final String PATH = "/error"; /** * Handle error response * @param request * @param response * @return error response as json */ @RequestMapping(value = PATH) public ErrorResponse error(HttpServletRequest request, HttpServletResponse response) { //errors Map<String,Object> errors = getErrorAttributes(request,true); //prepare the error object ErrorResponse er = new ErrorResponse(); er.setCode((int) errors.get("status")); er.addMessage((String) errors.get("message")); er.setPath((String) errors.get("path")); //System.out.println(request.getAttribute(RequestDispatcher.ERROR_EXCEPTION.toString())); return er; } @Override public String getErrorPath() { return PATH; } /** * Extract errors from the request * @param request the request to extract the errors from * @param includeStackTrace if to include the stack trace * @return map of errors */ private Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) { ServletWebRequest servletWebRequest = new ServletWebRequest(request); return errorAttributes.getErrorAttributes(servletWebRequest, includeStackTrace); } } <file_sep>/src/main/java/com/ndts/endless/Dao/MongoDB/CounterService.java package com.ndts.endless.Dao.MongoDB; import java.util.Iterator; import java.util.Set; import javax.annotation.PostConstruct; import org.reflections.Reflections; import org.reflections.scanners.TypeAnnotationsScanner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.FindAndModifyOptions; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Service; import com.ndts.endless.Annotations.CounterName; import com.ndts.endless.Dao.MongoDB.Collections.Counter; import com.ndts.endless.Exceptions.DaoException; /** * Counter service responsible for creating id's for collections * and for auto scanning Collections package to creae counters in mongo db * for each collection * @author <NAME> * */ @Service public class CounterService { //Class vars @Autowired private MongoOperations mongo; /************************************************************************** * start the counters creation * @throws DaoException * @throws InstantiationException * @throws IllegalAccessException *************************************************************************/ @PostConstruct public void init() throws DaoException, InstantiationException, IllegalAccessException { createCounters(); } /************************************************************************** * creates counter for all collections in the Collections package * @throws InstantiationException * @throws IllegalAccessException * @throws DaoException *************************************************************************/ private void createCounters() throws InstantiationException, IllegalAccessException, DaoException { //scan collections package not including sub packages and create a set collection of the classes Reflections reflections = new Reflections("com.ndts.endless.Dao.MongoDB.Collections", new TypeAnnotationsScanner()); Set<Class<? extends Object>> allClasses = reflections.getTypesAnnotatedWith(CounterName.class,true); //create counter for each entity/collection class scanned in the package for(Iterator<Class<? extends Object>> it=allClasses.iterator();it.hasNext();) { Class<? extends Object> ele = it.next(); createCounter(ele.newInstance().getClass()); } } /************************************************************************** * create a counter document in a counters collection for a specific entity/collection class * @param clazz the class of the entity/collection to create the counter for * @throws DaoException if the entity/collection was not annotated with * @CounterName(name='YourCollectionName') or passed empty string to field name *************************************************************************/ public void createCounter(Class<?> clazz) throws DaoException { //get the annotation counterName and it's name in order to //know what counter document id name to create if the @counterName //annotation is not present in the entity/collection class or the //passed name is emptyit will throw exception String counterName = null; try { counterName = clazz.getDeclaredAnnotation(CounterName.class).name(); if(counterName.isEmpty()) { throw new DaoException("You can not pass empty string to field name in @CounterName(name='') annotation"); } }catch(NullPointerException e) { throw new DaoException("You didn't annotate your "+ clazz.getName() +" class with @CounterName(name='YourCollectionName') annotation"); } Query query = new Query(Criteria.where("_id").is(counterName)); //query if(mongo.findOne(query, Counter.class)==null) { mongo.save(new Counter(counterName,0), "counters"); } } /************************************************************************** * get the next counter sequence * @param collectionName the collection name to get the counter of * @return counter sequence *************************************************************************/ public long getNextSequence(String collectionName) { Counter counter = mongo.findAndModify( new Query(Criteria.where("_id").is(collectionName)), //query new Update().inc("seq", 1), //update new FindAndModifyOptions().returnNew(true), //options Counter.class); //class return counter.getSeq(); } } <file_sep>/src/main/java/com/ndts/endless/Dao/MongoDB/Rules/AbstractUserNotificationDao.java package com.ndts.endless.Dao.MongoDB.Rules; import com.ndts.endless.Dao.MongoDB.Collections.UserNotification; import com.ndts.endless.Exceptions.DaoException; public interface AbstractUserNotificationDao { /************************************************************************** * creates a user notification * @param userNotification the user notification to create * @return user notification * @throws DaoException if failed to create the notification *************************************************************************/ public UserNotification createUserNotification(UserNotification userNotification) throws DaoException; } <file_sep>/src/main/java/com/ndts/endless/Enums/RoleType.java package com.ndts.endless.Enums; /** * constants of roles * @author <NAME> * */ public enum RoleType { ADMIN, USER; /** * create a representation string of the enum * @return the representation String of the enum */ public String getLabel(){ String name = name(); String firstLetter = name.substring(0, 1); name = firstLetter + name.substring(1).toLowerCase(); return name; } } <file_sep>/src/main/java/com/ndts/endless/Jackson/Converters/RoleJsonDeserializer.java package com.ndts.endless.Jackson.Converters; import java.io.IOException; import com.ndts.endless.Entities.Roles.Admin; import com.ndts.endless.Entities.Roles.User; import com.ndts.endless.Entities.Roles.Parents.Role; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; /** * Converts the data from json of role to the proper role object * since can not instantiate from Role because it's abstract * @author <NAME> * */ public class RoleJsonDeserializer extends JsonDeserializer<Role> { @Override public Role deserialize(JsonParser jsonParser, DeserializationContext ctx) throws IOException, JsonProcessingException { Role role = null; JsonNode node = jsonParser.readValueAsTree(); String roleTitle = node.get("role").asText(); if(roleTitle.equalsIgnoreCase("Admin")){ role = new Admin(); } if(roleTitle.equalsIgnoreCase("User")){ role = new User(); } return role; } } <file_sep>/src/main/java/com/ndts/endless/Exceptions/EmailSenderRuntimeException.java package com.ndts.endless.Exceptions; public class EmailSenderRuntimeException extends RuntimeException { /** * */ private static final long serialVersionUID = 1L; public EmailSenderRuntimeException(String message) { super(message); } } <file_sep>/src/main/java/com/ndts/endless/Dao/MongoDB/Repositories/UserRepository.java package com.ndts.endless.Dao.MongoDB.Repositories; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import com.ndts.endless.Dao.MongoDB.Collections.User; public interface UserRepository extends MongoRepository<User, Long> { public User findByStatus(String status, long id); public List<User> findAllByStatus(String status); public User findOneById(long id); @Query(value="{'status':?0}", fields="{'password' : 0}") public List<User> findAllByStatusAndExclude(String status); public User findOneByUsername(String username); @Query(fields="{'password' : 0}") public User findOneByUsernameAndStatus(String username, String status); @Query(fields="{'password' : 0}") public User findOneByIdAndStatus(long id, String status); } <file_sep>/src/main/java/com/ndts/endless/ServerFilters/CustomAuthenticationProcessingFilter.java package com.ndts.endless.ServerFilters; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter; public class CustomAuthenticationProcessingFilter extends AbstractPreAuthenticatedProcessingFilter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { super.doFilter(request, response, chain); } @Override protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) { // TODO Auto-generated method stub return null; } @Override protected Object getPreAuthenticatedCredentials(HttpServletRequest request) { // TODO Auto-generated method stub return null; } } <file_sep>/src/main/java/com/ndts/endless/EmailConfiguration/EmailSender.java package com.ndts.endless.EmailConfiguration; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import com.ndts.endless.Exceptions.EmailSenderRuntimeException; /** * Email sender builder, builds an email message and sends it * @author <NAME> * **/ public class EmailSender { //Class vars private String from; private String to; private String subject; private String replyTo; private String text; private SimpleMailMessage simpleMailMessage; private JavaMailSender mailSender; public EmailSender(JavaMailSender mailSender,SimpleMailMessage simpleMailMessage) { this.simpleMailMessage = simpleMailMessage; this.mailSender = mailSender; } public EmailSender from(String from) { this.from = from; simpleMailMessage.setFrom(from); return this; } public EmailSender to(String to) { this.to = to; simpleMailMessage.setTo(to); return this; } public EmailSender subject(String subject) { this.subject = subject; simpleMailMessage.setSubject(subject); return this; } public EmailSender replyTo(String replyTo) { this.replyTo = replyTo; simpleMailMessage.setReplyTo(replyTo); return this; } public EmailSender text(String text) { this.text = text; simpleMailMessage.setText(text); return this; } public void send() { boolean valid = true; if(from==null||from.isEmpty()) { valid = false; } if(to==null||to.isEmpty()) { valid = false; } if(subject==null||subject.isEmpty()) { valid = false; } if(replyTo==null||replyTo.isEmpty()) { valid = false; } if(text==null||text.isEmpty()) { valid = false; } if(!valid) { throw new EmailSenderRuntimeException("You must fill all the fields before sending an email."); } mailSender.send(simpleMailMessage); } public String getFrom() { return from; } public String getTo() { return to; } public String getSubject() { return subject; } public String getReplyTo() { return replyTo; } public String getText() { return text; } public SimpleMailMessage getSimpleMailMessage() { return simpleMailMessage; } } <file_sep>/src/main/java/com/ndts/endless/RestApi/UserController.java package com.ndts.endless.RestApi; import java.security.Principal; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.ndts.endless.BusinessLogic.UserLogic; import com.ndts.endless.Dao.MongoDB.Collections.User; import com.ndts.endless.Dao.MongoDB.Collections.UserNotification; import com.ndts.endless.Dao.MongoDB.Collections.VerificationToken; import com.ndts.endless.Enums.EntityType; import com.ndts.endless.Enums.RequestDateFields; import com.ndts.endless.Exceptions.DaoException; import com.ndts.endless.Exceptions.LogicException; import com.ndts.endless.Exceptions.ValidationException; import com.ndts.endless.Helpers.GlobalHelper; import com.ndts.endless.Validation.GlobalValidation; import com.ndts.endless.Validation.UserValidation; import com.ndts.endless.WebSocket.Services.NotificationService; /** * User controller * @author <NAME> * */ @RestController @RequestMapping(value="/users") public class UserController { //Class vars @Autowired private UserValidation userValidation; @Autowired private UserLogic userLogic; @Autowired private GlobalValidation globalValidation; @Autowired private NotificationService notificationService; //Constants public static final String USER = EntityType.USER.getPresentational(); public static final String CONTROLLER_PATH = "/users"; @RequestMapping(value="/test",method=RequestMethod.GET) @ResponseBody public ResponseEntity<?> getPrincipal(Principal principal,OAuth2Authentication authentication){ System.out.println(principal.toString()); ResponseEntity<?> response = new ResponseEntity<Principal>(principal,HttpStatus.OK); return response; } /************************************************************************** * Create user, user registration * @param user the user to create * @return response with the created user *************************************************************************/ @RequestMapping(value="/registration",method=RequestMethod.POST) @ResponseBody public ResponseEntity<?> createUser(@RequestBody User user){ ResponseEntity<?> response = null; User returnedUser = null; try { //validate user userValidation.validateUserCreation(user); //execute user business logic returnedUser = userLogic.createUser(user); //build response entity response = new ResponseEntity<User>(returnedUser,HttpStatus.CREATED); } catch (ValidationException | DaoException e) { //build error response response = GlobalHelper.buildErrorResponse(e, HttpStatus.CONFLICT, CONTROLLER_PATH+"/registration"); } return response; } /************************************************************************** * Get user by id * @param id the user id to get the user with * @return response with the returned user * @throws LogicException *************************************************************************/ @RequestMapping(value="/single/byId/{id}",method=RequestMethod.GET) @ResponseBody public ResponseEntity<?> getUser(@PathVariable("id") long id){ ResponseEntity<?> response = null; User returnUser=null; try { //execute business logic returnUser=userLogic.getUser(id); //build response entity response=new ResponseEntity<User>(returnUser,HttpStatus.OK); } catch (LogicException | DaoException e) { //build error response response = GlobalHelper.buildErrorResponse(e, HttpStatus.CONFLICT, CONTROLLER_PATH+"/single/byId/{id}"); } return response; } /************************************************************************** * Update user * @param user the user to update * @return response with the updated user *************************************************************************/ @RequestMapping(method=RequestMethod.PUT) @ResponseBody public ResponseEntity<?> updateUser(@RequestBody User user){ ResponseEntity<?> response = null; User returnedUser = null; try { //validate user update userValidation.validateUserUpdate(user); //update the user returnedUser=userLogic.updateUser(user); //build response entity response=new ResponseEntity<User>(returnedUser,HttpStatus.OK); }catch(DaoException | LogicException | ValidationException e) { //build error response response = GlobalHelper.buildErrorResponse(e, HttpStatus.CONFLICT, CONTROLLER_PATH); } return response; } /************************************************************************** * Delete user * @param id the id of the user to delete * @return response with the deleted user *************************************************************************/ @RequestMapping(value="/{id}",method=RequestMethod.DELETE) @ResponseBody public ResponseEntity<?> deleteUser(@PathVariable("id") long id){ ResponseEntity<?> response = null; User returnedUser = null; try { //validate user id globalValidation.validateId(id,EntityType.USER); //delete the user returnedUser=userLogic.deleteUser(id); //build response entity response = new ResponseEntity<User>(returnedUser,HttpStatus.OK); } catch (ValidationException | DaoException | LogicException e) { //build error response response = GlobalHelper.buildErrorResponse(e, HttpStatus.CONFLICT, CONTROLLER_PATH+"/{id}"); } return response; } /************************************************************************** * Get all users * @return all users *************************************************************************/ @PreAuthorize("hasAnyRole('Admin')") @RequestMapping(value="/all",method=RequestMethod.GET) @ResponseBody public ResponseEntity<?> getAllUsers(){ ResponseEntity<?> response = null; //gett all the users List<User> returnedUsers = userLogic.getAllUsers(); //build response entity response = new ResponseEntity<List<User>>(returnedUsers,HttpStatus.OK); UserNotification userNotification = new UserNotification(); userNotification.setMessage("shalom"); userNotification.setCreationDate(new Date()); notificationService.notify(userNotification , "neonux"); return response; } /************************************************************************** * Get all users by creation date * @param startDate * @param endDate * @param sortType * @return all the users by creation date *************************************************************************/ @RequestMapping(value="/all/byCreationDate",method=RequestMethod.GET) @ResponseBody public ResponseEntity<?> getAllUsersByCreationDate(@RequestParam("startDate") String startDate,@RequestParam("endDate") String endDate,@RequestParam("sortType") String sortType){ List<User> returnedUsers = null; ResponseEntity<?> response = null; try { //validate star date Date parsedStartDate = globalValidation.validateDate(startDate); //validate end date Date parsedEndDate = globalValidation.validateDate(endDate); //validate sort type Sort.Direction parsedSortType = globalValidation.validateSortType(sortType); //execute business logic returnedUsers = userLogic.getAllUsersByChosenDateField(RequestDateFields.CREATION_DATE,parsedStartDate,parsedEndDate,parsedSortType); //build the response response = new ResponseEntity<List<User>>(returnedUsers,HttpStatus.CREATED); } catch (ValidationException | DaoException e) { //build error response response = GlobalHelper.buildErrorResponse(e, HttpStatus.CONFLICT, CONTROLLER_PATH+"/all/byCreationDate/byRange/{startDate}/till/{endDate}/sortType/{sortType}"); } return response; } /************************************************************************** * Verify account * @param token the token to verify the account with * @return response with the verified user *************************************************************************/ @RequestMapping(value="/verify-account",method=RequestMethod.POST) @ResponseBody public ResponseEntity<?> verifyAccount(@RequestParam("token") String token){ ResponseEntity<?> response = null; User returnedUser = null; try { //execute user business logic returnedUser = userLogic.activateAccount(token); //build response entity response = new ResponseEntity<User>(returnedUser,HttpStatus.OK); } catch (DaoException | LogicException e) { //build error response response = GlobalHelper.buildErrorResponse(e, HttpStatus.CONFLICT, CONTROLLER_PATH+"/verify-account"); } return response; } /************************************************************************** * Re-send a verification token * @param existingToken the existing token in order to get a new one * @return response with the verified user *************************************************************************/ @RequestMapping(value="/resend-token",method=RequestMethod.POST) @ResponseBody public ResponseEntity<?> resendVerificationToken(@RequestParam("token") String existingToken){ ResponseEntity<?> response = null; VerificationToken returnedVerificationToken = null; try { //execute user business logic returnedVerificationToken = userLogic.resendToken(existingToken); //build response entity response = new ResponseEntity<VerificationToken>(returnedVerificationToken,HttpStatus.OK); } catch (DaoException | LogicException e) { //build error response response = GlobalHelper.buildErrorResponse(e, HttpStatus.CONFLICT, CONTROLLER_PATH+"/verify-account"); } return response; } } <file_sep>/src/main/java/com/ndts/endless/RestApi/ErrorHandlingController.java package com.ndts.endless.RestApi; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.security.access.AccessDeniedException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import com.ndts.endless.Entities.ErrorResponse; /** * Exceptions handler * @author <NAME> * */ @ControllerAdvice public class ErrorHandlingController { /************************************************************************** * handles json not readable message, can be caused by the client * not passing a json object * @param e the exception to handle * @param request the request from the client * @return json error response *************************************************************************/ @ExceptionHandler(HttpMessageNotReadableException.class) public ResponseEntity<ErrorResponse> handleJacksonExceptions(Exception e,HttpServletRequest request){ ErrorResponse er = new ErrorResponse(); er.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value()); er.addMessage("Problem converting json, dont try to post or update by not sending a json object"); er.setPath(request.getRequestURI()); return new ResponseEntity<ErrorResponse>(er,HttpStatus.valueOf(er.getCode())); } /* *//************************************************************************** * Handles most runtime exceptions * @param e the exception to handle * @param request the request from the client * @return json error response *************************************************************************//* @ExceptionHandler(RuntimeException.class) public ResponseEntity<ErrorResponse> handleRuntimeException(RuntimeException e,HttpServletRequest request){ ErrorResponse er = new ErrorResponse(); er.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value()); er.addMessage(e.getMessage()+" Please contact support@localhost."); er.setPath(request.getRequestURI()); return new ResponseEntity<ErrorResponse>(er,HttpStatus.valueOf(er.getCode())); }*/ } <file_sep>/src/main/java/com/ndts/endless/Enums/RequestDateFields.java package com.ndts.endless.Enums; public enum RequestDateFields { CREATION_DATE("creationDate"), END_DATE("endDate"), TARGET_DATE("targetDate"), LAST_UPDATED_DATE("lastUpdatedDate"); private String label; private RequestDateFields(String label){ this.label = label; } /** * create a representation string of the enum * @return the representation String of the enum */ public String getLabel(){ return label; } } <file_sep>/src/main/java/com/ndts/endless/Enums/UserType.java package com.ndts.endless.Enums; public enum UserType { COMPANY("Company"), USER("User"); private String label; private UserType(String label){ this.label = label; } /** * create a representation string of the enum * @return the representation String of the enum */ public String getLabel(){ return label; } } <file_sep>/src/main/java/com/ndts/endless/Dao/MongoDB/UserNotificationDao.java package com.ndts.endless.Dao.MongoDB; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ndts.endless.Dao.MongoDB.Collections.UserNotification; import com.ndts.endless.Dao.MongoDB.Repositories.UserNotificationRepository; import com.ndts.endless.Dao.MongoDB.Rules.AbstractUserNotificationDao; import com.ndts.endless.Exceptions.DaoException; /** * User notification data access object * allows CRUD operations on user notification collections * @author <NAME> * */ @Service public class UserNotificationDao implements AbstractUserNotificationDao{ //Class vars @Autowired private UserNotificationRepository userNotificationRepo; /************************************************************************** * creates a user notification *************************************************************************/ @Override public UserNotification createUserNotification(UserNotification userNotification) throws DaoException{ UserNotification returnedUserNotification = userNotificationRepo.save(userNotification); if(returnedUserNotification==null) { throw new DaoException("There was a problem creating a user notifcation."); } return returnedUserNotification; } } <file_sep>/src/main/java/com/ndts/endless/WebSocket/Controllers/NotificationController.java package com.ndts.endless.WebSocket.Controllers; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.ndts.endless.Dao.MongoDB.Collections.UserNotification; import com.ndts.endless.WebSocket.Services.NotificationService; @Controller public class NotificationController { @Autowired private NotificationService notificationService; @MessageMapping("/notify") @SendTo("/queue/notify") public UserNotification testing(String message) throws Exception { Thread.sleep(1000); // simulated delay UserNotification userNotification = new UserNotification(); userNotification.setMessage(message); userNotification.setCreationDate(new Date()); return userNotification; } /** * POST /some-action -> do an action. * * After the action is performed will be notified UserA. */ @RequestMapping(value = "/some-action", method = RequestMethod.POST) @ResponseBody public ResponseEntity<?> someAction() { // Do an action here // ... // Send the notification to "UserA" (by username) UserNotification userNotification = new UserNotification(); userNotification.setMessage("Hello"); userNotification.setCreationDate(new Date()); notificationService.notify(userNotification, // notification object "neonux" // username ); // Return an http 200 status code return new ResponseEntity<>(HttpStatus.OK); } } <file_sep>/src/main/java/com/ndts/endless/Enums/CalendarWeekDay.java package com.ndts.endless.Enums; public enum CalendarWeekDay { SUNDAY("Sunday","ראשון"), MONDAY("Monday","שני"), THUESDAY("Thuesday","שלישי"), WEDNESDAY("Wednesday","רביעי"), THURSDAY("Thursday","חמישי"), FRIDAY("Friday","שישי"), SATURDAY("Saturday","שבת"); private String englishDayName; private String hebrewDayName; private CalendarWeekDay(String englishDayName,String hebrewDayName) { this.englishDayName = englishDayName; this.hebrewDayName = hebrewDayName; } public String getEnglishDayName() { return englishDayName; } public String getHebrewDayName() { return hebrewDayName; } /** * validate that the value exists in the enum * @param value the value to validate * @return true if the value exists otherwise false */ public static boolean isEnum(String value){ if(value!=null) { //use the default valueOf() after converting the value to uppercase try { valueOf(value.toUpperCase()); return true; }catch(IllegalArgumentException e) { return false; } } return false; } /** * get the representational of the String * for example: dog will Dog with first letter uppercase * @param value * @return */ public static String toPresentational(String value) { value = value.toLowerCase(); value = value.substring(0, 1) + value.substring(1); return value; } } <file_sep>/src/main/java/com/ndts/endless/Dao/MongoDB/Repositories/VerificationRepository.java package com.ndts.endless.Dao.MongoDB.Repositories; import org.springframework.data.mongodb.repository.MongoRepository; import com.ndts.endless.Dao.MongoDB.Collections.VerificationToken; public interface VerificationRepository extends MongoRepository<VerificationToken,Long>{ public VerificationToken findByToken(String token); } <file_sep>/src/main/java/com/ndts/endless/Entities/Roles/User.java package com.ndts.endless.Entities.Roles; import com.ndts.endless.Entities.Roles.Parents.Role; import com.ndts.endless.Enums.RoleType; /** * user role * @author <NAME> * */ public class User extends Role { public User() { super(RoleType.USER); } }
6bcf29ab8193b376598ece8555e270a3f13ba9bb
[ "Java" ]
20
Java
neonux1987/endless
67618ea5b8dd3b55dbe051247f163b90534bd7a1
3e5220e02ecebc127fed1ec5b1de2c9a1666f85a
refs/heads/master
<repo_name>eosstore/eoskeeper<file_sep>/README.md # eoskeeper EOS BP节点高可用守护进程 [FOR English](https://github.com/eosstore/eoskeeper/blob/master/README-EN.md) ### 提示 如果您计划使用本程序,请仔细阅读源码eoskeeper.py。 ### 已实现的功能 * 实时监控节点当前区块高度、不可逆块高度、当前出块BP名字。 * 实时监控BP节点是否正在出块。(1主2备使用相同的秘钥启动,需要通过过滤日志判断具体是哪个机器正在出块) * 实时监控节点之间的p2p链接数量。(通过调用lsof命令实现,连接数是个非常重要的参数) * 任何参数出现异常将会通过企业微信和短信报警。(需要使用您自己的微信和短信模块) * 当主BP出现故障后,第一个备用BP在两轮后自动出块,实现BP的高可用。 * 如果主BP和第一个备用BP都故障无法出块,第二个备用BP在7轮后会开始出块,实现BP的高可用。 * 实时将各个节点的运行参数推送到influxdb,然后通过grafana进行展示。 其他:grafana界面,需要从influxdb数据库和zabbix数据库提取数据,并自行定制界面。 ### 运行环境 python版本: 2.7 ### 安装于运行 ``` 安装 $ easy_install -U sh requests $ mkdir /etc/eoskeeper 增加配置文件 vi /etc/eoskeeper/config.ini (参考config.ini) $ 将eoskeeper.py的源码放到 /usr/local/bin/eoskeeper 文件中。 $ chmod +x /usr/local/bin/eoskeeper $ 修改配置文件,关键是角色的修改。(角色的解释见下文,主BP角色为A,第一个备用BP角色为B,第二个备用BP角色为C,其他为F) 运行 建议使用systemctl 服务运行eoskeeper,创建服务请参考/systemctl/README.md 也可以eoskeeper,直接运行,运行前需要写好配置文件。 ``` ### 配置文件说明 ```a role = "A" block_producer_name = "eosstorebest" # 注册的bp名称 eosio_log_file = "/data/eosio.log" # eosio日志文件 eoskeeper_log_file = "/data/eoskeeper.log" # eoskeeper本身 infulxdb_url = "http://172.16.58.3:8086/write?db=eosdb" # influxdb的url mobiles = "1821050****,1352131****" #需要被短信通知的人员的手机号 ``` ### influxdb的两个表 BP节点表 (共3台机器) 表名 eosbpinfo 字段名/中文名 属性 示例 * host/主机名 (字符串) eos-open-fn-1-1 * hbn/当前块 (整数) 19876 * lib/不可逆块 (整数) 19856 * linkn/连接数量 (整数) 34 * lpbt/上次出块时间 (字符串) 10秒前 * paused (字符串) 是 * info/告警信息 (字符串,最长60个字符) 全节点表 (共7台机器) 表名 eosfninfo * 字段名/中文名 属性 示例 * host/主机名 (字符串) eos-open-fn-1-1 * hbn/当前块 (整数) 19876 * lib/不可逆块 (整数) 19856 * linkn/连接数量 (整数) 34 * info/告警信息 (字符串,最长60个字符) ### 逻辑说明 eoskeeper是一个用于监控eos程序的守护进程,并有报警和推送参数到influxdb的功能。 == 程序原理 == 我们的节点分为四种角色:A角色(BP)、B角色(备用BP,第一道防线)、C角色(备用BP,第二道防线)、普通全节点(后面用F角色表示) 在三个主机中会分别给eoskeeper守护进程配置文件中设置为A、B、C三个角色,以下是eoskeeper根据角色做出相应的动作。 当eosstorebest在前21名,B主机eosio运行正常,并且,B主机检测到2轮出块循环都没有eosstorebest账户时,B主机的eoskeeper会执行命令,使B出块。 当eosstorebest在前21名,C主机eosio运行正常,并且,C主机检测到6轮出块循环都没有eosstorebest账户时,C主机的eoskeeper会执行命令,使C出块。 == 配置相关 == 所有eosio需要配置 http-server-address = 127.0.0.1:8888 为了/v1/producer/* api BP节点的eosio配置文件需增加 plugin = eosio::producer_api_plugin == 管理相关 == 任何一台主机出现故障时,都需要及时修复。修复后,使各个节点恢复自己的角色。 ### 相关命令 ```bash curl --request POST --url http://127.0.0.1:8888/v1/producer/pause curl --request POST --url http://127.0.0.1:8888/v1/producer/resume curl --request POST --url http://127.0.0.1:8888/v1/producer/paused ``` <file_sep>/eoskeeper.py #!/usr/bin/env python # -*- coding: UTF-8 -*- import time import threading import re import ConfigParser from sh import tail import requests import subprocess import json import logging import socket # -- 这是一个右进左出的list -- # get函数把最右边的当成第0个元素 class List: def __init__(self, max_length): self.__list = [] self.__maxLength = max_length self.__lock = threading.Lock() def append(self, data): self.__lock.acquire() if self.__list.__len__() >= self.__maxLength: self.__list.pop(0) self.__list.append(data) self.__lock.release() def read(self, length): self.__lock.acquire() res = self.__list[(self.__list.__len__() - length):] self.__lock.release() return res def get(self, index): res = "" self.__lock.acquire() if self.__list.__len__() - 1 > index: res = self.__list[(self.__list.__len__() - index - 1)] self.__lock.release() return res def length(self): return self.__list.__len__() def dump(self): print self.__list # -- 从配置文件加载参数 -- class NewConfigParser(ConfigParser.RawConfigParser): def get(self, section, option): val = ConfigParser.RawConfigParser.get(self, section, option) return val.strip('"').strip("'") config = NewConfigParser() try: config.read('/etc/eoskeeper/config.ini') config.read('config.ini') except: pass role = config.get("global", "role") block_producer_name = config.get("global", "block_producer_name") eosio_log_file = config.get("global", "eosio_log_file") eoskeeper_log_file = config.get("global", "eoskeeper_log_file") infulxdb_url = config.get("global", "infulxdb_url") mobiles = config.get("global", "mobiles") logging.basicConfig(filename=eoskeeper_log_file, level="INFO") # -- 全局变量 -- l_http_json_ok = List(1000) # 记录http端口是否返回数据,及是否是json格式;正确则记录1,错误则记录为2 l_http_hbp = List(1000) # head_block_producer l_http_hbn = List(1000) # head_block_num l_http_lib = List(1000) # last_irreversible_block_id t_producing_block = 0 # the latest time of producing block nodeos_pid = 0 current_links = "" # strings current_linkn = 0 # link number hostname = "" local_ip = "" is_paused = "unknown" # /v1/producer/paused current_alarm_msg = "" server_version = "" # -- 全局常量 -- re1 = r'.*producer_plugin.cpp.*] Produced block .* (#\d+) @.*' url = 'http://127.0.0.1:8888/v1/chain/get_info' sms_url = "https://dx.ipyy.net/smsJson.aspx" # -- init --- def now(): return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) def log_info(msg): print "INFO: " + now() + " " + msg logging.info(" " + now() + " " + msg) def log_err(msg): print "ERROR: " + now() + " " + msg logging.error(" " + now() + " " + msg) def get_local_ip(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ip = s.getsockname()[0] s.close() return ip def init(): global nodeos_pid, hostname, local_ip, is_paused ret = "" try: ret = subprocess.check_output(["lsof", "-i:8888"]) except: log_info("ERROR! run lsof -i:8888\nExit!") exit(1) lines = ret.split("\n") line = lines[1] cols = re.split(r" +", line) nodeos_pid = cols[1] hostname = socket.gethostname() is_paused = is_produce_paused() try: local_ip = get_local_ip() except: pass # -- LogParser -- def log_parse(line): global t_producing_block res1 = re.match(re1, line) # 只有本节点出块时匹配此项。 if res1: t_producing_block = time.time() log_info(" ******* Produce block " + res1.group(1) + " ********") class LogParser(threading.Thread): def run(self): log_info("Run thread LogParser") while True: try: for line in tail("-n", 1, "-f", eosio_log_file, _iter=True): log_parse(line) except: log_err("eosio log file:" + eosio_log_file + " parse failed!") time.sleep(10) # -- HttpParser -- def http_parse(): try: r = requests.get(url) except: l_http_json_ok.append(2) logging.error("/v1/chain/get_info get failed") else: try: res = r.json() except: l_http_json_ok.append(2) logging.error("/v1/chain/get_info didn't return json") else: l_http_json_ok.append(1) server_version = res["server_version"] l_http_hbn.append(res["head_block_num"]) l_http_hbp.append(res["head_block_producer"]) l_http_lib.append(res["last_irreversible_block_num"]) class HttpParser(threading.Thread): def run(self): log_info("Run thread HttpParser") while True: http_parse() time.sleep(1) # 必须是1秒,不可更改 # -- LsofParser -- def lsof_parser(): global current_links, current_linkn count = 0 links = "" ret = subprocess.check_output(["lsof", "-nP", "-p", nodeos_pid]) lines = ret.split("\n") for line in lines: if re.match(r'.*TCP 172.*', line): count += 1 cols = re.split(r" +", line) links += cols[len(cols) - 2] + "\n" current_linkn = count current_links = links # log_info("\nlink_num: " + str(current_linkn) + "\nlink_str:\n" + current_links) log_info("\nlink_num: " + str(current_linkn) + "\n") class LsofParser(threading.Thread): def run(self): log_info("Run thread LsofParser") while True: try: lsof_parser() except: log_err("lsof parser failed.") time.sleep(300) # -- 是否需要启动出块命令 -- def start_produce(): global is_paused # ret = requests.post("http://127.0.0.1:8888/v1/producer/resume") # ABP阶段 if not ret.ok: log_err("/v1/producer/resume failed") else: is_paused = False def is_produce_paused(): ret = requests.post("http://127.0.0.1:8888/v1/producer/paused") if not ret.ok: log_err("/v1/producer/paused failed") return if ret.content == "false": return False elif ret.content == "true": return True def produce_or_not(): log_info("run produce_or_not()") if l_http_json_ok.read(50) == [1] * 50 and int(l_http_lib.get(0)) > int(l_http_lib.get(20)): if role == "B": ret = l_http_hbp.read(250) elif role == "C": ret = l_http_hbp.read(850) else: return bps = set() count = 0 for r in ret: if r == block_producer_name: count += 1 bps.add(r) log_info("There are " + str(count) + "bp name records in list l_http_hbp") if block_producer_name not in bps: start_produce() log_info(" ++++++++ START PRODUCE BLOCK ++++++++") else: if is_produce_paused(): log_info("Production Paused") else: log_info(block_producer_name + " produced block " + str( int(time.time() - t_producing_block)) + " seconds ago") bp_status = "unknown" # "unknown" "bp" "nonbp" class ProduceOrNot(threading.Thread): def run(self): log_info("Run thread ProduceOrNot") global bp_status if role == "B": time.sleep(280) elif role == "C": time.sleep(900) else: log_info("Assert ERROR!\nExit") exit(1) while True: res = is_21ebp() if res == "true": if bp_status == "nonbp": bp_status = "bp" time.sleep(250) try: produce_or_not() except: log_err("produce_or_not() failed.") elif res == "false": bp_status = "nonbp" time.sleep(10) class Messenger(object): def __init__(self): pass def access_server(self): CorpID = "wx************" # use your own info Secret = "T3CLEw4s****************************************" # use your own info url1 = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s" % (CorpID, Secret) r = requests.get(url1) # 获取access_token access_token = json.loads(r.text)['access_token'] return access_token def send_weixin(self, title, hostname, messages): news = { "touser": "**************************************", # use your own info # 用户ID 多个ID 可以用|隔开 # "touser": "wo_weixinni", "toparty": " 2 ", # 部门ID "totag": " ", "msgtype": "news", "agentid": 0, "news": { "articles": [ { "title": "%s|%s" % (title, hostname), "description": messages + now() }, ] } } token = self.access_server() body = json.dumps(news, ensure_ascii=False) url4 = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s" % token r = requests.post(url4, data=body) status = json.loads(r.text)['errmsg'] if status == 'ok': print "报警发送成功!" return True else: print "报警发送失败!" return False msger = Messenger() def send_mobile_msg(msg): # use your own sms info sign = '请及时处理。【EOS主网运维】' querystring = {"action": "send", "userid": "5*******", "account": "A*******", "password": "<PASSWORD>************", "mobile": mobiles, "content": msg + sign, "sendTime": "", "extno": ""} headers = { 'Cache-Control': "no-cache", 'Postman-Token': "<KEY>" } status = "" try: res = requests.request("GET", sms_url, headers=headers, params=querystring) rj = json.loads(res.content) status = rj['returnstatus'] except: pass return status == "Success" t_last_alarm = 0 def alarm(msg): global t_last_alarm if (time.time() - t_last_alarm) > 1800: t_last_alarm = time.time() try: if not msger.send_weixin("EOS故障报警", hostname, local_ip + " " + msg): log_err("send wechat msg failed.") if not send_mobile_msg("故障信息:" + hostname + "|" + local_ip + "|" + msg): log_err("send mobile msg failed.") except: log_err("msger.send_weixin() or send_mobile_msg() failed.") # -- 告警分析 -- def err_parse(): global current_alarm_msg msg = "" # 分析连接数量是否正常 if current_linkn < 5: msg += "节点peer连接数(" + str(current_linkn) + ")过低! " # 分析http端口是否正常 if l_http_json_ok.length() > 5: if l_http_json_ok.read(5) == [2] * 5: msg += "http api 请求异常! " # 分析http返回的lib是否正常 if l_http_lib.length() > 30: res = l_http_lib.read(20) if res[0] == res[18]: msg += "20秒内lib未增加,严重故障!" # 分析http返回的bps是否正常 if l_http_hbp.length() > 60: bps = set() for bp in l_http_hbp.read(60): bps.add(bp) if bps.__len__() < 5: msg += "1分钟内捕获的BP个数(" + str(bps.__len__()) + ")太少! " # 分析http返回的hbn是否正常 if l_http_hbn.length() > 10: res = l_http_hbn.read(10) if res[0] == res[9]: msg += "10秒内head_block_num未增加! " current_alarm_msg = msg if msg != "": alarm(msg) log_err(msg) class ErrAlarm(threading.Thread): def run(self): log_info("Run thread ErrAlarm") while True: time.sleep(5) err_parse() def get_hour_min(): t = time.strftime("%H:%M", time.localtime()) return t.split(':') t_last_notice = 0 def wechat_and_sms(msg): msger.send_weixin("EOS日常信息", hostname, local_ip + msg) send_mobile_msg("日常信息:" + hostname + "|" + local_ip + "|" + msg) def daily_notice(): global t_last_notice, role if role == "F": msg = hostname + "|hbn:" + str(l_http_hbn.get(0)) + "|lib:" + str(l_http_lib.get(0)) \ + "|linkn:" + str(current_linkn) + "|info:" + current_alarm_msg if time.time() - t_last_notice > 3600: h, m = get_hour_min() if (h == "7" or h == "19") and m < 30: t_last_notice = time.time() wechat_and_sms(msg) else: msg = hostname + "|hbn:" + str(l_http_hbn.get(0)) + "|lib:" + str(l_http_lib.get(0)) + "|linkn:" + str( current_linkn) \ + "|t_pb:" + str(t_producing_block) + "|info:" + current_alarm_msg if time.time() - t_last_notice > 3600: h, m = get_hour_min() if (h == "7" or h == "13" or h == "19") and m < 30: t_last_notice = time.time() wechat_and_sms(msg) class DailyNotice(threading.Thread): def run(self): log_info("Run thread DailyNotice") while True: daily_notice() time.sleep(300) def dump_var(): # l_http_json_ok.dump() # l_http_lib.dump() # l_http_hbn.dump() l_http_hbp.dump() class DumpVar(threading.Thread): def run(self): log_info("Run thread DumpVar") while True: dump_var() time.sleep(5) # str int int int str str str def post_bpn_info_to_infulxdb(host_name, hbn, lib, linkn, lpbt, paused, info): table_name = "eos_bp_node_info" if paused == "unknown": paused = "~" elif paused: paused = "是" else: paused = "否" t = time.time() if t - lpbt > 3600: lpbt_msg = "~" elif t - lpbt > 150: lpbt_msg = str(int(int(t - lpbt) / 60)) + "分钟前" else: lpbt_msg = str(int(t - lpbt)) + "秒前" tag_str = "host=" + host_name fields_str = "hbn/当前块=" + str(hbn) + "," fields_str += "lib/不可逆块=" + str(lib) + "," fields_str += "linkn/连接数量=" + str(linkn) + "," fields_str += "lpbt/上次出块时间=\"" + lpbt_msg + "\"," fields_str += "paused=\"" + paused + "\"," fields_str += "info/告警信息=\"" + info + "\"" data = table_name + "," + tag_str + " " + fields_str ret = requests.post(infulxdb_url, data) return ret.ok, ret.content # str int int int str def post_fulln_info_to_infulxdb(host_name, hbn, lib, linkn, info): table_name = "eos_full_node_info" tag_str = "host=" + host_name fields_str = "hbn/当前块=" + str(hbn) + "," fields_str += "lib/不可逆块=" + str(lib) + "," fields_str += "linkn/连接数量=" + str(linkn) + "," fields_str += "info/告警信息=\"" + info + "\"" data = table_name + "," + tag_str + " " + fields_str ret = "" try: ret = requests.post(infulxdb_url, data) except: pass return ret.ok, ret.content def push_fulln_msg(): global current_alarm_msg ok, content = post_fulln_info_to_infulxdb(hostname, l_http_hbn.get(0), l_http_lib.get(0), current_linkn, current_alarm_msg) if not ok: log_err("push_fulln_msg() " + content) def push_bpn_msg(): global is_paused, current_alarm_msg ok, content = post_bpn_info_to_infulxdb(hostname, l_http_hbn.get(0), l_http_lib.get(0), current_linkn, t_producing_block, is_paused, current_alarm_msg) if not ok: log_err("push_bpn_msg() " + content) class PushMsg(threading.Thread): def run(self): log_info("Run thread PushMsg") time.sleep(2) while True: if role == "F": try: push_fulln_msg() except: log_err("push_full_node_msg() failed.") else: try: push_bpn_msg() except: log_err("push_bpn_msg() failed.") time.sleep(3) def is_21ebp(): try: r = requests.post("http://127.0.0.1:8888/v1/chain/get_producers", '{"json":"true"}') if r.ok: ret = r.json() bps = ret["rows"] ebps = list(map(lambda bp: bp["owner"], bps[:21])) if block_producer_name in ebps: return "true" else: return "false" except: pass return "req_err" if __name__ == '__main__': log_info("eoskeeper start. " + now()) log_info("config.ini :\n" + role + "\n" + block_producer_name + "\n" + eosio_log_file + "\n" + eoskeeper_log_file + "\n" + infulxdb_url + "\n" + mobiles + "\n") res = is_21ebp() if res == "true": log_info('*' * 15 + " WE ARE BP NOW " + '*' * 15) elif res == "false": log_info('-' * 15 + " we aren't bp " + '-' * 15) else: log_info('/' * 15 + " FATAL ERROR! " + '/' * 15 + "\nExit!") exit(1) init() log_parser_t = LogParser() log_parser_t.setDaemon(True) log_parser_t.start() http_parser_t = HttpParser() http_parser_t.setDaemon(True) http_parser_t.start() lsof_parser_t = LsofParser() lsof_parser_t.setDaemon(True) lsof_parser_t.start() push_msg_t = PushMsg() push_msg_t.setDaemon(True) push_msg_t.start() err_alarm_t = ErrAlarm() err_alarm_t.setDaemon(True) err_alarm_t.start() daily_t = DailyNotice() daily_t.setDaemon(True) daily_t.start() # dump_var_t = DumpVar() # dump_var_t.setDaemon(True) # dump_var_t.start() if role == "B" or role == "C": produce_or_not_t = ProduceOrNot() produce_or_not_t.setDaemon(True) produce_or_not_t.start() while True: if not role == 'F': is_paused = is_produce_paused() time.sleep(600) <file_sep>/config.ini [global] role = "A" block_producer_name = "eosstorebest" eosio_log_file = "/data/eosio.log" eoskeeper_log_file = "/data/eoskeeper.log" infulxdb_url = "http://ip:port/write?db=eosdb" mobiles = "1821050****,1352131****" <file_sep>/systemctl/README.md ### 编写eoskeeper服务 ``` mkdir -p /usr/lib/systemd/system vi /usr/lib/systemd/system/eoskeeper.service ``` ### eoskeeper.service ``` [Unit] Description=eoskeeper [Service] User=eosio ExecStart=/bin/bash -c "/usr/local/bin/eoskeeper > /dev/null 2>&1" Restart=always [Install] WantedBy=multi-user.target ``` ### 操作 ``` systemctl start eoskeeper.service systemctl stop eoskeeper.service systemctl enable eoskeeper.service ``` <file_sep>/README-EN.md # eoskeeper [中文链接](https://github.com/eosstore/eoskeeper/blob/master/README.md) ### Prompt If you plan to use this program, read the source code:eoskeeper.py carefully. ### Implemented functionality * Real-time monitoring node current block height, irreversible block height, current block BP name. * Real-time monitoring of whether the BP node is coming out of the block. (1 master 2 standby uses the same key to start, you need to filter the log to determine which machine is out of the box) * Real-time monitoring of the number of p2p links between nodes. (The number of connections is a very important parameter by calling the lsof command) * Any abnormality in the parameters will be notified by Enterprise WeChat and SMS. (need to use your own WeChat and SMS module) * When the primary BP fails, the first standby BP automatically issues a block after two rounds to achieve high availability of BP. * If both the primary BP and the first standby BP fail to be blocked, the second standby BP will start to be out after 7 rounds to achieve high availability of BP. * Push the running parameters of each node to influxdb in real time, and then display it through grafana. other:grafana interface,you need get data from influxdb database and zabbix database,and do it for yourself. ### Runtime environment python version:2.7 ### Install and run ``` Install $ easy_install -U sh requests $ mkdir /etc/eoskeeper add config.ini vi /etc/eoskeeper/config.ini (reference config.ini) $ put eoskeeper.py source code to /usr/local/bin/eoskeeper. $ chmod +x /usr/local/bin/eoskeeper $ Modify configuration file,the important is to change the role. (the role is explained below. The main BP role is A, the first standby BP role is B, the second standby BP role is C, and the others are F) Run It is recommended to use systemctl service to run eoskeeper,please reference /systemctl/README.md to create service. you can alse run eoskeeper. ``` ### Introduce configuration ```a role = "A" block_producer_name = "eosstorebest" # bp name eosio_log_file = "/data/eosio.log" # eosio log eoskeeper_log_file = "/data/eoskeeper.log" # eoskeeper infulxdb_url = "http://13.115.200.171:8086/write?db=eosdb" # influxdb的url mobiles = "1821050****,1352131****" #The phone number of the person who needs to be notified ``` ### Two list of influxdb BP list (3 hosts) list-name: eosbpinfo Field name/Chinese name attribute sample * host/host name (string) eos-open-fn-1-1 * hbn/current block (int) 19876 * lib/irreversible block (int) 19856 * linkn/link number (int) 34 * lpbt/last produce time (string) 10秒前 * paused (string) yes * info/alarm information (string,No more than 60 characters) fullnode list (7 hosts) list-name: eosfninfo * Field name/Chinese name attribute sample * host/host name (string) eos-open-fn-1-1 * hbn/current block (int) 19876 * lib/irreversible block (int) 19856 * linkn/link number (int) 34 * info/alarm information (string,No more than 60 characters) ### Logic instructions eoskeeper is a monitor the daemon of the eos program,with function of alarm and push message to influxdb。 == Principle of procedure == Our have 4 roles:A(BP),B(backup BP,the first line of defense),C(backup BP,the second line of defense),fullnode(role F) The three hosts will be set to the roles of A, B, and C in the configuration file of the eoskeeper daemon. The following is the action taken by eoskeeper according to the role. When eosstorebest before the 21st,eosio in host B running normal,and when hostB check eosstorebest isn't produce blocks with 2 round,eoskeeper of host C could perform command,let node B produce. When eosstorebest before the 21st,eosio in host C running normal,and when hostC check eosstorebest isn't produce blocks with 2 round,eoskeeper of host C could perform command,let node C produce. == about configuration == all eosio need to be configured http-server-address = 127.0.0.1:8888 In order to /v1/producer/* api, eosio-configuration of bp node need add plugin = eosio::producer_api_plugin == about admin == When each host fails, it needs to be repaired in time. After the fix, restore each node to its own role. ### Relevant command ```bash curl --request POST --url http://127.0.0.1:8888/v1/producer/pause curl --request POST --url http://127.0.0.1:8888/v1/producer/resume curl --request POST --url http://127.0.0.1:8888/v1/producer/paused ```
e697699f2882461a55eafdb13c04390fa311b1b5
[ "Markdown", "Python", "INI" ]
5
Markdown
eosstore/eoskeeper
af7710fbe8eeb890ba38c26c29cbd81edbaba4c6
9aa96455f72f58a3db98d4997f162f6a83c96c29
refs/heads/master
<file_sep>class Polygon < ActiveRecord::Base belongs_to :user has_many :categories, :dependent => :destroy end <file_sep>class PolygonsController < ApplicationController def index @polygons = Polygon.where(user_id:current_user.id) end def create @polygon = Polygon.create(polygon_params) redirect_to polygon_categories_url(@polygon) end def destroy @polygon = Polygon.find(params[:id]) @polygon.destroy redirect_to polygons_url end private def polygon_params params.require(:polygon).permit(:user_id, :name).merge(user_id:current_user.id) end end
6406b5b6e1f73db1cc96f9328c5c2222c9357121
[ "Ruby" ]
2
Ruby
sheepfunk/rails-polygons
cb1de19cf093a7e2503196b7d1043058fb467bf3
4df24d2594cd67d9099770ffc5eaed4badb4e9dd
refs/heads/master
<file_sep>#include<iostream> #define ll long long using namespace std; int main() { ll t; cin>>t; while(t--) { ll count=0,n,mul=5; cin>>n; while((n/mul) > 0) { count = count + (n/mul); mul*=5; } cout<<count<<endl; } return 0; } <file_sep>#include<iostream> #define ll long long using namespace std; int main() { int t; cin>>t; while(t--) { int fact[200]; int n,len; ll prod; cin>>n; fact[0]=1; len =0; for(;n>=2;n--) { prod = 0; for(int k = 0;k<=len;k++) { prod = (fact[k]*n) + prod; fact[k]=prod % 10; prod = prod/10; } while(prod>0) { fact[++len]= prod % 10; prod=prod/10; } } for(int i=len;i>=0;i--) cout<<fact[i]; cout<<endl; } return 0; } <file_sep>#include<iostream> using namespace std; int main() { int t; cin>>t; while(t--) { long long int s,r=0,a,ar=0,ans = 0; cin>>s>>a; // cout<<s<<endl; while(s>0) { r= (r*10) + (s % 10); s=s/10; } while(a>0) { ar = (ar*10) + (a%10); a=a/10; } // cout<<r<<" "<<a<<endl; r = r + ar; while(r>0) { //cout<<(r%10); ans = (ans*10) + (r%10); r= r/10; } cout<<ans<<endl; } return 0; } <file_sep>A Collection of all problems I have solved in SPOJ <file_sep>#include<iostream> #include<stack> #include<string> using namespace std; int main() { int t; cin>>t; while(t--) { string s; stack <char> opr; cin>>s; for(int i=0;i<s.size();i++) { if(s[i]=='(') continue; else if(s[i]==')') { cout<<opr.top(); opr.pop(); } else if(s[i]>96) cout<<s[i]; else opr.push(s[i]); } cout<<endl; } return 0; }
89c7eec7852d5875071bb6c63ebb3ac9fd132c51
[ "Markdown", "C++" ]
5
C++
kkushagra/competitive-programming
a60b6447a115d705bed924eea6c11a0789004a92
2529daddc171a92cde650d2c26eb72ae21a82ddc
refs/heads/master
<file_sep>class CommentsController < ApplicationController def create @comment= Comment.create(comments_params) @post=Post.find(@comment.post_id) redirect_to @post end private def comments_params params.require(:comment).permit(:content, :post_id) end end
d3a947757c0a86ff4d3efc45a64296a624278361
[ "Ruby" ]
1
Ruby
NanyR/rails-blog-nested-resources-web-0217
9e6891350014080bdc88051a9503d735e36a724e
1350119034efe28e0611ea12941043ac7e165b68
refs/heads/main
<file_sep>import axios from 'axios'; const prod = 1; const url = (prod === 0 ? "http://localhost:3000" : "https://bluemeter-backend.herokuapp.com/"); const api = axios.create({ baseURL: url }); export default api;
9fa1435de5a8bd014c1934c2ab5f28f61fa17787
[ "JavaScript" ]
1
JavaScript
MiguelA737/bluemeter-frontend
b68d13956adb727042af14264de7743ecce677f0
6f00a726d1d3e215276108587dd770f175930fff
refs/heads/main
<file_sep># Arduino_AC1 ## Nossa primeira AC, observe bem o código, procure pelos erros. Use o FORK para adicionar esse projeto a sua organização antes de começar. ![](https://img.shields.io/github/forks/Leoruiz197/Arduino_AC1) ![](https://img.shields.io/github/stars/Leoruiz197/Arduino_AC1) ![](https://github.com/Os-Pozes/Arduino_AC1/blob/main/2021-04-01.png) ## **O PROBLEMA:** uma fabrica de costura teve um problema de tecnologia dentro de seu estabelecimento e chamou o grupo dos pozes para resolver este problema. Adicionamos um botão para ligar e desligar o LED vermelho que indica o produto, tornamos o fio do botão totalmente funcional e editamos alguns códigos. ![](https://github.com/Os-Pozes/Arduino_AC1/blob/main/076d14b1-0cf3-40cd-8664-76d575df40fd.jpg) Luigi, 16 anos, apreciador de música internacional, moda, video games e NBA. ![](https://github.com/Os-Pozes/Arduino_AC1/blob/main/4bdfbb79-c469-4ea6-adc4-dc555f35a8cc.jpg) Kaue tenho 16 anos gosto muito de futebol e gosto muito de ouvir música. ![](https://github.com/Os-Pozes/Arduino_AC1/blob/main/8650c008-68bd-4c9d-befa-1376e0416288.jpg) A Camila gosta de fazer exercicios e ficar com os amigos. ![](https://github.com/Os-Pozes/Arduino_AC1/blob/main/8a17cec2-6353-4222-adf7-026e969a95d4.jpg) Mateo morou no rio e fora do pais, adora viajar internacionalmente. ![](https://github.com/Os-Pozes/Arduino_AC1/blob/main/b0450719-729b-41dc-9e78-da8132f79a90.jpg) A <NAME> tem 16 anos e gosta muito de moda. ![](https://github.com/Os-Pozes/Arduino_AC1/blob/main/fotos%20do%20grupo%5D.jpg) O Gabriel torce pro Sao Paulo e curte basquete. <file_sep>//variaveis da led const int vermelho = 5; const int verde = 6; const int azul = 7; bool estadoLedVermelho = false; //adiçao de um botao const int botao1 = 2; const int botao2 = 3; unsigned long lastDebounceTime1 = 0; unsigned long lastDebounceTime2 = 0; const int botaoDelay = 100; void setup() { pinMode(A0, INPUT); pinMode(A1, INPUT); //saida led azul pinMode(vermelho, OUTPUT); pinMode(verde, OUTPUT); pinMode(azul, OUTPUT); Serial.begin(9600); //nome do grupo Serial.println("AC1 - Meu Primeiro Projeto 2021"); Serial.println(" V1.0"); Serial.println("Grupo: bullfrog "); } //acender e apagar led vermelho void loop() { if((millis() - lastDebounceTime1) > botaoDelay && digitalRead(botao1)){ Serial.println("botao 1 apertado"); ledVermelho(true); lastDebounceTime1 = millis(); } if((millis() - lastDebounceTime2) > botaoDelay && digitalRead(botao2)){ int getLuminosidade(){ int luminosidade; luminosidade = map(analogRead(A1), 6, 619, -3, 10); return luminosidade; } Serial.println("luminosidade elevada"); }else{ ledVerde(false); Serial.println("botao 2 apertado"); ledVermelho(false); lastDebounceTime2 = millis(); } if(getTemperatura() > 15){ ledAzul(true); Serial.println("temepatura elevada"); }else{ ledAzul(false); Serial.println("temepatura ideal"); } if(getLuminosidade() > 5){ ledVerde(true); Serial.println("luminosidade elevada"); }else{ ledSerial.println("luminosidade ideal"); } delay(10); }Verde(false); void ledVermelho(bool estado){ digitalWrite(vermelho,estado); } void ledAzul(bool estado){ digitalWrite(azul,estado); } int getTemperatura(){ int temperaturaC; temperaturaC = map(((analogRead(A0) - 20) * 3.04), 0, 1023, -40, 125) return temperaturaC; } //funcao de leitura da luminosidade int getLuminosidade(){ int luminosidade; luminosidade = map(analogRead(A1), 6, 619, -3, 10); return luminosidade; }
66f91e6f527c2ef1737fe944ddffeac00e573075
[ "Markdown", "C++" ]
2
Markdown
Os-Pozes/Arduino_AC1
33b14f579cb25be7f2db1a6bbafcd733b8506d62
30708601a46ecad117f8e2d8903bbd254cab1266
refs/heads/master
<file_sep># WordCount A naive MapReduce simulation project. <file_sep>/** * Created by yuanfanz on 17/1/15. */ import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class WordCount { public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> { @Override public void map(Object key, Text value, Context context) throws IOException, InterruptedException { //key: offset //value: line //first split the whole line into string array by space String[] words = value.toString().split(" "); //iterate the string array for (String word : words) { //写入写出都是以key-value pair的形式 //key是单词本身,封装在text里面 Text outKey = new Text(word); //value就是count,用IntWritable封装value //对于mapper,它只起到了拆分的作用,每次的count都是1,统计相加总数由reducer来完成 IntWritable outValue = new IntWritable(1); //用自带的context方法写出key-value pair context.write(outKey, outValue); } } } public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> { public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { //I [1] //big [1,1] //Iterable就是遍历所有的1,再相加 int sum = 0; //iterate values and sum up for (IntWritable value : values) { sum += value.get(); } //key不变,sum用IntWritable封装 context.write(key, new IntWritable(sum)); } } public static void main(String[] args) throws Exception { //定义MapReduce中的配置,读取写出的一些细节 Configuration configuration = new Configuration(); //一个run的project就是一个job Job job = Job.getInstance(configuration); //告诉job运行哪个class的jar job.setJarByClass(WordCount.class); //mapper, reducer, output key/value job.setMapperClass(TokenizerMapper.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); //文件输入和输出的path从命令行读取,分别是第一个和第二个 FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); job.waitForCompletion(true); } }
5db9d3f039afdda08826102fe5588db258954f80
[ "Markdown", "Java" ]
2
Markdown
yuanfanz/WordCount
bd3b843e91b813f76602bf3c85277621f33848c2
c75155cbcb8022782561d034cf03d7e484769942
refs/heads/master
<file_sep>// arpa/inet.h - definitions for internet operations // #include <arpa/inet.h> // in_port_t, in_addr_t, struct in_addr, INET_ADDRSTRLEN, and INET6_ADDRSTRLEN. #include <netinet/in.h> // uint16_t, uint32_t. #include <inttypes.h> // The following shall be declared as functions, or defined as macros, // or both. If functions are declared, function prototypes shall be // provided. uint32_t htonl(uint32_t); uint16_t htons(uint16_t); uint32_t ntohl(uint32_t); uint16_t ntohs(uint16_t); // The following shall be declared as functions and may also be defined // as macros. Function prototypes shall be provided. in_addr_t inet_addr(const char *); char *inet_ntoa(struct in_addr); const char *inet_ntop( int, const void *restrict, char *restrict, socklen_t); int inet_pton( int, const char *restrict, void *restrict); // Inclusion of the <arpa/inet.h> header may also make visible all // symbols from <netinet/in.h> and <inttypes.h>. <file_sep>// fnmatch.h - filename-matching types // #include <fnmatch.h> // The <fnmatch.h> header shall define the following symbolic constants: enum { // The string does not match the specified pattern. FNM_NOMATCH, #define FNM_NOMATCH FNM_NOMATCH // <slash> in string only matches <slash> in pattern. FNM_PATHNAME, #define FNM_PATHNAME FNM_PATHNAME // Leading <period> in string must be exactly matched by <period> // in pattern. FNM_PERIOD, #define FNM_PERIOD FNM_PERIOD // Disable backslash escaping. FNM_NOESCAPE #define FNM_NOESCAPE FNM_NOESCAPE }; // The following shall be declared as a function and may also be defined // as a macro. A function prototype shall be provided. int fnmatch(const char *, const char *, int); <file_sep>// grp.h - group structure // #include <grp.h> // The <grp.h> header shall declare the group structure, which shall // include the following members: struct group { char *gr_name; // The name of the group. gid_t gr_gid; // Numerical group ID. char **gr_mem; // Pointer to a null-terminated array of character // pointers to member names. }; // The <grp.h> header shall define the gid_t and size_t types as // described in <sys/types.h>. #include <sys/types.h> // The following shall be declared as functions and may also be defined // as macros. Function prototypes shall be provided. // XSI. void endgrent(void); // XSI. struct group *getgrent(void); struct group *getgrgid(gid_t); int getgrgid_r(gid_t, struct group *, char *, size_t, struct group **); struct group *getgrnam(const char *); int getgrnam_r(const char *, struct group *, char *, size_t , struct group **); // XSI. void setgrent(void); <file_sep>// float.h - floating types // #include <float.h> /* The rounding mode for floating-point addition is characterized by the implementation-defined value of FLT_ROUNDS: -1 Indeterminable. 0 Toward zero. 1 To nearest. 2 Toward positive infinity. 3 Toward negative infinity. All other values for FLT_ROUNDS characterize implementation-defined rounding behavior. */ #define FLT_ROUNDS 1 /* The values of operations with floating operands and values subject to the usual arithmetic conversions and of floating constants are evaluated to a format whose range and precision may be greater than required by the type. The use of evaluation formats is characterized by the implementation-defined value of FLT_EVAL_METHOD: -1 Indeterminable. 0 Evaluate all operations and constants just to the range and precision of the type. 1 Evaluate operations and constants of type float and double to the range and precision of the double type; evaluate long double operations and constants to the range and precision of the long double type. 2 Evaluate all operations and constants to the range and precision of the long double type. All other negative values for FLT_EVAL_METHOD characterize implementation-defined behavior. */ #define FLT_EVAL_METHOD 0 /* The <float.h> header shall define the following values as constant expressions with implementation-defined values that are greater or equal in magnitude (absolute value) to those shown, with the same sign. */ // Radix of exponent representation, b. #define FLT_RADIX 2 // Number of base-FLT_RADIX digits in the floating-point // significand, p. #define FLT_MANT_DIG 24 #define DBL_MANT_DIG 53 #define LDBL_MANT_DIG 64 /* Number of decimal digits, n, such that any floating-point number in the widest supported floating type with pmax radix b digits can be rounded to a floating-point number with n decimal digits and back again without change to the value. */ #define DECIMAL_DIG 21 /* Number of decimal digits, q, such that any floating-point number with q decimal digits can be rounded into a floating- point number with p radix b digits and back again without change to the q decimal digits. */ #define FLT_DIG 6 #define DBL_DIG 15 #define LDBL_DIG 18 /* Minimum negative integer such that FLT_RADIX raised to that power minus 1 is a normalized floating-point number, emin. */ #define FLT_MIN_EXP (-125) #define DBL_MIN_EXP (-1021) #define LDBL_MIN_EXP (-16381) /* Minimum negative integer such that 10 raised to that power is in the range of normalized floating-point numbers. */ #define FLT_MIN_10_EXP (-37) #define DBL_MIN_10_EXP (-307) #define LDBL_MIN_10_EXP (-4931) /* Maximum integer such that FLT_RADIX raised to that power minus 1 is a representable finite floating-point number, emax. */ #define FLT_MAX_EXP 128 #define DBL_MAX_EXP 1024 #define LDBL_MAX_EXP 16384 /* CX: Additionally, FLT_MAX_EXP shall be at least as large as FLT_MANT_DIG, DBL_MAX_EXP shall be at least as large as DBL_MANT_DIG, and LDBL_MAX_EXP shall be at least as large as LDBL_MANT_DIG; which has the effect that FLT_MAX, DBL_MAX, and LDBL_MAX are integral. */ /* Maximum integer such that 10 raised to that power is in the range of representable finite floating-point numbers. */ #define FLT_MAX_10_EXP 38 #define DBL_MAX_10_EXP 308 #define LDBL_MAX_10_EXP 4932 /* The <float.h> header shall define the following values as constant expressions with implementation-defined values that are greater than or equal to those shown: */ // Maximum representable finite floating-point number. #define FLT_MAX 3.40282347e+38F #define DBL_MAX 1.7976931348623157e+308 #define LDBL_MAX 1.18973149535723176502e+4932L /* The <float.h> header shall define the following values as constant expressions with implementation-defined (positive) values that are less than or equal to those shown: */ // The difference between 1 and the least value greater than 1 // that is representable in the given floating-point type, b1-p. #define FLT_EPSILON 1.19209290e-7F #define DBL_EPSILON 2.2204460492503131e-16 #define LDBL_EPSILON 1.08420217248550443401e-19L // Minimum normalized positive floating-point number, bemin-1. #define FLT_MIN 1.17549435e-38F #define DBL_MIN 2.2250738585072014e-308 #define LDBL_MIN 3.36210314311209350626e-4932L /* All known hardware floating-point formats satisfy the property that the exponent range is larger than the number of mantissa digits. The ISO C standard permits a floating-point format where this property is not true, such that the largest finite value would not be integral; however, it is unlikely that there will ever be hardware support for such a floating-point format, and it introduces boundary cases that portable programs should not have to be concerned with (for example, a non-integral DBL_MAX means that ceil() would have to worry about overflow). Therefore, this standard imposes an additional requirement that the largest representable finite value is integral. */ <file_sep>A stub POSIX.1-2008 C library. See http://pubs.opengroup.org/onlinepubs/9699919799/ for the standard itself. <file_sep>// ctype.h - character types // #include <ctype.h> /* * Some of the functionality described on this header extends the ISO C * standard. Applications shall define the appropriate feature test macro to enable * the visibility of these symbols in this header. * * In the compilation of an application that #defines a feature test macro * specified by POSIX.1-2008, no header defined by POSIX.1-2008 shall be included * prior to the definition of the feature test macro. This restriction also * applies to any implementation-provided header in which these feature test * macros are used. If the definition of the macro does not precede the #include, * the result is undefined. * * Feature test macros shall begin with the <underscore> character ( '_' ). */ #ifdef _HAS_LOCALE_T #include <locale.h> // locale_t #endif // The following shall be declared as functions and may also be defined // as macros. Function prototypes shall be provided for use with ISO C // standard compilers. int isalnum(int); #ifdef _HAS_LOCALE_T int isalnum_l(int, locale_t); #endif int isalpha(int); #ifdef _HAS_LOCALE_T int isalpha_l(int, locale_t); #endif // XXX: XSI-conforming implementations shall set the symbolic constant // _XOPEN_UNIX to a value other than -1 and shall set the symbolic constant // _XOPEN_VERSION to the value 700. // int isascii(int); // XXX: XSI, obsolescent int isblank(int); #ifdef _HAS_LOCALE_T int isblank_l(int, locale_t); #endif int iscntrl(int); #ifdef _HAS_LOCALE_T int iscntrl_l(int, locale_t); #endif int isdigit(int); #ifdef _HAS_LOCALE_T int isdigit_l(int, locale_t); #endif int isgraph(int); #ifdef _HAS_LOCALE_T int isgraph_l(int, locale_t); #endif int islower(int); #ifdef _HAS_LOCALE_T int islower_l(int, locale_t); #endif int isprint(int); #ifdef _HAS_LOCALE_T int isprint_l(int, locale_t); #endif int ispunct(int); #ifdef _HAS_LOCALE_T int ispunct_l(int, locale_t); #endif int isspace(int); #ifdef _HAS_LOCALE_T int isspace_l(int, locale_t); #endif int isupper(int); #ifdef _HAS_LOCALE_T int isupper_l(int, locale_t); #endif int isxdigit(int); #ifdef _HAS_LOCALE_T int isxdigit_l(int, locale_t); #endif // int toascii(int); // XXX: XSI, obsolescent int tolower(int); #ifdef _HAS_LOCALE_T int tolower_l(int, locale_t); #endif int toupper(int); #ifdef _HAS_LOCALE_T int toupper_l(int, locale_t); #endif // The <ctype.h> header shall define the following as macros: // int _toupper(int); // XXX: XSI, obsolescent // int _tolower(int); // XXX: XSI, obsolescent <file_sep>// complex.h - complex arithmetic // #include <complex.h> // The <complex.h> header shall define the following macros: // complex // Expands to _Complex. typedef _Complex complex; // Complex_I // Expands to a constant expression of type const float _Complex, // with the value of the imaginary unit (that is, a number i such // that i2=-1). typedef const float _Complex Complex_I; // imaginary // Expands to _Imaginary. typedef _Imaginary imaginary; // _Imaginary_I // Expands to a constant expression of type const float _Imaginary // with the value of the imaginary unit. typedef const float _Imaginary _Imaginary_I; // I // Expands to either _Imaginary_I or _Complex_I. If _Imaginary_I // is not defined, I expands to _Complex_I. typedef _Imaginary_I I; // The macros imaginary and _Imaginary_I shall be defined if and only if // the implementation supports imaginary types. // An application may undefine and then, perhaps, redefine the complex, // imaginary, and I macros. // The following shall be declared as functions and may also be defined // as macros. Function prototypes shall be provided. double cabs(double complex); float cabsf(float complex); long double cabsl(long double complex); double complex cacos(double complex); float complex cacosf(float complex); double complex cacosh(double complex); float complex cacoshf(float complex); long double complex cacoshl(long double complex); long double complex cacosl(long double complex); double carg(double complex); float cargf(float complex); long double cargl(long double complex); double complex casin(double complex); float complex casinf(float complex); double complex casinh(double complex); float complex casinhf(float complex); long double complex casinhl(long double complex); long double complex casinl(long double complex); double complex catan(double complex); float complex catanf(float complex); double complex catanh(double complex); float complex catanhf(float complex); long double complex catanhl(long double complex); long double complex catanl(long double complex); double complex ccos(double complex); float complex ccosf(float complex); double complex ccosh(double complex); float complex ccoshf(float complex); long double complex ccoshl(long double complex); long double complex ccosl(long double complex); double complex cexp(double complex); float complex cexpf(float complex); long double complex cexpl(long double complex); double cimag(double complex); float cimagf(float complex); long double cimagl(long double complex); double complex clog(double complex); float complex clogf(float complex); long double complex clogl(long double complex); double complex conj(double complex); float complex conjf(float complex); long double complex conjl(long double complex); double complex cpow(double complex, double complex); float complex cpowf(float complex, float complex); long double complex cpowl(long double complex, long double complex); double complex cproj(double complex); float complex cprojf(float complex); long double complex cprojl(long double complex); double creal(double complex); float crealf(float complex); long double creall(long double complex); double complex csin(double complex); float complex csinf(float complex); double complex csinh(double complex); float complex csinhf(float complex); long double complex csinhl(long double complex); long double complex csinl(long double complex); double complex csqrt(double complex); float complex csqrtf(float complex); long double complex csqrtl(long double complex); double complex ctan(double complex); float complex ctanf(float complex); double complex ctanh(double complex); float complex ctanhf(float complex); long double complex ctanhl(long double complex); long double complex ctanl(long double complex); // Values are interpreted as radians, not degrees. /* * The choice of I instead of i for the imaginary unit concedes to the * widespread use of the identifier i for other purposes. The * application can use a different identifier, say j, for the imaginary * unit by following the inclusion of the <complex.h> header with: * #undef I * #define j _Imaginary_I * An I suffix to designate imaginary constants is not required, as * multiplication by I provides a sufficiently convenient and more * generally useful notation for imaginary terms. The corresponding real * type for the imaginary unit is float, so that use of I for * algorithmic or notational convenience will not result in widening * types. * On systems with imaginary types, the application has the ability to * control whether use of the macro I introduces an imaginary type, by * explicitly defining I to be _Imaginary_I or _Complex_I. Disallowing * imaginary types is useful for some applications intended to run on * implementations without support for such types. * The macro _Imaginary_I provides a test for whether imaginary types * are supported. * The cis() function (cos(x) + I*sin(x)) was considered but rejected * because its implementation is easy and straightforward, even though * some implementations could compute sine and cosine more efficiently * in tandem. */ /* * The following function names and the same names suffixed with f or l * are reserved for future use, and may be added to the declarations in * the <complex.h> header. * * cerf() cexpm1() clog2() * cerfc() clog10() clgamma() * cexp2() clog1p() ctgamma() */ <file_sep>inttypes.h - fixed size integer types #include <inttypes.h> /* CX: Some of the functionality described on this reference page extends the ISO C standard. Applications shall define the appropriate feature test macro (see XSH The Compilation Environment) to enable the visibility of these symbols in this header. */ // The <inttypes.h> header shall include the <stdint.h> header. #include <stdint.h> /* The <inttypes.h> header shall define at least the following types: Structure type that is the type of the value returned by the imaxdiv() function. */ typedef struct { } imaxdiv_t; // CX: wchar_t as described in <stddef.h>. #include <stddef.h> /* XXX: Not implemented. The <inttypes.h> header shall define the following macros. Each expands to a character string literal containing a conversion specifier, possibly modified by a length modifier, suitable for use within the format argument of a formatted input/output function when converting the corresponding integer type. These macros have the general form of PRI (character string literals for the fprintf() and fwprintf() family of functions) or SCN (character string literals for the fscanf() and fwscanf() family of functions), followed by the conversion specifier, followed by a name corresponding to a similar type name in <stdint.h>. In these names, N represents the width of the type as described in <stdint.h>. For example, PRIdFAST32 can be used in a format string to print the value of an integer of type int_fast32_t. The fprintf() macros for signed integers are: PRIdN PRIdLEASTN PRIdFASTN PRIdMAX PRIdPTR PRIiN PRIiLEASTN PRIiFASTN PRIiMAX PRIiPTR The fprintf() macros for unsigned integers are: PRIoN PRIoLEASTN PRIoFASTN PRIoMAX PRIoPTR PRIuN PRIuLEASTN PRIuFASTN PRIuMAX PRIuPTR PRIxN PRIxLEASTN PRIxFASTN PRIxMAX PRIxPTR PRIXN PRIXLEASTN PRIXFASTN PRIXMAX PRIXPTR The fscanf() macros for signed integers are: SCNdN SCNdLEASTN SCNdFASTN SCNdMAX SCNdPTR SCNiN SCNiLEASTN SCNiFASTN SCNiMAX SCNiPTR The fscanf() macros for unsigned integers are: SCNoN SCNoLEASTN SCNoFASTN SCNoMAX SCNoPTR SCNuN SCNuLEASTN SCNuFASTN SCNuMAX SCNuPTR SCNxN SCNxLEASTN SCNxFASTN SCNxMAX SCNxPTR For each type that the implementation provides in <stdint.h>, the corresponding fprintf() and fwprintf() macros shall be defined and the corresponding fscanf() and fwscanf() macros shall be defined unless the implementation does not have a suitable modifier for the type. */ /* The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided. */ intmax_t imaxabs(intmax_t); imaxdiv_t imaxdiv(intmax_t, intmax_t); intmax_t strtoimax(const char *restrict, char **restrict, int); uintmax_t strtoumax(const char *restrict, char **restrict, int); intmax_t wcstoimax(const wchar_t *restrict, wchar_t **restrict, int); uintmax_t wcstoumax(const wchar_t *restrict, wchar_t **restrict, int); <file_sep>// iconv.h - codeset conversion facility // #include <iconv.h> // The <iconv.h> header shall define the following types: // Identifies the conversion from one codeset to another. typedef void *iconv_t; // As described in <sys/types.h>. #include <sys/types.h> // The following shall be declared as functions and may also be defined // as macros. Function prototypes shall be provided. size_t iconv(iconv_t, char **restrict, size_t *restrict, char **restrict, size_t *restrict); int iconv_close(iconv_t); iconv_t iconv_open(const char *, const char *); <file_sep>// assert.h - verify program assertion // #include <assert.h> /* * The <assert.h> header shall define the assert() macro. It refers to * the macro NDEBUG which is not defined in the header. If NDEBUG is * defined as a macro name before the inclusion of this header, the * assert() macro shall be defined simply as: * #define assert(ignore)((void) 0) * * Otherwise, the macro behaves as described in assert(). * The assert() macro shall be redefined according to the current state * of NDEBUG each time <assert.h> is included. * The assert() macro shall be implemented as a macro, not as a * function. If the macro definition is suppressed in order to access an actual * function, the behavior is undefined. */ extern void __assert_fail(const char *, const char *, int, const char *); // XXX: __func__ requires C99. #ifdef NDEBUG #define assert(ignore)((void) 0) #else #define assert(expr) \ ((expr) \ ? (void) 0 \ : __assert_fail(#expr, __FILE__, __LINE__, __func__)) #endif <file_sep>// glob.h - pathname pattern-matching types // #include <glob.h> // The <glob.h> header shall define the structures and symbolic // constants used by the glob() function. // The <glob.h> header shall define the glob_t structure type, which // shall include at least the following members: typedef struct { size_t gl_pathc; // Count of paths matched by pattern. char **gl_pathv; // Pointer to a list of matched pathnames. size_t gl_offs; // Slots to reserve at the beginning of gl_pathv. } glob_t; // The <glob.h> header shall define the size_t type as described in // <sys/types.h>. #include <sys/types.h> // The <glob.h> header shall define the following symbolic constants as // values for the flags argument: enum { // Append generated pathnames to those previously obtained. GLOB_APPEND, #define GLOB_APPEND GLOB_APPEND // Specify how many null pointers to add to the beginning of // gl_pathv. GLOB_DOOFFS, #define GLOB_DOOFFS GLOB_DOOFFS // Cause glob() to return on error. GLOB_ERR, #define GLOB_ERR GLOB_ERR // Each pathname that is a directory that matches pattern has a // <slash> appended. GLOB_MARK, #define GLOB_MARK GLOB_MARK // If pattern does not match any pathname, then return a list // consisting of only pattern. GLOB_NOCHECK, #define GLOB_NOCHECK GLOB_NOCHECK // Disable backslash escaping. GLOB_NOESCAPE, #define GLOB_NOESCAPE GLOB_NOESCAPE // Do not sort the pathnames returned. GLOB_NOSORT #define GLOB_NOSORT GLOB_NOSORT }; // The <glob.h> header shall define the following symbolic constants as // error return values: enum { // The scan was stopped because GLOB_ERR was set or (*errfunc)() // returned non-zero. GLOB_ABORTED, #define GLOB_ABORTED GLOB_ABORTED // The pattern does not match any existing pathname, and // GLOB_NOCHECK was not set in flags. GLOB_NOMATCH, #define GLOB_NOMATCH GLOB_NOMATCH // An attempt to allocate memory failed. GLOB_NOSPACE #define GLOB_NOSPACE GLOB_NOSPACE }; // The following shall be declared as functions and may also be defined // as macros. Function prototypes shall be provided. int glob( const char *restrict, int, int(*)(const char *, int), glob_t *restrict); void globfree(glob_t *); <file_sep>// fenv.h - floating-point environment // #include <fenv.h> /* The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1-2008 defers to the ISO C standard. */ // The <fenv.h> header shall define the following data types through // typedef: /* Represents the entire floating-point environment. The floating- point environment refers collectively to any floating-point status flags and control modes supported by the implementation. */ // XXX: No fields are defined yet. typedef struct { } fenv_t; /* Represents the floating-point status flags collectively, including any status the implementation associates with the flags. A floating-point status flag is a system variable whose value is set (but never cleared) when a floating-point exception is raised, which occurs as a side-effect of exceptional floating-point arithmetic to provide auxiliary information. A floating-point control mode is a system variable whose value may be set by the user to affect the subsequent behavior of floating-point arithmetic. fexcept_t does not have to be an integer type. Its values must be obtained by a call to fegetexceptflag(), and cannot be created by logical operations from the exception macros. An implementation might simply implement fexcept_t as an int and use the representations reflected by the exception macros, but is not required to; other representations might contain extra information about the exceptions. fexcept_t might be a struct with a member for each exception (that might hold the address of the first or last floating-point instruction that caused that exception). The ISO/IEC 9899:1999 standard makes no claims about the internals of an fexcept_t, and so the user cannot inspect it. */ // XXX: No fields are defined yet. typedef struct { } fexcept_t; /* The <fenv.h> header shall define each of the following macros if and only if the implementation supports the floating-point exception by means of the floating-point functions feclearexcept(), fegetexceptflag(), feraiseexcept(), fesetexceptflag(), and fetestexcept(). The defined macros shall expand to integer constant expressions with values that are bitwise-distinct. */ #define FE_DIVBYZERO 0x01 #define FE_INEXACT 0x02 #define FE_INVALID 0x04 #define FE_OVERFLOW 0x08 #define FE_UNDERFLOW 0x10 /* MX: If the implementation supports the IEC 60559 Floating-Point option, all five macros shall be defined. Additional implementation-defined floating-point exceptions with macros beginning with FE_ and an uppercase letter may also be specified by the implementation. */ /* The <fenv.h> header shall define the macro FE_ALL_EXCEPT as the bitwise-inclusive OR of all floating-point exception macros defined by the implementation, if any. If no such macros are defined, then the macro FE_ALL_EXCEPT shall be defined as zero. */ #define FE_ALL_EXCEPT \ (FE_DIVBYZERO | FE_INEXACT | FE_INVALID | FE_OVERFLOW | FE_UNDERFLOW) /* The <fenv.h> header shall define each of the following macros if and only if the implementation supports getting and setting the represented rounding direction by means of the fegetround() and fesetround() functions. The defined macros shall expand to integer constant expressions whose values are distinct non-negative values. */ enum { FE_DOWNWARD, #define FE_DOWNWARD FE_DOWNWARD FE_TONEAREST, #define FE_TONEAREST FE_TONEAREST FE_TOWARDZERO, #define FE_TOWARDZERO FE_TOWARDZERO FE_UPWARD #define FE_UPWARD FE_UPWARD }; /* MX: If the implementation supports the IEC 60559 Floating-Point option, all four macros shall be defined. Additional implementation-defined rounding directions with macros beginning with FE_ and an uppercase letter may also be specified by the implementation. */ /* The <fenv.h> header shall define the following macro, which represents the default floating-point environment (that is, the one installed at program startup) and has type pointer to const-qualified fenv_t. It can be used as an argument to the functions within the <fenv.h> header that manage the floating-point environment. */ #define FE_DFL_ENV ((const fenv_t *) -1) /* The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided. */ int feclearexcept(int); int fegetenv(fenv_t *); int fegetexceptflag(fexcept_t *, int); int fegetround(void); int feholdexcept(fenv_t *); int feraiseexcept(int); int fesetenv(const fenv_t *); int fesetexceptflag(const fexcept_t *, int); int fesetround(int); int fetestexcept(int); int feupdateenv(const fenv_t *); /* The FENV_ACCESS pragma provides a means to inform the implementation when an application might access the floating-point environment to test floating-point status flags or run under non-default floating- point control modes. The pragma shall occur either outside external declarations or preceding all explicit declarations and statements inside a compound statement. When outside external declarations, the pragma takes effect from its occurrence until another FENV_ACCESS pragma is encountered, or until the end of the translation unit. When inside a compound statement, the pragma takes effect from its occurrence until another FENV_ACCESS pragma is encountered (including within a nested compound statement), or until the end of the compound statement; at the end of a compound statement the state for the pragma is restored to its condition just before the compound statement. If this pragma is used in any other context, the behavior is undefined. If part of an application tests floating-point status flags, sets floating-point control modes, or runs under non-default mode settings, but was translated with the state for the FENV_ACCESS pragma off, the behavior is undefined. The default state (on or off) for the pragma is implementation-defined. (When execution passes from a part of the application translated with FENV_ACCESS off to a part translated with FENV_ACCESS on, the state of the floating-point status flags is unspecified and the floating-point control modes have their default settings.) This header is designed to support the floating-point exception status flags and directed-rounding control modes required by the IEC 60559:1989 standard, and other similar floating-point state information. Also it is designed to facilitate code portability among all systems. Certain application programming conventions support the intended model of use for the floating-point environment: * A function call does not alter its caller's floating-point control modes, clear its caller's floating-point status flags, nor depend on the state of its caller's floating-point status flags unless the function is so documented. * A function call is assumed to require default floating-point control modes, unless its documentation promises otherwise. * A function call is assumed to have the potential for raising floating-point exceptions, unless its documentation promises otherwise. With these conventions, an application can safely assume default floating-point control modes (or be unaware of them). The responsibilities associated with accessing the floating-point environment fall on the application that does so explicitly. Even though the rounding direction macros may expand to constants corresponding to the values of FLT_ROUNDS, they are not required to do so. For example: #include <fenv.h> void f(double x) { #pragma STDC FENV_ACCESS ON void g(double); void h(double); // ... g(x + 1); h(x + 1); // ... } If the function g() might depend on status flags set as a side-effect of the first x+1, or if the second x+1 might depend on control modes set as a side-effect of the call to function g(), then the application shall contain an appropriately placed invocation as follows: #pragma STDC FENV_ACCESS ON Exception and Rounding Macros Macros corresponding to unsupported modes and rounding directions are not defined by the implementation and must not be defined by the application. An application might use #ifdef to test for this. */ <file_sep>// cpio.h - cpio archive values // #include <cpio.h> // The <cpio.h> header shall define the symbolic constants needed by the // c_mode field of the cpio archive format. #define C_IRUSR 0000400 // Read by owner. #define C_IWUSR 0000200 // Write by owner. #define C_IXUSR 0000100 // Execute by owner. #define C_IRGRP 0000040 // Read by group. #define C_IWGRP 0000020 // Write by group. #define C_IXGRP 0000010 // Execute by group. #define C_IROTH 0000004 // Read by others. #define C_IWOTH 0000002 // Write by others. #define C_IXOTH 0000001 // Execute by others. #define C_ISUID 0004000 // Set user ID. #define C_ISGID 0002000 // Set group ID. #define C_ISVTX 0001000 // On directories, restricted deletion flag. #define C_ISDIR 0040000 // Directory. #define C_ISFIFO 0010000 // FIFO. #define C_ISREG 0100000 // Regular file. #define C_ISBLK 0060000 // Block special. #define C_ISCHR 0020000 // Character special. #define C_ISCTG 0110000 // Reserved. #define C_ISLNK 0120000 // Symbolic link. #define C_ISSOCK 0140000 // Socket. #define MAGIC "070707" <file_sep>// fcntl.h - file control options // #include <fcntl.h> /* The <fcntl.h> header shall define the following symbolic constants for the cmd argument used by fcntl(). The values shall be unique and shall be suitable for use in #if preprocessing directives. */ enum { // Duplicate file descriptor. F_DUPFD, #define F_DUPFD F_DUPFD // Duplicate file descriptor with the close-on- exec flag // FD_CLOEXEC set. F_DUPFD_CLOEXEC, #define F_DUPFD_CLOEXEC F_DUPFD_CLOEXEC // Get file descriptor flags. F_GETFD, #define F_GETFD F_GETFD // Set file descriptor flags. F_SETFD, #define F_SETFD F_SETFD // Get file status flags and file access modes. F_GETFL, #define F_GETFL F_GETFL // Set file status flags. F_SETFL, #define F_SETFL F_SETFL // Get record locking information. F_GETLK, #define F_GETLK F_GETLK // Set record locking information. F_SETLK, #define F_SETLK F_SETLK // Set record locking information; wait if blocked. F_SETLKW, #define F_SETLKW F_SETLKW // Get process or process group ID to receive SIGURG signals. F_GETOWN, #define F_GETOWN F_GETOWN // Set process or process group ID to receive SIGURG signals. F_SETOWN #define F_SETOWN F_SETOWN }; /* The <fcntl.h> header shall define the following symbolic constant used for the fcntl() file descriptor flags, which shall be suitable for use in #if preprocessing directives. Close the file descriptor upon execution of an exec family function. */ #define FD_CLOEXEC 1 /* The <fcntl.h> header shall also define the following symbolic constants for the l_type argument used for record locking with fcntl (). The values shall be unique and shall be suitable for use in #if preprocessing directives. */ enum { // Shared or read lock. F_RDLCK, #define F_RDLCK F_RDLCK // Unlock. F_UNLCK, #define F_UNLCK F_UNLCK // Exclusive or write lock. F_WRLCK #define F_WRLCK F_WRLCK }; /* The <fcntl.h> header shall define the values used for l_whence, SEEK_SET, SEEK_CUR, and SEEK_END as described in <stdio.h>. */ #include <stdio.h> /* The <fcntl.h> header shall define the following symbolic constants as file creation flags for use in the oflag value to open() and openat (). The values shall be bitwise-distinct and shall be suitable for use in #if preprocessing directives. */ // The FD_CLOEXEC flag associated with the new descriptor shall be // set to close the file descriptor upon execution of an exec // family function. #define O_CLOEXEC 0x01 // Create file if it does not exist. #define O_CREAT 0x02 // Fail if not a directory. #define O_DIRECTORY 0x04 // Exclusive use flag. #define O_EXCL 0x08 // Do not assign controlling terminal. #define O_NOCTTY 0x10 // Do not follow symbolic links. #define O_NOFOLLOW 0x20 // Truncate flag. #define O_TRUNC O_TRUNC 0x40 // Set the termios structure terminal parameters to a state that // provides conforming behavior; see Parameters_that_Can_be_Set. // // The O_TTY_INIT flag can have the value zero and in this case it need // not be bitwise-distinct from the other flags. #define O_TTY_INIT 0 /* The <fcntl.h> header shall define the following symbolic constants for use as file status flags for open(), openat(), and fcntl(). The values shall be suitable for use in #if preprocessing directives. */ enum { // Set append mode. O_APPEND, #define APPEND APPEND // SIO: Write according to synchronized I/O data integrity completion. O_DSYNC, #define O_DSYNC O_DSYNC // Non-blocking mode. O_NONBLOCK, #define O_NONBLOCK O_NONBLOCK // SIO: Synchronized read I/O operations. O_RSYNC, #define O_RSYNC O_RSYNC // Write according to synchronized I/O file integrity completion. O_SYNC #define O_SYNC O_SYNC }; /* The <fcntl.h> header shall define the following symbolic constant for use as the mask for file access modes. The value shall be suitable for use in #if preprocessing directives. Mask for file access modes. */ #define O_ACCMODE 0x7 /* The <fcntl.h> header shall define the following symbolic constants for use as the file access modes for open(), openat(), and fcntl(). The values shall be unique, except that O_EXEC and O_SEARCH may have equal values. The values shall be suitable for use in #if preprocessing directives. */ enum { // Open for execute only (non-directory files). The result is // unspecified if this flag is applied to a directory. O_EXEC, #define O_EXEC O_EXEC // Open for reading only. O_RDONLY, #define O_RDONLY O_RDONLY // Open for reading and writing. O_RDWR, #define O_RDWR O_RDWR // Open directory for search only. The result is unspecified if // this flag is applied to a non-directory file. O_SEARCH, #define O_SEARCH O_SEARCH // Open for writing only. O_WRONLY #define O_WRONLY O_WRONLY }; /* The <fcntl.h> header shall define the symbolic constants for file modes for use as values of mode_t as described in <sys/stat.h>. */ #include <sys/stat.h> enum { /* The <fcntl.h> header shall define the following symbolic constant as a special value used in place of a file descriptor for the *at() functions which take a directory file descriptor as a parameter: Use the current working directory to determine the target of relative file paths. */ AT_FDCWD, #define AT_FDCWD AT_FDCWD /* The <fcntl.h> header shall define the following symbolic constant as a value for the flag used by faccessat(): Check access using effective user and group ID. */ AT_EACCESS, #define AT_EACCESS AT_EACCESS /* The <fcntl.h> header shall define the following symbolic constant as a value for the flag used by fstatat(), fchmodat(), fchownat(), and utimensat(): Do not follow symbolic links. */ AT_SYMLINK_NOFOLLOW, #define AT_SYMLINK_NOFOLLOW AT_SYMLINK_NOFOLLOW /* The <fcntl.h> header shall define the following symbolic constant as a value for the flag used by linkat(): Follow symbolic link. */ AT_SYMLINK_FOLLOW, #define AT_SYMLINK_FOLLOW AT_SYMLINK_FOLLOW /* The <fcntl.h> header shall define the following symbolic constant as a value for the flag used by unlinkat(): Remove directory instead of file. */ AT_REMOVEDIR #define AT_REMOVEDIR AT_REMOVEDIR }; /* ADV: The <fcntl.h> header shall define the following symbolic constants for the advice argument used by posix_fadvise(): */ enum { // The application expects that it will not access the specified // data in the near future. POSIX_FADV_DONTNEED, #define POSIX_FADV_DONTNEED POSIX_FADV_DONTNEED // The application expects to access the specified data once and // then not reuse it thereafter. POSIX_FADV_NOREUSE, #define POSIX_FADV_NOREUSE POSIX_FADV_NOREUSE // The application has no advice to give on its behavior with // respect to the specified data. It is the default characteristic // if no advice is given for an open file. POSIX_FADV_NORMAL, #define POSIX_FADV_NORMAL POSIX_FADV_NORMAL // The application expects to access the specified data in a // random order. POSIX_FADV_RANDOM, #define POSIX_FADV_RANDOM POSIX_FADV_RANDOM // The application expects to access the specified data // sequentially from lower offsets to higher offsets. POSIX_FADV_SEQUENTIAL, #define POSIX_FADV_SEQUENTIAL POSIX_FADV_SEQUENTIAL // The application expects to access the specified data in the // near future. POSIX_FADV_WILLNEED #define POSIX_FADV_WILLNEED POSIX_FADV_WILLNEED }; /* The <fcntl.h> header shall define the flock structure describing a file lock. It shall include the following members: */ struct flock { short l_type; // Type of lock; F_RDLCK, F_WRLCK, F_UNLCK. short l_whence; // Flag for starting offset. off_t l_start; // Relative offset in bytes. off_t l_len; // Size; if 0 then until EOF. pid_t l_pid; // Process ID of the process holding the lock; returned // with F_GETLK. }; /* The <fcntl.h> header shall define the mode_t, off_t, and pid_t types as described in <sys/types.h>. */ #include <sys/types.h> /* The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided. */ int creat(const char *, mode_t); int fcntl(int, int, ...); int open(const char *, int, ...); int openat(int, const char *, int, ...); // ADV. int posix_fadvise(int, off_t, off_t, int); int posix_fallocate(int, off_t, off_t); /* Inclusion of the <fcntl.h> header may also make visible all symbols from <sys/stat.h> and <unistd.h>. */ <file_sep>// aio.h - asynchronous input and output // #include <aio.h> // off_t, pthread_attr_t, size_t, and ssize_t. #include <sys/types.h> // struct sigevent. #include <signal.h> // The tag sigevent shall be declared as naming an incomplete structure type, // the contents of which are described in the <signal.h> header. typedef struct sigevent sigevent; // struct timespec. #include <time.h> struct aiocb { int aio_fildes // File descriptor. off_t aio_offset // File offset. volatile void *aio_buf // Location of buffer. size_t aio_nbytes // Length of transfer. int aio_reqprio // Request priority offset. struct sigevent aio_sigevent // Signal number and value. int aio_lio_opcode // Operation to be performed. }; // Symbolic constants. enum { // A return value indicating that all requested operations have been canceled. AIO_CANCELED, #define AIO_CANCELED AIO_CANCELED // A return value indicating that some of the requested operations could not // be canceled since they are in progress. AIO_NOTCANCELED, #define AIO_NOTCANCELED AIO_NOTCANCELED // A return value indicating that none of the requested operations could be // canceled since they are already complete. AIO_ALLDONE #define AIO_ALLDONE AIO_ALLDONE }; enum { // A lio_listio() element operation option indicating that no transfer is // requested. LIO_NOP, #define LIO_NOP LIO_NOP // A lio_listio() synchronization operation indicating that the calling thread // is to continue execution while the lio_listio() operation is being // performed, and no notification is given when the operation is complete. LIO_NOWAIT, #define LIO_NOWAIT LIO_NOWAIT // A lio_listio() element operation option requesting a read. LIO_READ, #define LIO_READ LIO_READ // A lio_listio() synchronization operation indicating that the calling thread // is to suspend until the lio_listio() operation is complete. LIO_WAIT, #define LIO_WAIT LIO_WAIT // A lio_listio() element operation option requesting a write. LIO_WRITE #define LIO_WRITE LIO_WRITE }; // Functions, which may also be defined as macros. Function prototypes shall be // provided. int aio_cancel(int, struct aiocb *); int aio_error(const struct aiocb *); int aio_fsync(int, struct aiocb *); int aio_read(struct aiocb *); ssize_t aio_return(struct aiocb *); int aio_suspend( const struct aiocb *const [], int, const struct timespec *); int aio_write(struct aiocb *); int lio_listio( int, struct aiocb *restrict const [restrict], int, struct sigevent *restrict); // Inclusion of the <aio.h> header may make visible symbols defined in the // headers <fcntl.h>, <signal.h>, and <time.h>. <file_sep>// iso646.h - alternative spellings // #include <iso646.h> /* CX: The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1-2008 defers to the ISO C standard. */ /* The <iso646.h> header shall define the following eleven macros (on the left) that expand to the corresponding tokens (on the right): */ #define and && #define and_eq &= #define bitand & #define bitor | #define compl ~ #define not ! #define not_eq != #define or || #define or_eq |= #define xor ^ #define xor_eq ^= <file_sep>// errno.h - system error numbers // #include <errno.h> /* Some of the functionality described on this reference page extends the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1-2008 defers to the ISO C standard. The ISO C standard only requires the symbols [EDOM], [EILSEQ], and [ERANGE] to be defined. */ /* The <errno.h> header shall provide a declaration or definition for errno. The symbol errno shall expand to a modifiable lvalue of type int. It is unspecified whether errno is a macro or an identifier declared with external linkage. If a macro definition is suppressed in order to access an actual object, or a program defines an identifier with the name errno, the behavior is undefined. */ extern int errno; /* The <errno.h> header shall define the following macros which shall expand to integer constant expressions with type int, distinct positive values (except as noted below), and which shall be suitable for use in #if preprocessing directives: */ enum { // Argument list too long. E2BIG, #define E2BIG E2BIG // Permission denied. EACCES, #define EACCES EACCES // Address in use. EADDRINUSE, #define EADDRINUSE EADDRINUSE // Address not available. EADDRNOTAVAIL, #define EADDRNOTAVAIL EADDRNOTAVAIL // Address family not supported. EAFNOSUPPORT, #define EAFNOSUPPORT EAFNOSUPPORT // Resource unavailable, try again (may be the same value as // EWOULDBLOCK). EAGAIN, #define EAGAIN EAGAIN // Connection already in progress. EALREADY, #define EALREADY EALREADY // Bad file descriptor. EBADF, #define EBADF EBADF // Bad message. EBADMSG, #define EBADMSG EBADMSG // Device or resource busy. EBUSY, #define EBUSY EBUSY // Operation canceled. ECANCELED, #define ECANCELED ECANCELED // No child processes. ECHILD, #define ECHILD ECHILD // Connection aborted. ECONNABORTED, #define ECONNABORTED ECONNABORTED // Connection refused. ECONNREFUSED, #define ECONNREFUSED ECONNREFUSED // Connection reset. ECONNRESET, #define ECONNRESET ECONNRESET // Resource deadlock would occur. EDEADLK, #define EDEADLK EDEADLK // Destination address required. EDESTADDRREQ, #define EDESTADDRREQ EDESTADDRREQ // Mathematics argument out of domain of function. EDOM, #define EDOM EDOM // Reserved. EDQUOT, #define EDQUOT EDQUOT // File exists. EEXIST, #define EEXIST EEXIST // Bad address. EFAULT, #define EFAULT EFAULT // File too large. EFBIG, #define EFBIG EFBIG // Host is unreachable. EHOSTUNREACH, #define EHOSTUNREACH EHOSTUNREACH // Identifier removed. EIDRM, #define EIDRM EIDRM // Illegal byte sequence. EILSEQ, #define EILSEQ EILSEQ // Operation in progress. EINPROGRESS, #define EINPROGRESS EINPROGRESS // Interrupted function. EINTR, #define EINTR EINTR // Invalid argument. EINVAL, #define EINVAL EINVAL // I/O error. EIO, #define EIO EIO // Socket is connected. EISCONN, #define EISCONN EISCONN // Is a directory. EISDIR, #define EISDIR EISDIR // Too many levels of symbolic links. ELOOP, #define ELOOP ELOOP // File descriptor value too large. EMFILE, #define EMFILE EMFILE // Too many links. EMLINK, #define EMLINK EMLINK // Message too large. EMSGSIZE, #define EMSGSIZE EMSGSIZE // Reserved. EMULTIHOP, #define EMULTIHOP EMULTIHOP // Filename too long. ENAMETOOLONG, #define ENAMETOOLONG ENAMETOOLONG // Network is down. ENETDOWN, #define ENETDOWN ENETDOWN // Connection aborted by network. ENETRESET, #define ENETRESET ENETRESET // Network unreachable. ENETUNREACH, #define ENETUNREACH ENETUNREACH // Too many files open in system. ENFILE, #define ENFILE ENFILE // No buffer space available. ENOBUFS, #define ENOBUFS ENOBUFS // XSR: No message is available on the STREAM // head read queue. Obsolescent. ENODATA, #define ENODATA ENODATA // No such device. ENODEV, #define ENODEV ENODEV // No such file or directory. ENOENT, #define ENOENT ENOENT // Executable file format error. ENOEXEC, #define ENOEXEC ENOEXEC // No locks available. ENOLCK, #define ENOLCK ENOLCK // Reserved. ENOLINK, #define ENOLINK ENOLINK // Not enough space. ENOMEM, #define ENOMEM ENOMEM // No message of the desired type. ENOMSG, #define ENOMSG ENOMSG // Protocol not available. ENOPROTOOPT, #define ENOPROTOOPT ENOPROTOOPT // No space left on device. ENOSPC, #define ENOSPC ENOSPC // XSR: No STREAM resources. Obsolescent. ENOSR, #define ENOSR ENOSR // XSR: Not a STREAM. Obsolescent. ENOSTR, #define ENOSTR ENOSTR // Function not supported. ENOSYS, #define ENOSYS ENOSYS // The socket is not connected. ENOTCONN, #define ENOTCONN ENOTCONN // Not a directory or a symbolic link to a directory. ENOTDIR, #define ENOTDIR ENOTDIR // Directory not empty. ENOTEMPTY, #define ENOTEMPTY ENOTEMPTY // State not recoverable. ENOTRECOVERABLE, #define ENOTRECOVERABLE ENOTRECOVERABLE // Not a socket. ENOTSOCK, #define ENOTSOCK ENOTSOCK // Not supported (may be the same value as EOPNOTSUPP). ENOTSUP, #define ENOTSUP ENOTSUP // Inappropriate I/O control operation. ENOTTY, #define ENOTTY ENOTTY // No such device or address. ENXIO, #define ENXIO ENXIO // Operation not supported on socket (may be the same value as // ENOTSUP). EOPNOTSUPP, #define EOPNOTSUPP EOPNOTSUPP // Value too large to be stored in data type. EOVERFLOW, #define EOVERFLOW EOVERFLOW // Previous owner died. EOWNERDEAD, #define EOWNERDEAD EOWNERDEAD // Operation not permitted. EPERM, #define EPERM EPERM // Broken pipe. EPIPE, #define EPIPE EPIPE // Protocol error. EPROTO, #define EPROTO EPROTO // Protocol not supported. EPROTONOSUPPORT, #define EPROTONOSUPPORT EPROTONOSUPPORT // Protocol wrong type for socket. EPROTOTYPE, #define EPROTOTYPE EPROTOTYPE // Result too large. ERANGE, #define ERANGE ERANGE // Read-only file system. EROFS, #define EROFS EROFS // Invalid seek. ESPIPE, #define ESPIPE ESPIPE // No such process. ESRCH, #define ESRCH ESRCH // Reserved. ESTALE, #define ESTALE ESTALE // XSR: Stream ioctl() timeout. Obsolescent. ETIME, #define ETIME ETIME // Connection timed out. ETIMEDOUT, #define ETIMEDOUT ETIMEDOUT // Text file busy. ETXTBSY, #define ETXTBSY ETXTBSY // Operation would block (may be the same value as EAGAIN). EWOULDBLOCK, #define EWOULDBLOCK EWOULDBLOCK // Cross-device link. EXDEV, #define EXDEV EXDEV }; <file_sep>// dirent.h - format of directory entries // #include <dirent.h> // The internal format of directories is unspecified. // A type representing a directory stream. The DIR type may be an // incomplete type. // // XXX: Not adding any fields for now since POSIX doesn't specify that. struct __dirstream {}; typedef struct __dirstream DIR; // XXX: XSI. // The <dirent.h> header shall define the ino_t type as described in // <sys/types.h>. /* The array d_name is of unspecified size, which shall contain a filename of at * most {NAME_MAX} bytes followed by a terminating null byte. * * The name of an array of char of an unspecified size should not be * used as an lvalue. Use of: * sizeof(d_name) * is incorrect; use: * strlen(d_name) * instead. * The array of char d_name is not a fixed size. Implementations may * need to declare struct dirent with an array size for d_name of 1, but * the actual number of bytes provided matches (or only slightly * exceeds) the length of the filename string. */ #define NAME_MAX 256 struct dirent { // XXX: XSI. // ino_t d_ino; // File serial number. char d_name[NAME_MAX]; // Filename string of entry. }; // The following shall be declared as functions and may also be defined // as macros. Function prototypes shall be provided. int alphasort( const struct dirent **, const struct dirent **); int closedir(DIR *); int dirfd(DIR *); DIR *fdopendir(int); DIR *opendir(const char *); struct dirent *readdir(DIR *); int readdir_r( DIR *restrict, struct dirent *restrict, struct dirent **restrict); void rewinddir(DIR *); int scandir( const char *, struct dirent ***, int (*)(const struct dirent *), int (*)(const struct dirent **, const struct dirent **)); /* XXX: XSI. * void seekdir(DIR *, long); * long telldir(DIR *); */ <file_sep>// dlfcn.h - dynamic linking // #include <dlfcn.h> // Constants for use in the construction of a dlopen() mode argument: enum { // Relocations are performed at an implementation-defined time. RTLD_LAZY, #define RTLD_LAZY RTLD_LAZY // Relocations are performed when the object is loaded. RTLD_NOW, #define RTLD_NOW RTLD_NOW // All symbols are available for relocation processing of other modules. RTLD_GLOBAL, #define RTLD_GLOBAL RTLD_GLOBAL // All symbols are not made available for relocation processing by // other modules. RTLD_LOCAL #define RTLD_LOCAL RTLD_LOCAL }; // The following shall be declared as functions and may also be defined // as macros. Function prototypes shall be provided. int dlclose(void *); char *dlerror(void); void *dlopen(const char *, int); void *dlsym(void *restrict, const char *restrict);
0245c94fe505505460015ea9c3a76bed798db26f
[ "Markdown", "C" ]
19
C
nkaretnikov/libstub
ae9d5524cdc94434b8885dd68974fa3abf89773d
21db6cb145f5eca795c1afbb290a77e36779e6e1
refs/heads/master
<repo_name>maccarini/first-neural-network<file_sep>/README.md # first-neural-network Basic neural network written in python, using numPy that predicts exam scores based on study hours and sleep hours. It shows a basic implementation of gradient descent and backpropagation for optimizing a cost function in a 3-layer neural network. <file_sep>/firstNeuralNetwork.py # -*- coding: utf-8 -*- """ Created on Fri May 24 15:07:32 2019 @author: Lucas """ # Importing libraries import numpy as np # Importing dataset and setting X and y variables X_original = np.array([[3.,4.],[2.,7.],[8.,4.], [8.,8.]]) # first column shows study hours, second shows sleep hours y_original = np.array([[5.5],[6.1],[6.4],[6.9]]) # shows test score on a scale from 0.0-7.0 # Normalizing data X = X_original/np.amax(X_original, axis=0) y = y_original/7.0 # Defining the architechture for the simple neural network inputLayerSize = 2 hiddenLayerSize = 3 outputLayerSize = 1 # Defining the activation function used in each layer (sigmoid) def sigmoid(z, deriv=False): if deriv: return np.exp(-z)/(1+(np.exp(-z)))**2 else: return 1/(1+np.exp(-z)) # Initializing weight matrices with normally distributed random numbers w1 = np.random.randn(inputLayerSize, hiddenLayerSize) - 1 w2 = np.random.randn(hiddenLayerSize, outputLayerSize) - 1 # Defining a for loop for each epoch that consists in forward propagation and backpropagation costVector = [] # an array that holds the cost values for each iteration costNumber = 0 for i in range(50000): # Calculating values for each layer z2 = X.dot(w1) a2 = sigmoid(z2) z3 = a2.dot(w2) y_hat = sigmoid(z3) # Calculating the cost function (C) error = y - y_hat C = sum((error)**2) / 2 costVector.append(C) if (i % 10000 == 0): print('Cost',costNumber,':', C) costNumber += 1 # Calculating the partial derivatives of the cost with respect to each of the weights (Gradient Descent) delta3 = (-error)* sigmoid(z3, deriv=True) dCdW2 = (a2.T).dot(delta3) delta2 = delta3.dot(w2.T) * sigmoid(z2, deriv=True) dCdW1 = (X.T).dot(delta2) # Updating the weight matrices w1 = w1 - (dCdW1) * 0.01 w2 = w2 - (dCdW2) * 0.01 # Visualizing the cost of each epoch import matplotlib.pyplot as plt plt.plot(costVector) plt.xlabel('Iteration') plt.ylabel('Cost') plt.title('Cost reduction') plt.show()
52b47a30ee604a731b395413506682deb2721ab9
[ "Markdown", "Python" ]
2
Markdown
maccarini/first-neural-network
5c6bb163d26b092054efd6dd63b1a4a6cabf3e85
42eb42c7909326151ac47ecb98374defcb366bb6
refs/heads/main
<file_sep><?php echo "Hello PHP. This is my website. Welcome!";
b5c8dab35561ff5b0c1843608b3aec23eb71a35a
[ "PHP" ]
1
PHP
vuongthanhtuan/php
f4e73aef7c9d51052b9c3ec437257851c6492a1f
8e040ad4ec1badd191d1e017884acb8d0d77f317
refs/heads/master
<file_sep>using JWT; using JWT.Algorithms; using JWT.Exceptions; using JWT.Serializers; using Newtonsoft.Json; using System; using System.Collections.Generic; namespace Eims.WebApi.Core { public class JwtTools { public static string Key { get; set; } = "wangzhenyang"; public static string Encode(Dictionary<string, object> payload, string key = null) { if (string.IsNullOrEmpty(key)) key = Key; payload.Add("timeout", DateTime.Now.AddDays(1)); IJsonSerializer jsonSerializer = new JsonNetSerializer();//json序列化 IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//base64加密编码器 IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//算法 IJwtEncoder jwtEncoder = new JwtEncoder(algorithm, jsonSerializer, urlEncoder); return jwtEncoder.Encode(payload, key); } public static Dictionary<string, object> Decode(string code, string key = null) { if (string.IsNullOrEmpty(key)) key = Key; try { IJsonSerializer jsonSerializer = new JsonNetSerializer();//json序列化 IDateTimeProvider provider = new UtcDateTimeProvider();//日期提供者 IJwtValidator jwtValidator = new JwtValidator(jsonSerializer, provider);//验证器 IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//base64加密编码器 IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//算法 IJwtDecoder jwtDecoder = new JwtDecoder(jsonSerializer, jwtValidator, urlEncoder, algorithm); var json = jwtDecoder.Decode(code, key, true); var result = JsonConvert.DeserializeObject<Dictionary<string, object>>(json); if ((DateTime)result["timeout"] < DateTime.Now) throw new Exception("jwtstring已经过期,必须重新登陆"); result.Remove("timeout"); return result; } catch (TokenExpiredException) { throw; } } } }<file_sep>using Eims.Models; namespace Eims.IDAL { public interface IArticleService : IBaseService<Article> { } } <file_sep>using Eims.Models; namespace Eims.IDAL { public interface IWageService : IBaseService<Wage> { } } <file_sep>using System; namespace Eims.Dto { public class StaffDto { public Nullable<int> RoleId { get; set; } public int Id { get; set; } public string Password { get; set; } public string Name { get; set; } public string Sex { get; set; } public string IDcard { get; set; } public string Phone { get; set; } public string Email { get; set; } public Nullable<System.DateTime> Birthday { get; set; } public string Address { get; set; } public string Hometown { get; set; } public string GraduatedSchool { get; set; } public string EducationLevel { get; set; } public string PoliticalStatus { get; set; } public string MaritalStatus { get; set; } public string HealthStatus { get; set; } public string WorkingState { get; set; } } } <file_sep>using Eims.Models; namespace Eims.IDAL { public interface IStaffService : IBaseService<Staff> { } } <file_sep>using System; namespace Eims.Dto { public class ArticleWithStaffDto { public int Id { get; set; } public Nullable<int> StaffId { get; set; } public string Staff_Name { get; set; } public string Title { get; set; } public string Content { get; set; } public Nullable<System.DateTime> CreateTime { get; set; } } } <file_sep>using Eims.Dto; using Eims.IBLL; using Eims.IDAL; using Eims.Models; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using Unity; namespace Eims.BLL { public class ArticleManager : IArticleManager { [Dependency] public IArticleService articleService { get; set; } [Dependency] public IStaffService staffService { get; set; } public async Task<int> _add(ArticleDto article) { return await articleService.InsertAsync(new Models.Article() { Content = article.Content, CreateTime = article.CreateTime, Id = article.Id, StaffId = article.StaffId, Title = article.Title }); } public async Task<int> _del(int id) { return await articleService.DeleteAsync(id); } public async Task<int> _edit(ArticleDto article) { return await articleService.UpdateAsync(new Models.Article() { Content = article.Content, CreateTime = article.CreateTime, Id = article.Id, StaffId = article.StaffId, Title = article.Title }); } public async Task<List<ArticleDto>> _getAll(string key) { IQueryable<Models.Article> query; if (key != null && key != "") query = articleService.GetAll().Where(m => m.Title.Contains(key)); else query = articleService.GetAll(); return await query.Select(m => new ArticleDto() { Id = m.Id, Content = m.Content, CreateTime = m.CreateTime, StaffId = m.StaffId, Title = m.Title }).ToListAsync(); } public async Task<ArticleDto> _getOne(int id) { Article m = await articleService.GetAll().FirstOrDefaultAsync(a => a.Id == id); return new ArticleDto() { Id = m.Id, Content = m.Content, CreateTime = m.CreateTime, StaffId = m.StaffId, Title = m.Title }; } public async Task<List<ArticleDto>> _getPage(int ps, int pi, string key) { IQueryable<Models.Article> query; if (key != null && key != "") query = articleService.GetAll().Where(m => m.Title.Contains(key)); else query = articleService.GetAll(); return await query.OrderBy(m => m.CreateTime).Skip(ps * pi).Take(ps).Select(m => new ArticleDto() { Id = m.Id, Content = m.Content, CreateTime = m.CreateTime, StaffId = m.StaffId, Title = m.Title }).ToListAsync(); } public async Task<int> _getRowCount(string key = null) { IQueryable<Models.Article> query; if (key != null && key != "") query = articleService.GetAll().Where(m => m.Title.Contains(key)); else query = articleService.GetAll(); return await query.CountAsync(); } public async Task<int> _add(List<ArticleDto> models) { foreach (ArticleDto model in models) { await articleService.InsertAsync(new Article() { Content = model.Content, CreateTime = model.CreateTime, Id = model.Id, StaffId = model.StaffId, Title = model.Title }, false); } return await articleService.Save(); } public async Task<List<ArticleWithStaffDto>> _getPageArticleWithStaff(int ps, int pi, string key = null) { var staffs = await staffService.GetAll().ToListAsync(); var articles = await articleService.GetAll().ToListAsync(); if (key != null && key != "") articles = await articleService.GetAll().Where(m => m.Title.Contains(key)).ToListAsync(); return articles.AsQueryable().OrderBy(m => m.Id).Skip(ps * pi).Take(ps).Join(staffs, a => a.StaffId, b => b.Id, (a, b) => new ArticleWithStaffDto() { Id = a.Id, StaffId = a.StaffId, Content = a.Content, CreateTime = a.CreateTime, Title = a.Title, Staff_Name = b.Name }).ToList(); } public async Task<List<ArticleWithStaffDto>> _getPageArticleWithStaff(int ps, int pi, int fkid) { var staffs = await staffService.GetAll().ToListAsync(); var articles = await articleService.GetAll().Where(m => m.StaffId == fkid).ToListAsync(); return articles.AsQueryable().OrderBy(m => m.Id).Skip(ps * pi).Take(ps).Join(staffs, a => a.StaffId, b => b.Id, (a, b) => new ArticleWithStaffDto() { Id = a.Id, StaffId = a.StaffId, Content = a.Content, CreateTime = a.CreateTime, Title = a.Title, Staff_Name = b.Name }).ToList(); } public async Task<ArticleWithStaffDto> _getOneArticleWithStaff(int id) { var staffs = await staffService.GetAll().ToListAsync(); var article = await articleService.GetAll().Where(m => m.Id == id).ToListAsync(); return article.AsQueryable().Join(staffs, a => a.StaffId, b => b.Id, (a, b) => new ArticleWithStaffDto() { Id = a.Id, StaffId = a.StaffId, Content = a.Content, CreateTime = a.CreateTime, Title = a.Title, Staff_Name = b.Name }).FirstOrDefault(); } } } <file_sep>using Eims.Dto; using Eims.IBLL; using Eims.IDAL; using Eims.Models; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using Unity; namespace Eims.BLL { public class AttendanceManager : IAttendanceManager { [Dependency] public IAttendanceService attendanceService { get; set; } public async Task<List<AttendanceDto>> _getAll(string key) { IQueryable<Models.Attendance> query; if (key != null && key != "") query = attendanceService.GetAll().Where(m => m.Name.Contains(key)); else query = attendanceService.GetAll(); return await query.Select(m => new AttendanceDto() { Id = m.Id, Name = m.Name, Money = m.Money, Remarks = m.Remarks }).ToListAsync(); } public async Task<int> _add(AttendanceDto attendance) { return await attendanceService.InsertAsync(new Attendance() { Money = attendance.Money, Name = attendance.Name, Remarks = attendance.Remarks }); } public async Task<int> _edit(AttendanceDto attendance) { return await attendanceService.UpdateAsync(new Attendance() { Id = attendance.Id, Name = attendance.Name, Money = attendance.Money, Remarks = attendance.Remarks }); } public async Task<int> _del(int id) { return await attendanceService.DeleteAsync(id); } public async Task<List<AttendanceDto>> _getPage(int ps, int pi, string key) { IQueryable<Models.Attendance> query; if (key != null && key != "") query = attendanceService.GetAll().Where(m => m.Name.Contains(key)); else query = attendanceService.GetAll(); return await query.OrderBy(m => m.Id).Skip(ps * pi).Take(ps).Select(m => new AttendanceDto() { Id = m.Id, Name = m.Name, Money = m.Money, Remarks = m.Remarks }).ToListAsync(); } public async Task<AttendanceDto> _getOne(int id) { Attendance attendance = await attendanceService.GetAll().FirstOrDefaultAsync(m => m.Id == id); return new AttendanceDto() { Id = attendance.Id, Name = attendance.Name, Money = attendance.Money, Remarks = attendance.Remarks }; } public async Task<int> _getRowCount(string key = null) { IQueryable<Models.Attendance> query; if (key != null && key != "") query = attendanceService.GetAll().Where(m => m.Name.Contains(key)); else query = attendanceService.GetAll(); return await query.CountAsync(); } public async Task<int> _add(List<AttendanceDto> models) { foreach (AttendanceDto model in models) { await attendanceService.InsertAsync(new Attendance() { Money = model.Money, Name = model.Name, Remarks = model.Remarks }, false); } return await attendanceService.Save(); } } } <file_sep>using Eims.IDAL; using Eims.Models; namespace Eims.DAL { public class AttendanceService : BaseService<Attendance>, IAttendanceService { public AttendanceService() : base(new EimsContext()) { } } } <file_sep>using Eims.Dto; using System.Collections.Generic; using System.Threading.Tasks; namespace Eims.IBLL { public interface ISuggestManager : IBaseManager<SuggestDto> { Task<List<SuggestWithStaffDto>> _getPageSuggestWithStaff(int ps, int pi, string key = null); Task<List<SuggestWithStaffDto>> _getPageSuggestWithStaff(int ps, int pi, int fkid); Task<SuggestWithStaffDto> _getOneSuggestWithStaff(int id); Task<List<SuggestDto>> _getPageByStaffId(int ps, int pi, int id); } } <file_sep>using Eims.Dto; using Eims.IBLL; using Eims.WebApi.Filter; using Eims.WebApi.Models; using Eims.WebApi.Models.Auth; using System.Threading.Tasks; using System.Web.Http; using Unity; namespace Eims.WebApi.Controllers { /// <summary> /// 必须登录 /// </summary> [WebApiExceptionFilter, RoutePrefix("api/private"), MainAuth] public class PrivateController : ApiController { [Dependency] public IStaffManager staffManager { get; set; } [Dependency] public IWageManager wageManager { get; set; } [Dependency] public ISuggestManager suggestManager { get; set; } /// <summary> /// 获取我的历史总工资单 /// </summary> /// <returns></returns> [HttpGet, Route("payroll")] public async Task<Result> Payroll() { UserIdentity my = (UserIdentity)User.Identity; return Result.Success(await wageManager._getPayrollByStaffId(my.Id)); } /// <summary> /// 获取我的所有的奖惩、日工资 /// </summary> /// <returns></returns> [HttpGet, Route("wages")] public async Task<Result> Wages() { UserIdentity my = (UserIdentity)User.Identity; return Result.Success(await wageManager._getPageByStaffId(10, 0, my.Id)); } /// <summary> /// 我的信息 /// </summary> /// <returns></returns> [HttpGet, Route("info")] public async Task<Result> Info() { UserIdentity my = (UserIdentity)User.Identity; return Result.Success(await staffManager._getOne(my.Id)); } /// <summary> /// 我的反馈 /// </summary> /// <returns></returns> [HttpGet, Route("suggests")] public async Task<Result> Suggests() { UserIdentity my = (UserIdentity)User.Identity; return Result.Success(await suggestManager._getPageByStaffId(10, 0, my.Id)); } /// <summary> /// 修改我的信息 /// </summary> /// <param name="model"></param> /// <returns></returns> [HttpPut, Route("editinfo")] public async Task<Result> EditInfo(StaffDto model) { UserIdentity my = (UserIdentity)User.Identity; model.Id = my.Id; return Result.Success(await staffManager._edit(model)); } /// <summary> /// 添加反馈 /// </summary> /// <param name="model"></param> /// <returns></returns> [HttpPost, Route("addsuggest")] public async Task<Result> AddSuggesr(SuggestDto model) { UserIdentity my = (UserIdentity)User.Identity; model.StaffId = my.Id; return Result.Success(await suggestManager._add(model)); } } }<file_sep>using Eims.IDAL; using Eims.Models; namespace Eims.DAL { public class SuggestService : BaseService<Suggest>, ISuggestService { public SuggestService() : base(new EimsContext()) { } } } <file_sep>using Eims.Dto; using Eims.IBLL; using Eims.IDAL; using Eims.Models; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using Unity; namespace Eims.BLL { public class StaffManager : IStaffManager { [Dependency] public IStaffService staffService { get; set; } public async Task<int> _add(StaffDto staffDto) { return await staffService.InsertAsync(new Models.Staff() { Address = staffDto.Address, Birthday = staffDto.Birthday, EducationLevel = staffDto.EducationLevel, Email = staffDto.Email, GraduatedSchool = staffDto.GraduatedSchool, HealthStatus = staffDto.HealthStatus, Hometown = staffDto.Hometown, Id = staffDto.Id, IDcard = staffDto.IDcard, MaritalStatus = staffDto.MaritalStatus, Name = staffDto.Name, Password = <PASSWORD>, Phone = staffDto.Phone, RoleId = staffDto.RoleId, PoliticalStatus = staffDto.PoliticalStatus, Sex = staffDto.Sex, WorkingState = staffDto.WorkingState }); } public async Task<int> _del(int id) { return await staffService.DeleteAsync(id); } public async Task<int> _edit(StaffDto staffDto) { return await staffService.UpdateAsync(new Models.Staff() { Address = staffDto.Address, Birthday = staffDto.Birthday, EducationLevel = staffDto.EducationLevel, Email = staffDto.Email, GraduatedSchool = staffDto.GraduatedSchool, HealthStatus = staffDto.HealthStatus, Hometown = staffDto.Hometown, Id = staffDto.Id, IDcard = staffDto.IDcard, MaritalStatus = staffDto.MaritalStatus, Name = staffDto.Name, Password = <PASSWORD>Dto.Password, Phone = staffDto.Phone, RoleId = staffDto.RoleId, PoliticalStatus = staffDto.PoliticalStatus, Sex = staffDto.Sex, WorkingState = staffDto.WorkingState }); } public async Task<List<StaffDto>> _getAll(string key) { IQueryable<Models.Staff> query; if (key != null && key != "") query = staffService.GetAll().Where(m => m.Name.Contains(key) || m.IDcard == key); else query = staffService.GetAll(); return await query.Select(m => new StaffDto() { Address = m.Address, Birthday = m.Birthday, EducationLevel = m.EducationLevel, Email = m.Email, GraduatedSchool = m.GraduatedSchool, HealthStatus = m.HealthStatus, Hometown = m.Hometown, Id = m.Id, IDcard = m.IDcard, MaritalStatus = m.MaritalStatus, Name = m.Name, Password = <PASSWORD>, Phone = m.Phone, RoleId = m.RoleId, PoliticalStatus = m.PoliticalStatus, Sex = m.Sex, WorkingState = m.WorkingState }).ToListAsync(); } public async Task<List<StaffDto>> _getPage(int ps, int pi, string key = null) { IQueryable<Models.Staff> query; if (key != null && key != "") query = staffService.GetAll().Where(m => m.Name.Contains(key) || m.IDcard == key); else query = staffService.GetAll(); return await query.OrderBy(m => m.Id).Skip(ps * pi).Take(ps).Select(m => new StaffDto() { Address = m.Address, Birthday = m.Birthday, EducationLevel = m.EducationLevel, Email = m.Email, GraduatedSchool = m.GraduatedSchool, HealthStatus = m.HealthStatus, Hometown = m.Hometown, Id = m.Id, IDcard = m.IDcard, MaritalStatus = m.MaritalStatus, Name = m.Name, Password = m.<PASSWORD>, Phone = m.Phone, RoleId = m.RoleId, PoliticalStatus = m.PoliticalStatus, Sex = m.Sex, WorkingState = m.WorkingState }).ToListAsync(); } public async Task<AccountDto> _login(int id, string password) { var staff = await staffService.GetAll().FirstOrDefaultAsync(m => m.Id == id && m.Password == password); if (staff == null) return null; return new AccountDto() { Id = staff.Id, RoleId = staff.RoleId, }; } public async Task<StaffDto> _getOne(int id) { Staff staff = await staffService.GetAll().FirstOrDefaultAsync(m => m.Id == id); if (staff == null) return null; return new StaffDto() { Address = staff.Address, Birthday = staff.Birthday, EducationLevel = staff.EducationLevel, Email = staff.Email, GraduatedSchool = staff.GraduatedSchool, HealthStatus = staff.HealthStatus, Hometown = staff.Hometown, Id = staff.Id, IDcard = staff.IDcard, MaritalStatus = staff.MaritalStatus, Name = staff.Name, Password = <PASSWORD>, Phone = staff.Phone, RoleId = staff.RoleId, PoliticalStatus = staff.PoliticalStatus, Sex = staff.Sex, WorkingState = staff.WorkingState }; } public async Task<int> _getRowCount(string key = null) { IQueryable<Models.Staff> query; if (key != null && key != "") query = staffService.GetAll().Where(m => m.Name.Contains(key) || m.IDcard == key); else query = staffService.GetAll(); return await query.CountAsync(); } public async Task<int> _add(List<StaffDto> models) { foreach (StaffDto model in models) { await staffService.InsertAsync(new Staff() { Address = model.Address, Birthday = model.Birthday, EducationLevel = model.EducationLevel, Email = model.Email, GraduatedSchool = model.GraduatedSchool, HealthStatus = model.HealthStatus, Hometown = model.Hometown, Id = model.Id, IDcard = model.IDcard, MaritalStatus = model.MaritalStatus, Name = model.Name, Password = <PASSWORD>, Phone = model.Phone, RoleId = model.RoleId, PoliticalStatus = model.PoliticalStatus, Sex = model.Sex, WorkingState = model.WorkingState }, false); } return await staffService.Save(); } } } <file_sep>using Eims.Dto; using Eims.IBLL; using System.Web.Http; namespace Eims.WebApi.Controllers { [RoutePrefix("api/staff")] public class StaffController : BaseController<StaffDto, IStaffManager> { } }<file_sep>using Eims.Dto; using Eims.IBLL; using Eims.IDAL; using Eims.Models; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using Unity; namespace Eims.BLL { public class SuggestManager : ISuggestManager { [Dependency] public ISuggestService suggestService { get; set; } [Dependency] public IStaffService staffService { get; set; } public async Task<int> _add(SuggestDto model) { return await suggestService.InsertAsync(new Suggest() { Content = model.Content, Id = model.Id, Reply = model.Reply, ReplyTime = model.ReplyTime, StaffId = model.StaffId, SuggestTime = model.SuggestTime, Title = model.Title }); } public async Task<int> _del(int id) { return await suggestService.DeleteAsync(id); } public async Task<int> _edit(SuggestDto model) { return await suggestService.UpdateAsync(new Suggest() { Content = model.Content, Id = model.Id, Reply = model.Reply, ReplyTime = model.ReplyTime, StaffId = model.StaffId, SuggestTime = model.SuggestTime, Title = model.Title }); } public async Task<List<SuggestDto>> _getAll(string key) { IQueryable<Models.Suggest> query; if (key != null && key != "") query = suggestService.GetAll().Where(m => m.Title.Contains(key) || m.Content.Contains(key)); else query = suggestService.GetAll(); return await query.Select(m => new SuggestDto() { Content = m.Content, Id = m.Id, Reply = m.Reply, ReplyTime = m.ReplyTime, StaffId = m.StaffId, SuggestTime = m.SuggestTime, Title = m.Title }).ToListAsync(); } public async Task<SuggestDto> _getOne(int id) { Suggest m = await suggestService.GetAll().FirstOrDefaultAsync(a => a.Id == id); return new SuggestDto() { Content = m.Content, Id = m.Id, Reply = m.Reply, ReplyTime = m.ReplyTime, StaffId = m.StaffId, SuggestTime = m.SuggestTime, Title = m.Title }; } public async Task<List<SuggestDto>> _getPage(int ps, int pi, string key) { IQueryable<Models.Suggest> query; if (key != null && key != "") query = suggestService.GetAll().Where(m => m.Title.Contains(key) || m.Content.Contains(key)); else query = suggestService.GetAll(); return await query.OrderBy(m => m.Id).Skip(ps * pi).Take(ps).Select(m => new SuggestDto() { Content = m.Content, Id = m.Id, Reply = m.Reply, ReplyTime = m.ReplyTime, StaffId = m.StaffId, SuggestTime = m.SuggestTime, Title = m.Title }).ToListAsync(); } public async Task<List<SuggestDto>> _getPageByStaffId(int staffId, int ps = 10, int pi = 0) { return await suggestService.GetAll().Where(m => m.StaffId == staffId).OrderBy(m => m.Id).Skip(ps * pi).Take(ps).Select(m => new SuggestDto() { Content = m.Content, Id = m.Id, Reply = m.Reply, ReplyTime = m.ReplyTime, StaffId = m.StaffId, SuggestTime = m.SuggestTime, Title = m.Title }).ToListAsync(); } public async Task<int> _getRowCount(string key = null) { IQueryable<Models.Suggest> query; if (key != null && key != "") query = suggestService.GetAll().Where(m => m.Title.Contains(key) || m.Content.Contains(key)); else query = suggestService.GetAll(); return await query.CountAsync(); } public async Task<int> _add(List<SuggestDto> models) { foreach (SuggestDto model in models) { await suggestService.InsertAsync(new Suggest() { Content = model.Content, Id = model.Id, Reply = model.Reply, ReplyTime = model.ReplyTime, StaffId = model.StaffId, SuggestTime = model.SuggestTime, Title = model.Title }, false); } return await suggestService.Save(); } public async Task<List<SuggestWithStaffDto>> _getPageSuggestWithStaff(int ps, int pi, string key = null) { var staffs = await staffService.GetAll().ToListAsync(); var suggests = await suggestService.GetAll().ToListAsync(); if (key != null && key != "") suggests = await suggestService.GetAll().Where(m => m.Title.Contains(key) || m.Content.Contains(key)).ToListAsync(); return suggests.AsQueryable().OrderBy(m => m.Id).Skip(ps * pi).Take(ps).Join(staffs, a => a.StaffId, b => b.Id, (a, b) => new SuggestWithStaffDto() { Id = a.Id, StaffId = a.StaffId, Content = a.Content, Title = a.Title, Reply = a.Reply, ReplyTime = a.ReplyTime, SuggestTime = a.SuggestTime, Staff_Name = b.Name }).ToList(); } public async Task<List<SuggestWithStaffDto>> _getPageSuggestWithStaff(int ps, int pi, int fkid) { var staffs = await staffService.GetAll().ToListAsync(); var suggests = await suggestService.GetAll().Where(m => m.StaffId == fkid).ToListAsync(); return suggests.AsQueryable().OrderBy(m => m.Id).Skip(ps * pi).Take(ps).Join(staffs, a => a.StaffId, b => b.Id, (a, b) => new SuggestWithStaffDto() { Id = a.Id, StaffId = a.StaffId, Content = a.Content, Title = a.Title, Reply = a.Reply, ReplyTime = a.ReplyTime, SuggestTime = a.SuggestTime, Staff_Name = b.Name }).ToList(); } public async Task<SuggestWithStaffDto> _getOneSuggestWithStaff(int id) { var staffs = await staffService.GetAll().ToListAsync(); var suggests = await suggestService.GetAll().Where(m => m.Id == id).ToListAsync(); return suggests.AsQueryable().Join(staffs, a => a.StaffId, b => b.Id, (a, b) => new SuggestWithStaffDto() { Id = a.Id, StaffId = a.StaffId, Content = a.Content, Title = a.Title, Reply = a.Reply, ReplyTime = a.ReplyTime, SuggestTime = a.SuggestTime, Staff_Name = b.Name }).FirstOrDefault(); } } } <file_sep>using Eims.Dto; using System.Collections.Generic; using System.Threading.Tasks; namespace Eims.IBLL { public interface IWageManager : IBaseManager<WageDto> { Task<List<WageWithStaffDto>> _getPageWageWithStaff(int ps, int pi, string key); Task<List<WageWithStaffDto>> _getPageWageWithStaff(int ps, int pi, int fkid); Task<WageWithStaffDto> _getOneWageWithStaff(int id); Task<List<WageDto>> _getPageByStaffId(int ps, int pi, int staffId); Task<List<PayrollDto>> _getPayrollByStaffId(int staffId); } } <file_sep>using Eims.Dto; using Eims.IBLL; using Eims.WebApi.Models; using System.Threading.Tasks; using System.Web.Http; namespace Eims.WebApi.Controllers { [RoutePrefix("api/suggest")] public class SuggestController : BaseController<SuggestDto, ISuggestManager> { [Route("staff"), HttpGet] public async Task<Result> WithStaff(int ps, int pi, string key) { return Result.Success(await manager._getPageSuggestWithStaff(ps, pi, key)); } [Route("staff"), HttpGet] public async Task<Result> WithStaff(int ps, int pi, int fkid) { return Result.Success(await manager._getPageSuggestWithStaff(ps, pi, fkid)); } [Route("staff/{id}"), HttpGet] public async Task<Result> WithStaff(int id) { return Result.Success(await manager._getOneSuggestWithStaff(id)); } } }<file_sep>using Eims.WebApi.Core; using Eims.WebApi.Models.Auth; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace Eims.WebApi.Filter { public class MainAuthAttribute : Attribute, IAuthorizationFilter { public bool RoleValidation { get; set; } = false;//是否开启权限验证 public bool AllowMultiple => throw new NotImplementedException(); public async Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation) { //获取request->headers->token IEnumerable<string> headers; if (actionContext.Request.Headers.TryGetValues("token", out headers)) { //解密token为键值对 Dictionary<string, object> keyValues = JwtTools.Decode(headers.First()); int id = Convert.ToInt32(keyValues["Id"].ToString()); int roleId = Convert.ToInt32(keyValues["RoleId"].ToString()); //将解密内容存入user->identiey (actionContext.ControllerContext.Controller as ApiController).User = new ApplicationUser(id, roleId); //验证类别 if (RoleValidation == false || roleId == 0) { return await continuation(); } } return new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized); } } }<file_sep>using Eims.BLL; using Eims.DAL; using Eims.IBLL; using Eims.IDAL; using Unity; namespace Eims.Core { public partial class RegisterTypes { /// <summary> /// Registers the type mappings with the Unity container. /// </summary> /// <param name="container">The unity container to configure.</param> /// <remarks> /// There is no need to register concrete types such as controllers or /// API controllers (unless you want to change the defaults), as Unity /// allows resolving a concrete type even if it was not previously /// registered. /// </remarks> public static void Partial(IUnityContainer container) { container.RegisterType<IAttendanceManager, AttendanceManager>(); container.RegisterType<IAttendanceService, AttendanceService>(); container.RegisterType<IArticleManager, ArticleManager>(); container.RegisterType<IArticleService, ArticleService>(); container.RegisterType<IStaffManager, StaffManager>(); container.RegisterType<IStaffService, StaffService>(); container.RegisterType<ISuggestManager, SuggestManager>(); container.RegisterType<ISuggestService, SuggestService>(); container.RegisterType<IWageManager, WageManager>(); container.RegisterType<IWageService, WageService>(); } } }<file_sep>using Eims.IDAL; using Eims.Models; using System; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; namespace Eims.DAL { public class BaseService<T> : IBaseService<T>, IDisposable where T : class, new() { private readonly EimsContext _db; public BaseService(EimsContext db) { _db = db; } public async Task<int> InsertAsync(T model, bool saved = true) { _db.Configuration.ValidateOnSaveEnabled = false; _db.Set<T>().Add(model); if (saved) return await Save(); else return -1; } public async Task<int> DeleteAsync(int id, bool saved = true) { _db.Configuration.ValidateOnSaveEnabled = false; var t = _db.Set<T>().Find(id); _db.Entry(t).State = EntityState.Deleted; if (saved) return await Save(); else return -1; } public async Task<int> UpdateAsync(T model, bool saved = true) { _db.Configuration.ValidateOnSaveEnabled = false; _db.Entry(model).State = EntityState.Modified; if (saved) return await Save(); else return -1; } public async Task<int> Save() { try { int i = await _db.SaveChangesAsync(); _db.Configuration.ValidateOnSaveEnabled = true; return i; } catch { return -101; } } public IQueryable<T> GetAll() { return _db.Set<T>().AsNoTracking(); } public void Dispose() { throw new NotImplementedException(); } } } <file_sep>using Eims.Dto; using System.Collections.Generic; using System.Threading.Tasks; namespace Eims.IBLL { public interface IArticleManager : IBaseManager<ArticleDto> { Task<List<ArticleWithStaffDto>> _getPageArticleWithStaff(int ps, int pi, string key = null); Task<List<ArticleWithStaffDto>> _getPageArticleWithStaff(int ps, int pi, int fkid); Task<ArticleWithStaffDto> _getOneArticleWithStaff(int id); } } <file_sep>using System; using System.IO; using System.Text; namespace Eims.Core { /// <summary> /// 写入一个异常错误 /// </summary> /// <param name="ex">异常</param> public static class LogTools { /// <summary> /// 加入异常日志 /// </summary> /// <param name="ex">异常</param> public static void WriteException(string ex) { string subFold = DateTime.Now.Year + DateTime.Now.Month.ToString("D2"); string fileName = subFold + DateTime.Now.Day.ToString("D2") + ".txt"; string path = "C:/LogFile/" + subFold; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string wholePath = path + "\\" + fileName; using (StreamWriter sw = new StreamWriter(wholePath, true, Encoding.UTF8)) { sw.WriteLine(ex); sw.Dispose(); sw.Close(); } return; } } } <file_sep>using System; namespace Eims.Dto { public class ArticleDto { public int Id { get; set; } public Nullable<int> StaffId { get; set; } public string Title { get; set; } public string Content { get; set; } public Nullable<System.DateTime> CreateTime { get; set; } } } <file_sep>using Eims.Dto; using Eims.IBLL; using Eims.WebApi.Models; using System.Threading.Tasks; using System.Web.Http; namespace Eims.WebApi.Controllers { [RoutePrefix("api/article")] public class ArticleController : BaseController<ArticleDto, IArticleManager> { [Route("staff"), HttpGet] public async Task<Result> WithStaff(int ps, int pi, string key) { return Result.Success(await manager._getPageArticleWithStaff(ps, pi, key)); } [Route("staff"), HttpGet] public async Task<Result> WithStaff(int ps, int pi, int fkid) { return Result.Success(await manager._getPageArticleWithStaff(ps, pi, fkid)); } [Route("staff/{id}"), HttpGet] public async Task<Result> WithStaff(int id) { return Result.Success(await manager._getOneArticleWithStaff(id)); } } }<file_sep>using Eims.Models; namespace Eims.IDAL { public interface IAttendanceService : IBaseService<Attendance> { } } <file_sep>using System; namespace Eims.Dto { public class SuggestWithStaffDto { public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } public Nullable<int> StaffId { get; set; } public Nullable<System.DateTime> SuggestTime { get; set; } public string Reply { get; set; } public Nullable<System.DateTime> ReplyTime { get; set; } public string Staff_Name { get; set; } } } <file_sep>using System.Collections.Generic; using System.Threading.Tasks; namespace Eims.IBLL { public interface IBaseManager<T> { /// <summary> /// 分页查询 /// </summary> /// <param name="ps">页长度</param> /// <param name="pi">页码(从0开始)</param> /// <param name="key">关键字</param> /// <returns></returns> Task<List<T>> _getPage(int ps, int pi, string key = null); /// <summary> /// 不分页查询 /// </summary> /// <returns></returns> Task<List<T>> _getAll(string key = null); /// <summary> /// 获取一条数据 /// </summary> /// <param name="id">主键</param> /// <returns></returns> Task<T> _getOne(int id); /// <summary> /// 获取总行数 /// </summary> /// <param name="key">关键字</param> /// <returns></returns> Task<int> _getRowCount(string key = null); /// <summary> /// 添加一條數據 /// </summary> /// <param name="model">数据对象</param> /// <returns></returns> Task<int> _add(T model); /// <summary> /// 添加多條數據 /// </summary> /// <param name="models">数据对象List</param> /// <returns></returns> Task<int> _add(List<T> models); /// <summary> /// 編輯一条数据 /// </summary> /// <param name="model">数据对象</param> /// <returns></returns> Task<int> _edit(T model); /// <summary> /// 删除一条数据 /// </summary> /// <param name="id">主键</param> /// <returns></returns> Task<int> _del(int id); } } <file_sep>namespace Eims.WebApi.Models { public class UserViewModel { public string Token { get; set; } public int Id { get; set; } public int Role { get; set; } } }<file_sep><<<<<<< HEAD # eims eims ======= # eims #### 介绍 {**以下是码云平台说明,您可以替换此简介** 码云是 OSCHINA 推出的基于 Git 的代码托管平台(同时支持 SVN)。专为开发者提供稳定、高效、安全的云端软件开发协作平台 无论是个人、团队、或是企业,都能够用码云实现代码托管、项目管理、协作开发。企业项目请看 [https://gitee.com/enterprises](https://gitee.com/enterprises)} #### 软件架构 软件架构说明 #### 安装教程 1. xxxx 2. xxxx 3. xxxx #### 使用说明 1. xxxx 2. xxxx 3. xxxx >>>>>>> c6a7dbe1fa62b1a414a27b85c98908ee38a82526 <file_sep>using System; using System.Security.Principal; namespace Eims.WebApi.Models.Auth { public class UserIdentity : IIdentity { public UserIdentity(int id, int roleId) { this.Id = id; this.RoleId = roleId; } public int Id { get; set; } public int RoleId { get; set; } public string Name { get; } public string AuthenticationType { get; } public bool IsAuthenticated { get; } } public class ApplicationUser : IPrincipal { public IIdentity Identity { get; } public ApplicationUser(int id, int roleId) { Identity = new UserIdentity(id, roleId); } public bool IsInRole(string role) { throw new NotImplementedException(); } } }<file_sep>using Eims.Dto; using System.Threading.Tasks; namespace Eims.IBLL { public interface IStaffManager : IBaseManager<StaffDto> { Task<AccountDto> _login(int id, string password); } } <file_sep>using System; using System.Linq; using System.Threading.Tasks; namespace Eims.IDAL { public interface IBaseService<T> : IDisposable where T : class { Task<int> InsertAsync(T model, bool saved = true); Task<int> UpdateAsync(T model, bool saved = true); Task<int> DeleteAsync(int id, bool saved = true); Task<int> Save(); IQueryable<T> GetAll(); } } <file_sep>using Eims.Dto; namespace Eims.IBLL { public interface IAttendanceManager : IBaseManager<AttendanceDto> { } } <file_sep>using System.Collections.Generic; namespace Eims.WebApi.Models { public class PaginationViewModel<T> { public int pi { get; set; } public int RowCount { get; set; } public List<T> RowList { get; set; } } }<file_sep>using Eims.Dto; using Eims.IBLL; using Eims.IDAL; using Eims.Models; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using Unity; namespace Eims.BLL { public class WageManager : IWageManager { [Dependency] public IWageService wageService { get; set; } [Dependency] public IStaffService StaffService { get; set; } public async Task<int> _add(WageDto model) { return await wageService.InsertAsync(new Wage() { AttendanceMoney = model.AttendanceMoney, Id = model.Id, AttendanceName = model.AttendanceName, Remark = model.Remark, StaffId = model.StaffId, Time = model.Time, Times = model.Times }); } public async Task<int> _del(int id) { return await wageService.DeleteAsync(id); } public async Task<int> _edit(WageDto model) { return await wageService.UpdateAsync(new Wage() { AttendanceMoney = model.AttendanceMoney, Id = model.Id, AttendanceName = model.AttendanceName, Remark = model.Remark, StaffId = model.StaffId, Time = model.Time, Times = model.Times }); } public async Task<List<WageDto>> _getAll(string key) { IQueryable<Models.Wage> query; if (key != null && key != "") query = wageService.GetAll().Where(m => m.AttendanceName.Contains(key)); else query = wageService.GetAll(); return await query.Select(m => new WageDto() { AttendanceMoney = m.AttendanceMoney, Id = m.Id, AttendanceName = m.AttendanceName, Remark = m.Remark, StaffId = m.StaffId, Time = m.Time, Times = m.Times }).ToListAsync(); } public async Task<List<PayrollDto>> _getPayrollByStaffId(int staffId) { IQueryable<Wage> query = wageService.GetAll().Where(m => m.StaffId == staffId); return await query.GroupBy(m => new { m.StaffId, m.AttendanceName, m.AttendanceMoney }).Select(m => new PayrollDto() { StaffId = (int)m.Key.StaffId, AttenName = m.Key.AttendanceName, AttenMoney = (float)m.Key.AttendanceMoney, AttenTimes = m.Sum(i => (int)i.Times) }).ToListAsync(); } public async Task<WageDto> _getOne(int id) { Wage m = await wageService.GetAll().FirstOrDefaultAsync(a => a.Id == id); return new WageDto() { AttendanceMoney = m.AttendanceMoney, Id = m.Id, AttendanceName = m.AttendanceName, Remark = m.Remark, StaffId = m.StaffId, Time = m.Time, Times = m.Times }; } public async Task<List<WageDto>> _getPage(int ps, int pi, string key) { IQueryable<Models.Wage> query; if (key != null && key != "") query = wageService.GetAll().Where(m => m.AttendanceName.Contains(key)); else query = wageService.GetAll(); return await query.OrderBy(m => m.Id).Skip(ps * pi).Take(ps).Select(m => new WageDto() { AttendanceMoney = m.AttendanceMoney, Id = m.Id, AttendanceName = m.AttendanceName, Remark = m.Remark, StaffId = m.StaffId, Time = m.Time, Times = m.Times }).ToListAsync(); } public async Task<List<WageDto>> _getPageByStaffId(int staffId, int ps = 10, int pi = 0) { return await wageService.GetAll().Where(m => m.StaffId == staffId).OrderBy(m => m.Id).Skip(ps * pi).Take(ps).Select(m => new WageDto() { AttendanceMoney = m.AttendanceMoney, Id = m.Id, AttendanceName = m.AttendanceName, Remark = m.Remark, StaffId = m.StaffId, Time = m.Time, Times = m.Times }).ToListAsync(); } public async Task<int> _getRowCount(string key = null) { IQueryable<Models.Wage> query; if (key != null && key != "") query = wageService.GetAll().Where(m => m.AttendanceName.Contains(key)); else query = wageService.GetAll(); return await query.CountAsync(); } public async Task<int> _add(List<WageDto> models) { foreach (WageDto model in models) { await wageService.InsertAsync(new Wage() { AttendanceMoney = model.AttendanceMoney, Id = model.Id, AttendanceName = model.AttendanceName, Remark = model.Remark, StaffId = model.StaffId, Time = model.Time, Times = model.Times }, false); } return await wageService.Save(); } public async Task<List<WageWithStaffDto>> _getPageWageWithStaff(int ps, int pi, string key) { var staffs = await StaffService.GetAll().ToListAsync(); var wages = await wageService.GetAll().ToListAsync(); if (key != null && key != "") wages = await wageService.GetAll().Where(m => m.AttendanceName.Contains(key)).ToListAsync(); return wages.AsQueryable().OrderBy(m => m.Id).Skip(ps * pi).Take(ps).Join(staffs, a => a.StaffId, b => b.Id, (a, b) => new WageWithStaffDto() { AttendanceMoney = a.AttendanceMoney, Id = a.Id, AttendanceName = a.AttendanceName, Remark = a.Remark, StaffId = a.StaffId, Time = a.Time, Times = a.Times, Staff_Name = b.Name }).ToList(); } public async Task<List<WageWithStaffDto>> _getPageWageWithStaff(int ps, int pi, int fkid) { var staffs = await StaffService.GetAll().ToListAsync(); var wages = await wageService.GetAll().Where(m => m.StaffId == fkid).ToListAsync(); return wages.AsQueryable().OrderBy(m => m.Id).Skip(ps * pi).Take(ps).Join(staffs, a => a.StaffId, b => b.Id, (a, b) => new WageWithStaffDto() { AttendanceMoney = a.AttendanceMoney, Id = a.Id, AttendanceName = a.AttendanceName, Remark = a.Remark, StaffId = a.StaffId, Time = a.Time, Times = a.Times, Staff_Name = b.Name }).ToList(); } public async Task<WageWithStaffDto> _getOneWageWithStaff(int id) { var staffs = await StaffService.GetAll().ToListAsync(); var wages = await wageService.GetAll().Where(m => m.Id == id).ToListAsync(); return wages.AsQueryable().Join(staffs, a => a.StaffId, b => b.Id, (a, b) => new WageWithStaffDto() { AttendanceMoney = a.AttendanceMoney, Id = a.Id, AttendanceName = a.AttendanceName, Remark = a.Remark, StaffId = a.StaffId, Time = a.Time, Times = a.Times, Staff_Name = b.Name }).FirstOrDefault(); } } } <file_sep>using Eims.IDAL; using Eims.Models; namespace Eims.DAL { public class WageService : BaseService<Wage>, IWageService { public WageService() : base(new EimsContext()) { } } } <file_sep>namespace Eims.WebApi.Models { public class Result { public int Code { get; set; }//1和0 public object Data { get; set; } public string ErrorMessage { get; set; } public static Result Success(object data) { return new Result() { Code = 1, Data = data }; } public static Result Fail(string errorMessage) { return new Result() { Code = 0, Data = errorMessage }; } } }<file_sep>using Eims.IDAL; using Eims.Models; namespace Eims.DAL { public class ArticleService : BaseService<Article>, IArticleService { public ArticleService() : base(new EimsContext()) { } } } <file_sep>using Eims.Dto; using Eims.IBLL; using Eims.WebApi.Core; using Eims.WebApi.Filter; using Eims.WebApi.Models; using System.Collections.Generic; using System.Threading.Tasks; using System.Web.Http; using Unity; namespace Eims.WebApi.Controllers { //无需登录 [WebApiExceptionFilter, RoutePrefix(prefix: "api/public")] public class PublicController : ApiController { [Dependency] public IStaffManager staffManager { get; set; } [Dependency] public IArticleManager articleManager { get; set; } [Dependency] public ISuggestManager suggestManager { get; set; } /// <summary> /// 登录 /// </summary> /// <param name="model"></param> /// <returns></returns> [Route("login"), HttpPost] public async Task<Result> login([FromBody]LoginViewModel model) { if (ModelState.IsValid) { AccountDto user = await staffManager._login(model.Id, model.Password); if (user == null) return Result.Fail("账号或密码错误"); return Result.Success(new UserViewModel() { Token = JwtTools.Encode(new Dictionary<string, object>(){ { "Id",user.Id }, { "RoleId",user.RoleId } }), Id = user.Id, Role = (int)user.RoleId }); } return Result.Fail("输入不规范"); } /// <summary> /// 分页获取文章 /// </summary> /// <param name="ps"></param> /// <param name="pi"></param> /// <param name="key"></param> /// <returns></returns> [Route("article"), HttpGet] public async Task<Result> article(int ps, int pi, string key) { return Result.Success(await articleManager._getPage(ps, pi, key)); } /// <summary> /// 公开反馈 /// </summary> /// <param name="ps"></param> /// <param name="pi"></param> /// <param name="key"></param> /// <returns></returns> [Route("suggest"), HttpGet] public async Task<Result> suggest(int ps, int pi, string key) { return Result.Success(await suggestManager._getPage(ps, pi, key)); } } }<file_sep>using Eims.IDAL; using Eims.Models; namespace Eims.DAL { public class StaffService : BaseService<Staff>, IStaffService { public StaffService() : base(new EimsContext()) { } } } <file_sep>using Eims.Models; namespace Eims.IDAL { public interface ISuggestService : IBaseService<Suggest> { } } <file_sep>using Eims.Dto; using Eims.IBLL; using System.Web.Http; namespace Eims.WebApi.Controllers { [RoutePrefix("api/attendance")] public class AttendanceController : BaseController<AttendanceDto, IAttendanceManager> { } }<file_sep>using Eims.IBLL; using Eims.WebApi.Filter; using Eims.WebApi.Models; using System.Collections.Generic; using System.Threading.Tasks; using System.Web.Http; using Unity; namespace Eims.WebApi.Controllers { // 必须登录,且是管理员 [WebApiExceptionFilter, MainAuth(RoleValidation = true)] public class BaseController<T, M> : ApiController where M : IBaseManager<T> { [Dependency] public M manager { get; set; } /// <summary> /// 删除一行 /// </summary> /// <param name="id"></param> /// <returns></returns> public async Task<Result> Delete(int id) { return Result.Success(await manager._del(id)); } /// <summary> /// 分页查询获取 /// </summary> /// <param name="ps"></param> /// <param name="pi"></param> /// <param name="key"></param> /// <returns></returns> public async Task<Result> Get(int ps, int pi, string key = null) { int rowCount = await manager._getRowCount(key); return Result.Success(new PaginationViewModel<T>() { pi = pi, RowCount = rowCount, RowList = await manager._getPage(ps, pi, key) }); } /// <summary> /// 主键获取 /// </summary> /// <param name="id"></param> /// <returns></returns> public async Task<Result> Get(int id) { return Result.Success(await manager._getOne(id)); } /// <summary> /// 获取所有 /// </summary> /// <returns></returns> public async Task<Result> Get() { return Result.Success(await manager._getAll()); } /// <summary> /// 添加一行 /// </summary> /// <param name="model"></param> /// <returns></returns> public async Task<Result> Post(T model) { return Result.Success(await manager._add(model)); } /// <summary> /// 添加多行 /// </summary> /// <param name="models"></param> /// <returns></returns> public async Task<Result> Patch(List<T> models) { return Result.Success(await manager._add(models)); } /// <summary> /// 修改一行 /// </summary> /// <param name="model"></param> /// <returns></returns> public async Task<Result> Put(T model) { return Result.Success(await manager._edit(model)); } } }<file_sep>using System; namespace Eims.Dto { public class WageDto { public int Id { get; set; } public Nullable<System.DateTime> Time { get; set; } public Nullable<int> StaffId { get; set; } public string AttendanceName { get; set; } public Nullable<double> AttendanceMoney { get; set; } public string Remark { get; set; } public Nullable<int> Times { get; set; } } } <file_sep>using System; namespace Eims.Dto { public class AccountDto { public Nullable<int> RoleId { get; set; } public int Id { get; set; } public string Password { get; set; } } } <file_sep>using Eims.BLL; using Eims.Dto; using Eims.WebApi.Models; using System.Collections.Generic; using System.Threading.Tasks; using System.Web.Http; namespace Eims.WebApi.Controllers { [RoutePrefix("api/wage")] public class WageController : BaseController<WageDto, WageManager> { [Route("staff"), HttpGet] public async Task<Result> WithStaff(int ps, int pi, string key) { return Result.Success(await manager._getPageWageWithStaff(ps, pi, key)); } [Route("staff"), HttpGet] public async Task<Result> WithStaff(int ps, int pi, int fkid) { return Result.Success(await manager._getPageWageWithStaff(ps, pi, fkid)); } [Route("staff/{id}"), HttpGet] public async Task<Result> WithStaff(int id) { return Result.Success(await manager._getOneWageWithStaff(id)); } [Route("{staffId}/payroll"), HttpGet] public async Task<Result> GetPayrollByStaffId(int staffId) { return Result.Success(await manager._getPayrollByStaffId(staffId)); } [Route("addlist"), HttpPost] public async Task<Result> Addlist(List<WageDto> wages) { return Result.Success(await manager._add(wages)); } } }<file_sep>using System; namespace Eims.Dto { public class AttendanceDto { public int Id { get; set; } public string Name { get; set; } public Nullable<double> Money { get; set; } public string Remarks { get; set; } } } <file_sep>namespace Eims.Dto { public class PayrollDto { /// <summary> /// 员工编号 /// </summary> public int StaffId { get; set; } /// <summary> /// 奖惩名 /// </summary> public string AttenName { get; set; } /// <summary> /// 金额 /// </summary> public float AttenMoney { get; set; } /// <summary> /// 次数 /// </summary> public int AttenTimes { get; set; } } }
72717e13eaf78a4f169a00192018fa9bca04860d
[ "Markdown", "C#" ]
48
C#
wzy2k/eims
f0e973ee984a5c37c7a9ef0d9f4b7d1ea48a2b9b
69e21fc4f4a9cb29606f2aef07f4c32b6d9357ce
refs/heads/master
<file_sep>/** * Created by vntjomg on 12/12/16. */ public class Snake { private int size; public Position[] positions; /* * Draw the snake */ public Snake(){ this.setSize(1); positions = new Position[1]; positions[0] = new Position(); positions[0].setX(2); positions[0].setY(2); } public void increaseSize() { this.setSize(this.getSize() + 1); } public void moveUp(){ this.positions[0].setY(this.positions[0].getY() - 1); } public void moveDown(){ this.positions[0].setY(this.positions[0].getY() + 1); } public void moveLeft(){ this.positions[0].setX(this.positions[0].getX() - 1); } public void moveRight(){ this.positions[0].setX(this.positions[0].getX() + 1); } public int getSize() { return size; } public void setSize(int size) { this.size = size; } } <file_sep>/** * Tile is the object that represent one position in the screen. */ public class Tile { /** * Theses variables define the state of the tile, the tile can be * - apple tile (which means that it contain a apple) * - Snake tile (which means that it contain a part of the snake body) * - Empty tile (When the tile isnt a apple or a snake body it should have a empty behavior) **/ private boolean apple = false; private boolean snakeBody = false; /** * Each type of tile is represented in a differently way in the * screen, this variables define theirs styles. **/ final private String LABEL = "[ ]"; private String LABEL_WITH_SNAKE_BODY= "[@]"; private String LABEL_WITH_APPLE = "[#]"; /** * Print the tile in the screen basead on its type **/ public void printTile() { if (this.hasApple()) { System.out.print(this.LABEL_WITH_APPLE); } else if(this.isSnakeBody()){ System.out.print(this.LABEL_WITH_SNAKE_BODY); } else { System.out.print(this.LABEL); } } public boolean hasApple() { return apple; } public void setApple(boolean apple) { this.apple = apple; } public boolean isSnakeBody() { return snakeBody; } public void setSnakeBody(boolean snakeBody) { this.snakeBody = snakeBody; } }
7deb6c3e133202a3ab98480234e8aa65e8e8d886
[ "Java" ]
2
Java
that-jpg/SnakeGame.java
8eca1d6f6a9c2ea3ed97fb4739f1bd0fff0af450
f5c397438cc180e42df88efb154ca714a02ce7ef
refs/heads/master
<repo_name>WisamAlhroub/ppu-2020<file_sep>/src/main/java/edu/ppu/algos/SpringMain.java package edu.ppu.algos; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringMain { public static void main(String[] a) { SpringApplication.run(SpringMain.class, a); } } <file_sep>/src/main/java/edu/ppu/std/ListSumService.java package edu.ppu.std; import java.util.List; public class ListSumService { public int sum(List<Integer> numbers){ throw new RuntimeException("this method is not implemented yet"); } } <file_sep>/src/main/java/edu/ppu/std/ListMaxService.java package edu.ppu.std; import java.util.List; public class ListMaxService { public int getMax(List<Integer> numbers) { throw new RuntimeException("this method is not implemented yet"); } } <file_sep>/src/main/java/edu/ppu/domain/C1.java package edu.ppu.domain; public class C1 { } <file_sep>/src/main/java/edu/ppu/algos/MainClass.java package edu.ppu.algos; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Calendar; public class MainClass { public static void main(String[] args) throws IOException, InterruptedException { FileWriter fileWriter = new FileWriter(new File("ppu-dep-test.txt")); //for(int i=0;i<100;i++) { fileWriter.write("Hello worl ..."); // Thread.sleep(1000); // } fileWriter.close(); } } <file_sep>/README.md ![Java CI with Maven](https://github.com/wherbawi/ppu-2020/workflows/Java%20CI%20with%20Maven/badge.svg)
d671858f8846bdfeb00759897bc2370626665270
[ "Markdown", "Java" ]
6
Java
WisamAlhroub/ppu-2020
35c0b2814034ee9f0d7e36d8af0ffa9fb42bb540
cc55cf26eab0a6517514e7a12b33c7796fe75206
refs/heads/master
<file_sep>#include <iostream> using namespace std; int main() { int num; cin >> num; for(int i = 0;i < num;i++){ double x,y; cin >> x >> y; cout << "Property " << i + 1 << ": This property will begin eroding in year " <<int ((x*x + y*y) * 3.1415926 / 100) + 1 <<"."<<endl; } cout << "END OF OUTPUT."; return 0; }<file_sep>#include <stdio.h> #include<cmath> int main() { int num; scanf("%d",&num); double *data = new double[num]; for(int i = 0;i < num;i++){ scanf("%lf",&data[i]); } for(int j = 0;j < num - 1;j++) { double max1,max2; int count1,count2; if(data[0] >= data[1]) { count1 = 0; count2 = 1; max1 = data[0]; max2 = data[1]; } else{ count1 = 1; count2 = 0; max1 = data[1]; max2 = data[0]; } for (int i = 2; i < num; i++) { if (data[i] <= max2); else if (data[i] > max2 && data[i] <= max1) { max2 = data[i]; count2 = i; } else{ count2 = count1; count1 = i; max2 = max1; max1 = data[i]; } } data[count1] = 2 * sqrt(max1 * max2); // printf("%d\n",count2); data[count2] = 0; } for(int i = 0;i < num;i++) if(data[i] != 0.0) printf("%.3f",data[i]); return 0; }<file_sep>#include <iostream> using namespace std; int main() { int num; cin >> num; for(int i = 1;i <= num;i++){ int unused,a; cin >> unused >>a; int count = 0; for(int i = 2;i <= a;i++){ int sum = 0; sum = (i+1)*i/2; if(sum > a)break; if((a - sum) % i == 0)count++; } cout << i<<" "<<count<<endl; } return 0; }<file_sep>#include<stdio.h> #include<string.h> typedef struct NUM{ char content[8]; int count; }NUM; struct NUM num_list[10000]; //void quicksort(struct NUM *num_list,int begin,int end); //static void swap(void *x, void *y, size_t l); int main() { int t = 0; scanf("%d",&t); for(int j = 0;j < t;j++){ char temp[1002]; scanf("%s",temp); int a = 0; for (int i = 0; temp[i] != '\0'; i++) { if (temp[i] != '-') { if(temp[i] > 'Q')--temp[i]; if(temp[i] >= 'A' && temp[i] <='Z') temp[a] = (temp[i] - 'A') / 3 + 2 + '0'; else temp[a] = temp[i]; ++a; } } temp[7] = '\0'; int i = 0, flag = 0; for (; num_list[i].count != 0;i++) { if (strcmp(num_list[i].content, temp) == 0) { num_list[i].count++; flag = 1; break; } } if (flag == 0) { strcpy(num_list[i].content, temp); num_list[i].count = 1; } } int l = 0,z = 0; for(;num_list[l].count != 0;l++) if(z == 0 && num_list[l].count > 1) z = 1; if(z == 1) { // quicksort(num_list,0,l-1); //选择排序 for(int x = 0;x < l;x++){ int index = x; for(int y = x+1;y < l;y++){ int flag = 0; for(int i = 0;num_list[y].content[i] != '\0' && num_list[index].content[i] != '\0';i++) if(num_list[y].content[i] < num_list[index].content[i]){ flag = 1; break; } if(flag != 0) index = y; } struct NUM temp = num_list[x]; num_list[x] = num_list[index]; num_list[index] = temp; } for (int d = 0; num_list[d].count != 0; d++) { if (num_list[d].count > 1) { printf("%3.3s-%s %d\n", num_list[d].content, &num_list[d].content[3],num_list[d].count); } } } else{ printf("No duplicates.\n"); } // printf("!%d %d %d!",start,end,end - start); return 0; } /* void quicksort(struct NUM *num_list,int begin,int end) { if(begin<end){ struct NUM pivot=*(num_list+(begin+end)/2); int l=begin,r=end; // printf("%d\n",pivot); while(l<=r){ int flag = 0; for(int i = 0;(*(num_list+l)).content[i] != '\0' && pivot.content[i] != '\0';i++){ if((*(num_list+l)).content[i] > pivot.content[i]){ flag = 1; break; } } if(flag == 0){ l++; }else{ swap(num_list+l,num_list+r,sizeof(struct NUM)); r--; } } l--; r++; swap(num_list+l,num_list+(begin+end)/2,sizeof(struct NUM)); l--; quicksort(num_list,begin, l); quicksort(num_list,r, end); } } static void swap(void *x, void *y, size_t l) { char *a = (char *)x, *b = (char*)y, c; while(l--) { c = *a; *a++ = *b; *b++ = c; } } */<file_sep>#include <iostream> using namespace std; int main() { double money,sum; for(int i = 1;i <= 12;i++){ cin >> money; sum += money; } cout << "$" << sum / 12; return 0; }<file_sep>#include <iostream> using namespace std; int main() { int a; cin>> a; int count = 0; for(int i = 1;i <= a;i++){ int sum = 0; for(int j = 1;j <= i;j++)sum+=j; if(sum > a)break; if((a - sum) % i == 0)count++; } cout << count; return 0; } <file_sep># POJ My solutions to some of the POJ problems. <file_sep>#include <iostream> using namespace std; int main() { double a; cin >> a; while(a != 0){ double test = 0.5,i = 3; while(test < a){ test +=1/i; i++; } cout << i - 2 << " card(s)" << endl; cin >> a; } return 0; }<file_sep>#include <iostream> using namespace std; int main(){ char R[6],ans[150] = "1"; int n; cin >> R >> n; if(n == 0) cout<< "0" <<endl; else{ while(n){ if(n % 2 == 1){ n--; } n = n >> 1; } cout << ans << endl; } }
704b29b554bd7d3b9addbce04c01757cedda1da0
[ "Markdown", "C++" ]
9
C++
KickCellarDoor/POJ
0c39269da69a7318fa41c32da4bbaf81e629bb66
a68ddffb5ec43bb7c4fd46444232479f68422e91
refs/heads/master
<repo_name>niroshannrsh/dynamodb-schema-migrate<file_sep>/lib/utils.js var exe = require('exe'); var Utils= function () { console.log("This is a Constructor"); }; Utils.execute = function (command){ exe(command); } module.exports= Utills; <file_sep>/README.md # DynamoDB-Schema-Migrate Easily Migrate a Existing Schema(Tables) from one Region to another Region This is a Node Command Line tool to easily migrate your existing DynamoDB tables from one region to another with zero configuration.
ed1ce1b45283cf1b854c18aa30ce6b745fdbbf7a
[ "JavaScript", "Markdown" ]
2
JavaScript
niroshannrsh/dynamodb-schema-migrate
dbca47f1e4906ede490a371cbf871446494a9b77
40f69f9cbca73a6c15e97ea5f655f9bbf0b1aa7f
refs/heads/master
<file_sep>apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "com.sudhirpradhan.sensorslist" minSdkVersion 14 targetSdkVersion 28 versionCode 1 versionName "1.0" //strip other than english resources resConfigs "en" } buildTypes { release { shrinkResources true minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' //Other parameters debuggable false jniDebuggable false renderscriptDebuggable false //signingConfig playStoreConfig //Add your own signing config pseudoLocalesEnabled false zipAlignEnabled true } } } dependencies { implementation 'com.android.support:appcompat-v7:28.0.0' } <file_sep>package com.sudhirpradhan.sensorslist; import android.app.Activity; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorManager; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.Html; import android.text.method.ScrollingMovementMethod; import android.widget.TextView; import java.util.List; public class MainActivity extends Activity { private SensorManager mSensorManager; TextView tvTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvTextView = findViewById(R.id.tvTextView); tvTextView.setMovementMethod(new ScrollingMovementMethod()); mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); List<Sensor> deviceSensors = mSensorManager.getSensorList(Sensor.TYPE_ALL); String tempstr = "<b>" + "This device has "+deviceSensors.size()+" sensors"+ "</b>"; tvTextView.append(Html.fromHtml(tempstr)); //tvTextView.append("\n"); for (int i = 1; i <= deviceSensors.size(); i++) { String tempStr2 = "<b>" + i + ":" + "</b>"; tvTextView.append("\n\n"); tvTextView.append(Html.fromHtml(tempStr2)); tvTextView.append("\n" + deviceSensors.get(i - 1).toString()); } //String myName="made by sudhirpradhan"; //tvTextView.append(Html.fromHtml(myName)); } } <file_sep># Sensors-List It lists all the sensors present in an android device.
de4ccb58d7defdceaa0bdec680ba389e49ed8024
[ "Markdown", "Java", "Gradle" ]
3
Gradle
sudhir-pradhan/Sensors-List
e6ef78c6b0b1de73e847a6747382c0a430f6601d
5a71334c171164c31dd463edca12b89815d44efe
refs/heads/master
<file_sep>package telran.ashkelon2018.books.dto; import lombok.Getter; @Getter public class QueryDto { String query; }
70559960a3da59dfccf302d1ac45c3783f5c71b7
[ "Java" ]
1
Java
Ashkelon2018/BooksSpringOrm
ec9cf0397de1f07137af7826448f15499d70ec78
28c4a0c9954470092ea8c519040c0018fd0cff01
refs/heads/master
<repo_name>TIXIADIYI/Buy<file_sep>/src/main/java/com/bean/Product_typeBean.java package com.bean; import com.dao.Product_typeDao; import com.model.Product_type; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class Product_typeBean { @Resource private Product_typeDao product_typedao; //查询所有商品分类 public Product_type[] all(){ return product_typedao.all(); } //根据id删除分类 public int del(Integer id){ return product_typedao.del(id); } //根据id查询分类 public Product_type get(Integer id){ return product_typedao.get(id); } //添加分类 public int in(Product_type product_type){ return product_typedao.in(product_type); } //编辑分类 public int set(Product_type product_type){ return product_typedao.set(product_type); } //热门分类排序 public Product_type[] product_type_hot(){ return product_typedao.product_type_hot(); } } <file_sep>/src/main/java/com/web/admin/AdminProduct_comment.java package com.web.admin; import com.bean.ProductBean; import com.bean.Product_commentBean; import com.bean.UserBean; import com.model.Product; import com.model.Product_comment; import com.model.Product_type; import com.model.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; @Controller @RequestMapping(value = "/admin/index") public class AdminProduct_comment { @Resource Product_commentBean product_commentbean; @Resource ProductBean productboean; @Resource UserBean userbean; //跳转到评论表 @RequestMapping(value = "/product_comment", method = RequestMethod.GET) public String admin_product_comment(HttpServletRequest request){ Product_comment[] product_comment=product_commentbean.all(); request.setAttribute("product_comment",product_comment); return "admin/product_comment_list.jsp"; } //删除评论 @ResponseBody @RequestMapping(value = "/product_comment/del", method = RequestMethod.GET) public Integer admin_product_comment_del(Integer id){ return product_commentbean.del(id); } //跳转至编辑评论 @RequestMapping(value = "/product_comment/edit", method = RequestMethod.GET) public String admin_prodcut_comment_edit(HttpServletRequest request,Integer id){ Product product[] =productboean.all(); request.setAttribute("product",product); User user[]=userbean.all(); request.setAttribute("user",user); request.setAttribute("add_or_edit",false); Product_comment product_comment=product_commentbean.get(id); request.setAttribute("product_comment",product_comment); return "admin/product_comment_add.jsp"; } //跳转至添加评论 @RequestMapping(value = "/product_comment/add", method = RequestMethod.GET) public String admin_prodcut_comment_add(HttpServletRequest request){ Product product[] =productboean.all(); request.setAttribute("product",product); User user[]=userbean.all(); request.setAttribute("user",user); request.setAttribute("add_or_edit",true); return "admin/product_comment_add.jsp"; } //添加评论提交 @ResponseBody @RequestMapping(value = "/product_comment/add/post", method = RequestMethod.POST) public Integer admin_product_comment_add_post(Product_comment product_comment){ return product_commentbean.add(product_comment); } //编辑评论提交 @ResponseBody @RequestMapping(value = "/product_comment/edit/post", method = RequestMethod.POST) public Integer admin_product_comment_add_edit(Product_comment product_comment) { return product_commentbean.set(product_comment); } } <file_sep>/src/main/java/com/web/shop/ShopLogin.java package com.web.shop; import com.bean.Product_commentBean; import com.bean.UserBean; import com.model.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpSession; @Controller @RequestMapping(value = "/shop") public class ShopLogin { @Resource private UserBean userbean; //跳转至登录页面 @RequestMapping(value = "/login", method = RequestMethod.GET) public String shoplogin(){ return "/shop/login/login.jsp"; } //登录提交验证 @ResponseBody @RequestMapping(value = "/login/post", method = RequestMethod.POST) public Integer shoplogin_post(String user, String pass, HttpSession session){ if(user==null||pass==null||user.equals("")||pass.equals("")){ return 2; }else{ User users=userbean.login(user,pass); if(users!=null){ session.setAttribute("user",users); return 1; }else{ return 0; } } } //注册 @ResponseBody @RequestMapping(value = "/login/zhuce", method = RequestMethod.POST) public Integer shoplogin_zhuce(String user,String pass,String pass2){ if(user==null||pass==null||pass2==null||user.equals("")||pass.equals("")||pass2.equals("")){ return 2; }else if(!pass.equals(pass2)){ return 4; } else if(userbean.zhuce_tm(user)==null){ if(userbean.zhuce(user,pass)!=0){ return 1; }else{ return 0; } }else{ return 3; } } //退出登录 @RequestMapping(value = "/login/exit", method = RequestMethod.GET) public String shoplogin_exit(HttpSession session){ session.removeAttribute("user"); return "/shop/index"; } } <file_sep>/src/main/java/com/bean/ProductBean.java package com.bean; import com.dao.ProductDao; import com.model.Product; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class ProductBean { @Resource private ProductDao productdao; //查询所有商品 public Product[] all(){ return productdao.all(); } //根据分类查询商品 public Product[] product_type_get(Integer product_type_id){ return productdao.product_type_get(product_type_id); } //根据id查询商品 public Product get(Integer id){ return productdao.get(id); } //根据id上下架商品 public int display_tf(Integer id,boolean display){ int i=0; if(display){ i=productdao.display_t(id); }else { i=productdao.display_f(id); } return i; } //根据id删除商品 public int del(Integer id){ return productdao.del(id); } //根据用户id查询 public Product[] user_id_get(Integer user_id){ return productdao.user_id_get(user_id); } //添加商品 public int in(Product product){ return productdao.in(product); } //修改商品 public int set(Product product){ return productdao.set(product); } //关键字 public Product[] sel(String Key){ return productdao.sel(Key); } //根据id增加一点点击数 public int click(Integer id){ return productdao.click(id); } //最热门10 public Product[] product_hot(){ return productdao.product_hot(); } //最新10 public Product[] product_new(){ return productdao.product_new(); } //根据分类id查询该分类中最热门的商品 public Product product_type_get_hot(Integer product_type_id){ return productdao.product_type_get_hot(product_type_id); } //终极数据库语句 public Product[] product_type_key_order_desc(Integer product_type_id,String Key,Integer product_sort){ return productdao.product_type_key_order_desc(product_type_id,Key,product_sort); } //终极数据库语句(价格升序版本 public Product[] product_type_key_order(Integer product_type_id,String Key){ return productdao.product_type_key_order(product_type_id,Key); } } <file_sep>/src/main/webapp/shop/js/style.js  //登录操作 function cliLogin() { var txtUser = $.trim($("#txtUser").val()); var txtPwd = $("#Userpwd").val(); var txtCode = $.trim($('#txtCode').val()); if ($.trim(txtUser) == "") { Tip('请输入账号!'); $("#txtUser").focus(); return; } if ($.trim(txtPwd) == "") { Tip('请输入密码!'); $("#Userpwd").focus(); return; } return false; } function Tip(msg) { $(".tishi").show().text(msg); } <file_sep>/src/main/java/com/web/admin/AdminUser.java package com.web.admin; import com.bean.UserBean; import com.model.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; @Controller @RequestMapping(value = "/admin/index") public class AdminUser { @Resource UserBean userbean; //跳转至用户表 @RequestMapping(value = "/user", method = RequestMethod.GET) public String admin_user(HttpServletRequest request){ User[] user=userbean.all(); request.setAttribute("user",user); return "admin/user_list.jsp"; } //删除 @ResponseBody @RequestMapping(value = "/user/del", method = RequestMethod.GET) public Integer admin_user_del(Integer id){ return userbean.del(id); } //跳转系列 //添加 @RequestMapping(value = "/user/add", method = RequestMethod.GET) public String admin_user_add(HttpServletRequest request){ request.setAttribute("add_or_edit",true); return "admin/user_add.jsp"; } //编辑 @RequestMapping(value = "/user/edit", method = RequestMethod.GET) public String admin_user_edit(HttpServletRequest request,Integer id){ User user=userbean.get(id); request.setAttribute("user",user); System.out.println("啦啦"); request.setAttribute("add_or_edit",false); return "admin/user_add.jsp"; } //添加提交 @ResponseBody @RequestMapping(value = "/user/add/post", method = RequestMethod.POST) public Integer admin_user_add_post(User user){ return userbean.add(user); } //编辑提交 @ResponseBody @RequestMapping(value = "/user/edit/post", method = RequestMethod.POST) public Integer admin_user_edit_post(User user){ return userbean.set(user); } } <file_sep>/src/main/java/com/bean/User_collectionBean.java package com.bean; import com.dao.User_collectionDao; import com.model.User_collection; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class User_collectionBean { @Resource private User_collectionDao user_collectiondao; //查询所有 public User_collection[] all(){ return user_collectiondao.all(); } //get public User_collection get(Integer id){ return user_collectiondao.get(id); } //根据id删除 public int del(Integer id){ return user_collectiondao.del(id); } //添加 public int add(User_collection collection){ return user_collectiondao.add(collection); } //编辑 public int set(User_collection collection){ return user_collectiondao.set(collection); } //重复 public User_collection rep(User_collection collection){ return user_collectiondao.rep(collection); } //根据用户id查询 public User_collection[] user_id_get(Integer user_id){ return user_collectiondao.user_id_get(user_id); } // } <file_sep>/src/main/java/com/web/shop/ShopAll.java package com.web.shop; import com.bean.ProductBean; import com.bean.Product_typeBean; import com.bean.RecommendBean; import com.bean.User_collectionBean; import com.model.*; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.Arrays; @Controller @RequestMapping(value = "/shop") public class ShopAll { @Resource private ProductBean productbean; @Resource private Product_typeBean product_typeBean; @Resource private RecommendBean recommendbean; @Resource private User_collectionBean user_collectionBean; //分页 每页数量 private int pages=9; //跳转至商品列表页面 @RequestMapping(value = "/store/all", method = RequestMethod.GET) public String shop_store_all(HttpServletRequest request,HttpSession session,Integer product_type_id, Integer product_sort, boolean product_sort_3, Integer page, String Key) { //获取所有分类 Product_type[] product_type=product_typeBean.all(); request.setAttribute("product_type",product_type); //获取随机推荐 Recommend recommend=recommendbean.one(); request.setAttribute("recommend",recommend); //获取最热门商品 Product[] product_hot=productbean.product_hot(); request.setAttribute("product_hot",product_hot); //获取热门分类 Product_type[] product_type_top=product_typeBean.product_type_hot(); request.setAttribute("product_type_top",product_type_top); //传送的变量检测和修正 if(product_type_id==null){ product_type_id=-1; } if(Key!=null){ if(Key.equals("")){ Key=null; } } if(product_sort==null){ product_sort=0; } if(product_sort.equals("")){ product_sort=0; } if(page==null){ page=0; } if(page.equals("")){ page=0; } boolean product_sort_3s=false; if(product_sort==3){ product_sort_3s=product_sort_3; } //传送数据 //显示分类的数据 String product_type_name="全部分类"; if(product_type_id!=-1){ Product_type product_type1=product_typeBean.get(product_type_id); product_type_name=product_type1.getName(); } request.setAttribute("product_type_name",product_type_name); //其他 request.setAttribute("product_type_id",product_type_id); request.setAttribute("Key",Key); request.setAttribute("product_sort",product_sort); request.setAttribute("product_sort_3",product_sort_3s); //获取数据 Product[] product=null; if(product_sort_3s) { product=productbean.product_type_key_order(product_type_id,Key); }else{ product=productbean.product_type_key_order_desc(product_type_id,Key,product_sort); } //获取用户收藏 User user=(User)(session.getAttribute("user")); if(user!=null) { boolean[] product_collection=new boolean[product.length]; User_collection user_collection=new User_collection(); user_collection.setUser_id(user); for(int i=0;i<product.length;i++){ user_collection.setProduct_id(product[i]); if(user_collectionBean.rep(user_collection)!=null){ product_collection[i]=true; } } request.setAttribute("product_collection",product_collection); } //分页 商品数据截取 int max=product.length; int pagemax=max/pages; if(max!=0&&max%pages==0){ pagemax-=1; } if(max>pages){ if(pages*page+pages<=max){ max=pages*page+pages; } product= Arrays.copyOfRange(product, pages*page, max); } request.setAttribute("product",product); request.setAttribute("page",page); request.setAttribute("pagemax",pagemax); //跳转 return "/shop/store.jsp"; } } <file_sep>/data/buy_data.sql /* Navicat MySQL Data Transfer Source Server : localhost_3306 Source Server Type : MySQL Source Server Version : 80011 Source Host : localhost:3306 Source Schema : buy_data Target Server Type : MySQL Target Server Version : 80011 File Encoding : 65001 Date: 31/10/2018 11:55:43 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for admins -- ---------------------------- DROP TABLE IF EXISTS `admins`; CREATE TABLE `admins` ( `id` int(10) NOT NULL AUTO_INCREMENT, `name` char(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `pass` char(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of admins -- ---------------------------- INSERT INTO `admins` VALUES (1, 'admin', '<PASSWORD>'); INSERT INTO `admins` VALUES (2, 'admin2', '123'); INSERT INTO `admins` VALUES (3, 'nan', '123'); INSERT INTO `admins` VALUES (4, 'nan2', '123'); -- ---------------------------- -- Table structure for product_comment -- ---------------------------- DROP TABLE IF EXISTS `product_comment`; CREATE TABLE `product_comment` ( `comment` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL, `user_id` int(20) NULL DEFAULT NULL, `product_id` int(20) NULL DEFAULT NULL, `time` date NULL DEFAULT NULL, `praise` bit(1) NULL DEFAULT NULL, `id` int(100) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) USING BTREE, INDEX `user_id`(`user_id`) USING BTREE, INDEX `product_id`(`product_id`) USING BTREE, CONSTRAINT `product_comment_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `product_comment_ibfk_2` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB AUTO_INCREMENT = 15 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of product_comment -- ---------------------------- INSERT INTO `product_comment` VALUES ('这个手机很赞!', 2, 1, '2018-10-16', b'0', 1); INSERT INTO `product_comment` VALUES ('辣鸡玩意', 1, 6, '2018-10-25', b'1', 2); INSERT INTO `product_comment` VALUES ('安全啊啊啊啊啊', 2, 4, '2018-10-11', b'1', 3); INSERT INTO `product_comment` VALUES ('坎坎坷坷', 1, 12, '2018-10-30', b'1', 4); INSERT INTO `product_comment` VALUES ('少时诵诗书所所所所所所所所', NULL, 10, '2018-10-30', b'1', 5); INSERT INTO `product_comment` VALUES ('哦哦哦', 2, 1, '2018-10-11', b'0', 6); INSERT INTO `product_comment` VALUES ('呀呀呀呀呀呀晕晕晕晕晕晕晕晕晕晕晕', 2, 1, '2018-10-03', b'1', 7); INSERT INTO `product_comment` VALUES ('噢噢噢噢哦哦哦哦哦哦哦哦哦哦哦哦', 3, 1, '2018-10-04', b'0', 8); INSERT INTO `product_comment` VALUES ('啦啦啦啦啦啦啦啦绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿', NULL, 10, '2018-10-30', b'1', 9); INSERT INTO `product_comment` VALUES ('55555ˆ–', NULL, 1, '2018-10-30', b'1', 10); INSERT INTO `product_comment` VALUES ('999999999', NULL, 1, '2018-10-30', b'0', 11); INSERT INTO `product_comment` VALUES ('那你那你女', NULL, 6, '2018-10-30', b'1', 12); INSERT INTO `product_comment` VALUES ('123', 1, 11, '2018-10-30', b'1', 13); INSERT INTO `product_comment` VALUES ('好极了', 1, 12, '2018-10-30', b'1', 14); -- ---------------------------- -- Table structure for product_type -- ---------------------------- DROP TABLE IF EXISTS `product_type`; CREATE TABLE `product_type` ( `id` tinyint(20) NOT NULL AUTO_INCREMENT, `name` char(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, PRIMARY KEY (`id`) USING BTREE, INDEX `t_type`(`name`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 24 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of product_type -- ---------------------------- INSERT INTO `product_type` VALUES (6, 'U盘'); INSERT INTO `product_type` VALUES (4, '书籍'); INSERT INTO `product_type` VALUES (8, '彩妆'); INSERT INTO `product_type` VALUES (1, '智能手机'); INSERT INTO `product_type` VALUES (5, '服装'); INSERT INTO `product_type` VALUES (23, '生活用品'); INSERT INTO `product_type` VALUES (3, '相机'); INSERT INTO `product_type` VALUES (2, '笔记本电脑'); INSERT INTO `product_type` VALUES (7, '背包'); -- ---------------------------- -- Table structure for products -- ---------------------------- DROP TABLE IF EXISTS `products`; CREATE TABLE `products` ( `phone` char(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `qq` char(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `id` int(10) NOT NULL AUTO_INCREMENT, `name` char(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `price` float(20, 0) NULL DEFAULT NULL, `remake` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL, `image` char(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `sum` int(50) NULL DEFAULT NULL, `time` date NULL DEFAULT NULL, `click` int(20) NOT NULL DEFAULT 0, `product_type_id` tinyint(20) NULL DEFAULT NULL, `prices` float(50, 0) NULL DEFAULT NULL, `display` bit(1) NOT NULL, `user_id` int(20) NULL DEFAULT NULL, `weixin` char(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE, INDEX `p_type`(`product_type_id`) USING BTREE, INDEX `user_id`(`user_id`) USING BTREE, CONSTRAINT `products_ibfk_1` FOREIGN KEY (`product_type_id`) REFERENCES `product_type` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `products_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ) ENGINE = InnoDB AUTO_INCREMENT = 14 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of products -- ---------------------------- INSERT INTO `products` VALUES (NULL, NULL, 1, '楠神旗舰电脑', 0, NULL, NULL, NULL, '2018-10-02', 12, 2, 0, b'1', 1, NULL); INSERT INTO `products` VALUES (NULL, NULL, 2, '楠神的商品', NULL, NULL, '1111111', NULL, '2018-10-17', 5, 1, NULL, b'1', 1, NULL); INSERT INTO `products` VALUES (NULL, NULL, 3, '楠神手机', 0, NULL, 'img/shop02.png', NULL, '2018-06-06', 101, 1, 0, b'1', 1, NULL); INSERT INTO `products` VALUES (NULL, NULL, 4, '海飞丝', 50, '要毕业了用不完,还有400多毫升', NULL, 5, '2018-10-09', 40, 23, 100, b'1', 2, NULL); INSERT INTO `products` VALUES (NULL, NULL, 5, '测试专用商品', 99, '测试专用哦', NULL, 999, '2018-10-31', 55, 5, 999, b'1', 2, NULL); INSERT INTO `products` VALUES (NULL, NULL, 6, '测试专用商品2', 88, NULL, NULL, NULL, '2018-10-30', 5, 6, NULL, b'1', NULL, NULL); INSERT INTO `products` VALUES (NULL, NULL, 7, '测试专用商品3', 77, NULL, NULL, NULL, NULL, 66, 7, NULL, b'1', NULL, NULL); INSERT INTO `products` VALUES (NULL, NULL, 8, '测试专用商品4', NULL, NULL, NULL, NULL, NULL, 7, 8, NULL, b'0', NULL, NULL); INSERT INTO `products` VALUES (NULL, NULL, 9, '测试专用商品5', 66, NULL, NULL, NULL, NULL, 3, 23, 1, b'1', NULL, NULL); INSERT INTO `products` VALUES ('123', '123', 10, '哈哈哈', 123, '123', '', 213, NULL, 123, 1, 123, b'1', 2, '123'); INSERT INTO `products` VALUES ('123', '1234567890', 11, '哈哈哈', 500, '牛逼哄哄吊炸天', '', 500, '2018-10-11', 124, 4, 123, b'1', 1, '123'); INSERT INTO `products` VALUES ('123', '1234567890', 12, 'hhh', 500, '', '', 500, '2018-10-13', 126, 8, 123, b'1', 2, '123'); INSERT INTO `products` VALUES (NULL, '55', 13, '好吃的呀呀呀呀呀呀', 500, '废话', '/Buy/upload/image/20180707/20180707003628_837.jpg', NULL, '2018-10-30', 2, 23, 0, b'1', 1, '55'); -- ---------------------------- -- Table structure for recommend -- ---------------------------- DROP TABLE IF EXISTS `recommend`; CREATE TABLE `recommend` ( `id` int(50) NOT NULL AUTO_INCREMENT, `commend` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL, `admin_id` int(20) NULL DEFAULT NULL, `value` char(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE, INDEX `admin_id`(`admin_id`) USING BTREE, CONSTRAINT `recommend_ibfk_1` FOREIGN KEY (`admin_id`) REFERENCES `admins` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of recommend -- ---------------------------- INSERT INTO `recommend` VALUES (1, '你对楠神手机的看法?', 1, '楠神手机'); INSERT INTO `recommend` VALUES (2, '限时销售!楠神手机尊享版', 1, '楠神手机'); INSERT INTO `recommend` VALUES (3, '全球限量版楠神手机探索版', 1, '楠神手机'); INSERT INTO `recommend` VALUES (4, '美滋滋电脑你值得拥有!', 1, '电脑'); -- ---------------------------- -- Table structure for user_collection -- ---------------------------- DROP TABLE IF EXISTS `user_collection`; CREATE TABLE `user_collection` ( `id` int(100) NOT NULL AUTO_INCREMENT, `user_id` int(50) NULL DEFAULT NULL, `product_id` int(50) NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE, INDEX `user_id`(`user_id`) USING BTREE, INDEX `product_id`(`product_id`) USING BTREE, CONSTRAINT `user_collection_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `user_collection_ibfk_2` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of user_collection -- ---------------------------- INSERT INTO `user_collection` VALUES (1, 1, 1); INSERT INTO `user_collection` VALUES (3, 2, 11); INSERT INTO `user_collection` VALUES (4, 1, 11); INSERT INTO `user_collection` VALUES (5, 1, 10); INSERT INTO `user_collection` VALUES (8, 1, 12); -- ---------------------------- -- Table structure for users -- ---------------------------- DROP TABLE IF EXISTS `users`; CREATE TABLE `users` ( `id` int(50) NOT NULL AUTO_INCREMENT, `user` char(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `pass` char(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `name` char(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `header` char(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `remake` char(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `sex` bit(1) NULL DEFAULT b'1', `address` char(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `time` date NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of users -- ---------------------------- INSERT INTO `users` VALUES (1, 'user', '123456', '小煞笔', '/Buy/upload/image/20180707/20180707003628_837.jpg', '123', b'0', '', '2018-10-03'); INSERT INTO `users` VALUES (2, '12345678900', '123456', '楠神', '', '牛逼哄哄吊炸天', b'1', '', NULL); INSERT INTO `users` VALUES (3, '111', '123', 'you盘2', '', '牛逼哄哄吊炸天', b'0', '', '2018-10-16'); SET FOREIGN_KEY_CHECKS = 1; <file_sep>/src/main/java/com/dao/ProductDao.java package com.dao; import com.model.Product; import org.apache.ibatis.annotations.Param; public interface ProductDao { //查询所有商品(默认排序) Product[] all(); //根据id查询商品 Product get(@Param(value = "id") Integer id); //根据分类查询商品 Product[] product_type_get(@Param(value = "product_type_id")Integer product_type_id); //根据用户id查询 Product[] user_id_get(@Param(value = "user_id")Integer user_id); //根据ID上架商品 int display_t(@Param(value = "id") Integer id); //根据ID下架商品 int display_f(@Param(value = "id") Integer id); //根据id删除商品 int del(@Param(value = "id") Integer id); //添加商品 int in(Product product); //修改商品 int set(Product product); //查询关键字 Product[] sel(String Key); //根据id增加一点点击数 int click(Integer id); //根据分类id查询该分类中最热门的商品 Product product_type_get_hot(Integer product_type_id); //最热门10 Product[] product_hot(); //最新10 Product[] product_new(); //终极数据库语句 Product[] product_type_key_order_desc(@Param(value = "product_type_id")Integer product_type_id,@Param(value = "Key")String Key,@Param(value = "product_sort")Integer product_sort); //终极数据库语句(价格升序版) Product[] product_type_key_order(@Param(value = "product_type_id")Integer product_type_id,@Param(value = "Key")String Key); } <file_sep>/src/main/java/com/web/admin/AdminIndex.java package com.web.admin; import com.bean.AdminBean; import com.model.Admin; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpSession; @Controller @RequestMapping(value = "/admin") public class AdminIndex { //跳转至后台主页 @RequestMapping(value = "/index", method = RequestMethod.GET) public String adminlogin(){ return "admin/admin_index.jsp"; } //退出登录 @RequestMapping(value = "/exit", method = RequestMethod.GET) public String adminexit(HttpSession session){ session.removeAttribute("admin"); return "admin/login"; } } <file_sep>/src/main/webapp/shop/js/yanz1.js $("#slider1").slider({ callback: function(result) { $("#result1").text(result); } }); $("#slider2").slider({ width: 340, // width height: 40, // height sliderBg: "rgb(134, 134, 131)", // 滑块背景颜色 color: "#fff", // 文字颜色 fontSize: 14, // 文字大小 bgColor: "#33CC00", // 背景颜色 textMsg: "按住滑块,拖拽验证", // 提示文字 successMsg: "验证通过了哦", // 验证成功提示文字 successColor: "red", // 滑块验证成功提示文字颜色 time: 400, // 返回时间 callback: function(result) { // 回调函数,true(成功),false(失败) $("#result2").text(result); } }); $("#reset1").click(function() { $("#slider1").slider("restore"); }); $("#reset2").click(function() { $("#slider2").slider("restore"); }); <file_sep>/src/main/java/com/web/admin/AdminCollection.java package com.web.admin; import com.bean.ProductBean; import com.bean.UserBean; import com.bean.User_collectionBean; import com.model.Product; import com.model.User; import com.model.User_collection; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; @Controller @RequestMapping(value = "/admin/index") public class AdminCollection { @Resource private User_collectionBean user_collectionbean; @Resource private UserBean userbean; @Resource private ProductBean productbean; //跳转至用户表 @RequestMapping(value = "/user_collection", method = RequestMethod.GET) public String admin_user_collection(HttpServletRequest request){ User_collection[] user_collection=user_collectionbean.all(); request.setAttribute("user_collection",user_collection); return "admin/user_collection_list.jsp"; } //删除 @ResponseBody @RequestMapping(value = "/user_collection/del", method = RequestMethod.GET) public Integer admin_collection_del(Integer id){ return user_collectionbean.del(id); } //跳转添加 @RequestMapping(value = "/user_collection/add", method = RequestMethod.GET) public String admin_user_add(HttpServletRequest request){ User[] user=userbean.all(); request.setAttribute("user",user); Product[] product=productbean.all(); request.setAttribute("product",product); request.setAttribute("add_or_edit",true); return "admin/user_collection_add.jsp"; } //跳转编辑 @RequestMapping(value = "/user_collection/edit", method = RequestMethod.GET) public String admin_user_edit(Integer id,HttpServletRequest request){ User[] user=userbean.all(); request.setAttribute("user",user); Product[] product=productbean.all(); request.setAttribute("product",product); User_collection user_collection=user_collectionbean.get(id); request.setAttribute("user_collection",user_collection); request.setAttribute("add_or_edit",false); return "admin/user_collection_add.jsp"; } //添加提交 @ResponseBody @RequestMapping(value = "/user_collection/add/post", method = RequestMethod.POST) public Integer admin_collection_add_post(User_collection user_collection){ return user_collectionbean.add(user_collection); } //编辑提交 @ResponseBody @RequestMapping(value = "/user_collection/edit/post", method = RequestMethod.POST) public Integer admin_collection_edit_post(User_collection user_collection){ return user_collectionbean.set(user_collection); } } <file_sep>/src/main/java/com/model/Product.java package com.model; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; public class Product { private Integer id; private String name; private Float price=0f; private String remake; private String image; private Integer sum; @DateTimeFormat(pattern = "yyyy-MM-dd") private Date time=new Date(1,1,1);; private Integer click=0; private Product_type product_type_id; private Float prices=0f; private User user_id; private boolean display; private String phone; private String qq; private String weixin; public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public String getWeixin() { return weixin; } public void setWeixin(String weixin) { this.weixin = weixin; } public User getUser_id() { return user_id; } public void setUser_id(User user_id) { this.user_id = user_id; } public boolean isDisplay() { return display; } public void setDisplay(boolean display) { this.display = display; } public Float getPrice() { return price; } public void setPrice(Float price) { this.price = price; } public Float getPrices() { return prices; } public void setPrices(Float prices) { this.prices = prices; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRemake() { return remake; } public void setRemake(String remake) { this.remake = remake; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public Integer getSum() { return sum; } public void setSum(Integer sum) { this.sum = sum; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public Integer getClick() { return click; } public void setClick(Integer click) { this.click = click; } public Product_type getProduct_type_id() { return product_type_id; } public void setProduct_type_id(Product_type product_type_id) { this.product_type_id = product_type_id; } }
96e938121acf92b6d1abcffc2f87957ca4d4cf4c
[ "JavaScript", "Java", "SQL" ]
14
Java
TIXIADIYI/Buy
c690c3c010c80f628364234e87dd1bc712b7383e
40afb960e9f5c961767919d858a0a30845279a65
refs/heads/main
<file_sep>require 'ffi' module Sys module ProcTableFunctions extend FFI::Library ffi_lib :kvm attach_function :devname, [:dev_t, :mode_t], :string attach_function :kvm_open, [:string, :string, :string, :int, :string], :pointer attach_function :kvm_close, [:pointer], :int attach_function :kvm_getprocs, [:pointer, :int, :int, :pointer], :pointer attach_function :kvm_getargv, [:pointer, :pointer, :int], :pointer end end <file_sep>[![Ruby](https://github.com/djberg96/sys-proctable/actions/workflows/ruby.yml/badge.svg)](https://github.com/djberg96/sys-proctable/actions/workflows/ruby.yml) # sys-proctable ## Description A Ruby interface for gathering process information. ## Prerequisites * ffi * rspec (development only) * rake (development only) * rubocop (development only) ## Supported Platforms * Windows 2000 or later * Linux 2.6+ * FreeBSD * DragonflyBSD * Solaris 8+ * OS X 10.7+ * AIX 5.3+ ## Installation ```sh gem install sys-proctable ``` For version 1.1.5 or earlier, you may need to specify a platform in some cases. For example: ```sh gem install sys-proctable --platform mswin32 # Windows gem install sys-proctable --platform sunos # Solaris gem install sys-proctable --platform linux # Linux gem install sys-proctable --platform freebsd # FreeBSD gem install sys-proctable --platform darwin # OS X ``` ## Adding the trusted cert `gem cert --add <(curl -Ls https://raw.githubusercontent.com/djberg96/sys-proctable/main/certs/djberg96_pub.pem)` ## Synopsis ```ruby require 'sys/proctable' include Sys # Everything ProcTable.ps{ |p| puts p.pid.to_s puts p.comm # ... } # Just one process s = ProcTable.ps(pid: 2123) puts s.pid.to_s puts s.comm # ... # Return the results as an array of ProcTableStructs a = ProcTable.ps a.each do |p| puts p.pid # ... end ``` ## Notes Various platforms support different options. Mostly this is to let you skip the collection of certain bits of information in order to improve speed and/or reduce memory. For example on Linux you can do this to skip the collection of smaps information: ```ruby Sys::ProcTable.ps(smaps: false) ``` Windows users may send a host name to get process information from a different host. This relies on the WMI service running. ```ruby Sys::ProcTable.ps(host: some_host) ``` ## Known Issues ### FreeBSD A kvm interface is used. That means the owner of the process using the sys-proctable library needs to be a member of the kvm group (or root). ### Bundler For version 1.1.5 or earlier, Bundler seems to have trouble installing the proper gem because of the platform specific gem names. To deal with that, run this command first: ```sh bundle config specific_platform true ``` You should not have to do this for version 1.2.0 or later. ### Solaris The cmdline member on Solaris is limited to 80 characters unless you (or your program) own the process. This is a Solaris design flaw/feature. ### OS X The libproc interface is used. That means you will only get list of processes that you have access to. To get a full listing, run as root. ## Future Plans Support for Solaris will probably be dropped in the next major release. ## Acknowledgements This library was originally based on the Perl module Proc::ProcessTable by <NAME>. Many ideas, as well as large chunks of code, were taken from his work. So, a big THANK YOU goes out to Dan Urist. A big thanks also goes out to Mike Hall who was very helpful with ideas, logic and testing. Thanks also go to <NAME> for providing an account on one of his FreeBSD machines. This is how the FreeBSD support was (initially) added. Thanks go to <NAME> for providing a patch that grabs name, eid, euid, gid and guid info in the Linux version, along with some general debugging help. Thanks go to <NAME> for the original OS X code. Thanks also go to <NAME> for adding the original cmdline support for OS X. Finally I'd like to thank all the folks who have submitted bug reports and/or patches. ## Help Wanted I do not have access to all platforms. If your platform is not supported then you will need to either submit a patch or give me a remote account on a box with a compiler so that I can write the code. ## More documentation See the documentation under the 'doc' directory for more information, including platform specific notes and issues. ## License Apache-2.0 ## Copyright (C) 2003-2023 <NAME> All Rights Reserved. ## Author <NAME> <file_sep>require 'rubygems' require_relative 'lib/sys/proctable/version' Gem::Specification.new do |spec| spec.name = 'sys-proctable' spec.version = Sys::ProcTable::VERSION spec.author = '<NAME>' spec.license = 'Apache-2.0' spec.email = '<EMAIL>' spec.homepage = 'http://github.com/djberg96/sys-proctable' spec.summary = 'An interface for providing process table information' spec.files = Dir['**/*'].reject{ |f| f.include?('git') } spec.test_files = Dir['spec/*.rb'] spec.cert_chain = ['certs/djberg96_pub.pem'] spec.add_dependency('ffi', '~> 1.1') spec.add_development_dependency('rspec', '~> 3.9') spec.add_development_dependency('rake') spec.add_development_dependency('rubocop') spec.add_development_dependency('rubocop-rspec') spec.add_development_dependency('mkmf-lite') spec.metadata = { 'homepage_uri' => 'https://github.com/djberg96/sys-proctable', 'bug_tracker_uri' => 'https://github.com/djberg96/sys-proctable/issues', 'changelog_uri' => 'https://github.com/djberg96/sys-proctable/blob/main/CHANGES.md', 'documentation_uri' => 'https://github.com/djberg96/sys-proctable/wiki', 'source_code_uri' => 'https://github.com/djberg96/sys-proctable', 'wiki_uri' => 'https://github.com/djberg96/sys-proctable/wiki', 'rubygems_mfa_required' => 'true', 'github_repo' => 'https://github.com/djberg96/sys-proctable' } spec.description = <<-EOF The sys-proctable library provides an interface for gathering information about processes on your system, i.e. the process table. Most major platforms are supported and, while different platforms may return different information, the external interface is identical across platforms. EOF end <file_sep>######################################################################## # sys_proctable_darwin_spec.rb # # Test suite for the Darwin version of the sys-proctable library. You # should run these tests via the 'rake test' task. ######################################################################## require 'spec_helper' RSpec.describe Sys::ProcTable, :darwin do let(:fields){ %w[ flags status xstatus pid ppid uid gid ruid rgid svuid svgid rfu1 comm name nfiles pgid pjobc tdev tpgid nice start_tvsec start_tvusec virtual_size resident_size total_user total_system threads_user threads_system policy faults pageins cow_faults messages_sent messages_received syscalls_mach syscalls_unix csw threadnum numrunning priority cmdline exe environ threadinfo ] } before(:all) do @pid1 = Process.spawn({'A' => 'B', 'Z' => nil}, 'sleep 60') @pid2 = Process.spawn('ruby', '-Ilib', '-e', "sleep \'120\'.to_i", '--', 'foo bar') sleep 1 # wait to make sure env is replaced by sleep end after(:all) do Process.kill('TERM', @pid1) Process.kill('TERM', @pid2) end context 'fields singleton method' do it 'responds to a fields method' do expect(described_class).to respond_to(:fields) end it 'returns the expected results for the fields method' do expect(described_class.fields).to be_kind_of(Array) expect(described_class.fields).to eq(fields) end end context 'ProcTable::Struct members' do subject(:process){ described_class.ps(:pid => @pid1) } it 'contains a pid member and returns the expected value' do expect(process).to respond_to(:pid) expect(process.pid).to be_kind_of(Numeric) expect(process.pid).to eq(@pid1) end it 'contains a ppid member and returns the expected value' do expect(process).to respond_to(:ppid) expect(process.ppid).to be_kind_of(Numeric) expect(process.ppid).to eq(Process.pid) end it 'contains a pgid member and returns the expected value' do expect(process).to respond_to(:pgid) expect(process.pgid).to be_kind_of(Numeric) expect(process.pgid).to eq(Process.getpgrp) end it 'contains a ruid member and returns the expected value' do expect(process).to respond_to(:ruid) expect(process.ruid).to be_kind_of(Numeric) expect(process.ruid).to eq(Process.uid) end it 'contains an rgid member and returns the expected value' do expect(process).to respond_to(:rgid) expect(process.rgid).to be_kind_of(Numeric) expect(process.rgid).to eq(Process.gid) end it 'contains an svuid member and returns the expected value' do expect(process).to respond_to(:svuid) expect(process.svuid).to be_kind_of(Numeric) expect(process.svuid).to eq(Process.uid) end it 'contains an svgid member and returns the expected value' do expect(process).to respond_to(:svgid) expect(process.svgid).to be_kind_of(Numeric) expect(process.svgid).to eq(Process.gid) end it 'contains a comm member and returns the expected value' do expect(process).to respond_to(:comm) expect(process.comm).to be_kind_of(String) expect(process.comm).to eq('sleep') end it 'contains a cmdline member and returns the expected value' do expect(process).to respond_to(:cmdline) expect(process.cmdline).to be_kind_of(String) expect(process.cmdline).to eq('sleep 60') end it 'returns a string with the expected arguments for the cmdline member', :skip => :jruby do ptable = Sys::ProcTable.ps(:pid => @pid2) expect(ptable.cmdline).to eq('ruby -Ilib -e sleep \'120\'.to_i -- foo bar') end it 'contains an exe member and returns the expected value' do expect(process).to respond_to(:exe) expect(process.exe).to be_kind_of(String) expect(process.exe).to eq(`which sleep`.chomp) end it 'contains an environ member and returns the expected value' do skip 'It appears to no longer be possible to get environ on spawned processes on Catalina or later in most cases' expect(process).to respond_to(:environ) expect(process.environ).to be_kind_of(Hash) expect(process.environ['A']).to eq('B') expect(process.environ['Z']).to be_nil end end context 'private constants' do it 'makes FFI methods private' do expect(described_class).not_to respond_to(:sysctl) expect(described_class).not_to respond_to(:proc_listallpids) expect(described_class).not_to respond_to(:proc_pidinfo) end it 'makes FFI structs private' do expect(described_class.constants).not_to include(:ProcBsdInfo) expect(described_class.constants).not_to include(:ProcThreadInfo) expect(described_class.constants).not_to include(:ProcTaskInfo) expect(described_class.constants).not_to include(:ProcTaskAllInfo) end it 'makes internal constants private' do expect(described_class.constants).not_to include(:PROC_PIDTASKALLINFO) expect(described_class.constants).not_to include(:PROC_PIDTHREADINFO) expect(described_class.constants).not_to include(:PROC_PIDLISTTHREADS) expect(described_class.constants).not_to include(:CTL_KERN) expect(described_class.constants).not_to include(:KERN_PROCARGS) expect(described_class.constants).not_to include(:KERN_PROCARGS2) expect(described_class.constants).not_to include(:MAX_COMLEN) expect(described_class.constants).not_to include(:MAX_PATHLEN) expect(described_class.constants).not_to include(:MAXTHREADNAMESIZE) expect(described_class.constants).not_to include(:PROC_PIDPATHINFO_MAXSIZE) end end end <file_sep># frozen_string_literal: true ####################################################################### # sys_proctable_linux_spec.rb # # Test suite for the Linux version of the sys-proctable library. You # should run these tests via the 'rake spec' task. ####################################################################### require 'spec_helper' RSpec.describe Sys::ProcTable, :linux do let(:fields){ %w[ cmdline cwd environ exe fd root pid name uid euid gid egid comm state ppid pgrp session tty_nr tpgid flags minflt cminflt majflt cmajflt utime stime cutime cstime priority nice num_threads itrealvalue starttime vsize rss rlim rsslim startcode endcode startstack kstkesp kstkeip signal blocked sigignore sigcatch wchan nswap cnswap exit_signal processor rt_priority policy delayacct_blkio_ticks guest_time cguest_time pctcpu pctmem nlwp cgroup smaps ] } before(:context) do @subject ||= described_class.ps.last end context 'struct members' do it 'contains a cmdline member and returns the expected value' do expect(@subject).to respond_to(:cmdline) expect(@subject.cmdline).to be_kind_of(String) end it 'contains a cwd member and returns the expected value' do expect(@subject).to respond_to(:cwd) expect(@subject.cwd).to be_kind_of(String) if @subject.cwd end it 'contains a environ member and returns the expected value' do expect(@subject).to respond_to(:environ) expect(@subject.environ).to be_kind_of(Hash) end it 'contains an exe member and returns the expected value' do expect(@subject).to respond_to(:exe) expect(@subject.exe).to be_kind_of(String) if @subject.exe end it 'contains an fd member and returns the expected value' do expect(@subject).to respond_to(:fd) expect(@subject.fd).to be_kind_of(Hash) end it 'contains a root member and returns the expected value' do expect(@subject).to respond_to(:root) expect(@subject.root).to be_kind_of(String) if @subject.root end it 'contains a pid member and returns the expected value' do expect(@subject).to respond_to(:pid) expect(@subject.pid).to be_kind_of(Integer) end it 'contains a comm member and returns the expected value' do expect(@subject).to respond_to(:comm) expect(@subject.comm).to be_kind_of(String) end it 'contains a state member and returns the expected value' do expect(@subject).to respond_to(:state) expect(@subject.state).to be_kind_of(String) end it 'contains a ppid member and returns the expected value' do expect(@subject).to respond_to(:ppid) expect(@subject.ppid).to be_kind_of(Integer) end it 'contains a pgrp member and returns the expected value' do expect(@subject).to respond_to(:pgrp) expect(@subject.pgrp).to be_kind_of(Integer) end it 'contains a session member and returns the expected value' do expect(@subject).to respond_to(:session) expect(@subject.session).to be_kind_of(Integer) end it 'contains a tty_nr member and returns the expected value' do expect(@subject).to respond_to(:tty_nr) expect(@subject.tty_nr).to be_kind_of(Integer) end it 'contains a tpgid member and returns the expected value' do expect(@subject).to respond_to(:tpgid) expect(@subject.tpgid).to be_kind_of(Integer) end it 'contains a flags member and returns the expected value' do expect(@subject).to respond_to(:flags) expect(@subject.flags).to be_kind_of(Numeric) end it 'contains a minflt member and returns the expected value' do expect(@subject).to respond_to(:minflt) expect(@subject.minflt).to be_kind_of(Numeric) end it 'contains a cminflt member and returns the expected value' do expect(@subject).to respond_to(:cminflt) expect(@subject.cminflt).to be_kind_of(Numeric) end it 'contains a majflt member and returns the expected value' do expect(@subject).to respond_to(:majflt) expect(@subject.majflt).to be_kind_of(Numeric) end it 'contains a cmajflt member and returns the expected value' do expect(@subject).to respond_to(:cmajflt) expect(@subject.cmajflt).to be_kind_of(Numeric) end it 'contains a utime member and returns the expected value' do expect(@subject).to respond_to(:utime) expect(@subject.utime).to be_kind_of(Numeric) end it 'contains a stime member and returns the expected value' do expect(@subject).to respond_to(:stime) expect(@subject.stime).to be_kind_of(Numeric) end it 'contains a cutime member and returns the expected value' do expect(@subject).to respond_to(:cutime) expect(@subject.cutime).to be_kind_of(Numeric) end it 'contains a cstime member and returns the expected value' do expect(@subject).to respond_to(:cstime) expect(@subject.cstime).to be_kind_of(Numeric) end it 'contains a priority member and returns the expected value' do expect(@subject).to respond_to(:priority) expect(@subject.priority).to be_kind_of(Numeric) end it 'contains a nice member and returns the expected value' do expect(@subject).to respond_to(:nice) expect(@subject.nice).to be_kind_of(Numeric) end it 'contains a num_threads member and returns the expected value' do expect(@subject).to respond_to(:num_threads) expect(@subject.num_threads).to be_kind_of(Numeric) end it 'contains a itrealvalue member and returns the expected value' do expect(@subject).to respond_to(:itrealvalue) expect(@subject.itrealvalue).to be_kind_of(Numeric) end it 'contains a starttime member and returns the expected value' do expect(@subject).to respond_to(:starttime) expect(@subject.starttime).to be_kind_of(Numeric) end it 'contains a vsize member and returns the expected value' do expect(@subject).to respond_to(:vsize) expect(@subject.vsize).to be_kind_of(Numeric) end it 'contains a rss member and returns the expected value' do expect(@subject).to respond_to(:rss) expect(@subject.rss).to be_kind_of(Numeric) end it 'contains an rsslim member and returns the expected value' do expect(@subject).to respond_to(:rsslim) expect(@subject.rsslim).to be_kind_of(Numeric) expect(@subject.rsslim).to eq(@subject.rlim) end it 'contains an startcode member and returns the expected value' do expect(@subject).to respond_to(:startcode) expect(@subject.startcode).to be_kind_of(Numeric) end it 'contains an endcode member and returns the expected value' do expect(@subject).to respond_to(:endcode) expect(@subject.endcode).to be_kind_of(Numeric) end it 'contains a startstack member and returns the expected value' do expect(@subject).to respond_to(:startstack) expect(@subject.startstack).to be_kind_of(Integer) end it 'contains a kstkesp member and returns the expected value' do expect(@subject).to respond_to(:kstkesp) expect(@subject.kstkesp).to be_kind_of(Integer) end it 'contains a kstkeip member and returns the expected value' do expect(@subject).to respond_to(:kstkeip) expect(@subject.kstkeip).to be_kind_of(Integer) end it 'contains a signal member and returns the expected value' do expect(@subject).to respond_to(:signal) expect(@subject.signal).to be_kind_of(Integer) end it 'contains a blocked member and returns the expected value' do expect(@subject).to respond_to(:blocked) expect(@subject.blocked).to be_kind_of(Integer) end it 'contains a sigignore member and returns the expected value' do expect(@subject).to respond_to(:sigignore) expect(@subject.sigignore).to be_kind_of(Integer) end it 'contains a sigcatch member and returns the expected value' do expect(@subject).to respond_to(:sigcatch) expect(@subject.sigcatch).to be_kind_of(Integer) end it 'contains a wchan member and returns the expected value' do expect(@subject).to respond_to(:wchan) expect(@subject.wchan).to be_kind_of(Integer) end it 'contains a nswap member and returns the expected value' do expect(@subject).to respond_to(:nswap) expect(@subject.nswap).to be_kind_of(Integer) end it 'contains a cnswap member and returns the expected value' do expect(@subject).to respond_to(:cnswap) expect(@subject.cnswap).to be_kind_of(Integer) end it 'contains a exit_signal member and returns the expected value' do expect(@subject).to respond_to(:exit_signal) expect(@subject.exit_signal).to be_kind_of(Integer) end it 'contains a processor member and returns the expected value' do expect(@subject).to respond_to(:processor) expect(@subject.processor).to be_kind_of(Integer) end it 'contains a rt_priority member and returns the expected value' do expect(@subject).to respond_to(:rt_priority) expect(@subject.rt_priority).to be_kind_of(Integer) end it 'contains a policy member and returns the expected value' do expect(@subject).to respond_to(:policy) expect(@subject.policy).to be_kind_of(Integer) end it 'contains a delayacct_blkio_ticks member and returns the expected value' do expect(@subject).to respond_to(:delayacct_blkio_ticks) expect(@subject.delayacct_blkio_ticks).to be_kind_of(Integer) end it 'contains a guest_time member and returns the expected value' do expect(@subject).to respond_to(:guest_time) expect(@subject.guest_time).to be_kind_of(Integer) end it 'contains a cguest_time member and returns the expected value' do expect(@subject).to respond_to(:cguest_time) expect(@subject.cguest_time).to be_kind_of(Integer) end it 'contains a name member and returns the expected value' do expect(@subject).to respond_to(:name) expect(@subject.name).to be_kind_of(String) end it 'contains a uid member and returns the expected value' do expect(@subject).to respond_to(:uid) expect(@subject.uid).to be_kind_of(Integer) end it 'contains a euid member and returns the expected value' do expect(@subject).to respond_to(:euid) expect(@subject.euid).to be_kind_of(Integer) end it 'contains a gid member and returns the expected value' do expect(@subject).to respond_to(:gid) expect(@subject.gid).to be_kind_of(Integer) end it 'contains a egid member and returns the expected value' do expect(@subject).to respond_to(:egid) expect(@subject.egid).to be_kind_of(Integer) end it 'contains a pctmem member and returns the expected value' do expect(@subject).to respond_to(:pctmem) expect(@subject.pctmem).to be_kind_of(Float) end it 'contains a pctcpu member and returns the expected value' do expect(@subject).to respond_to(:pctcpu) expect(@subject.pctcpu).to be_kind_of(Float) end it 'contains a nlwp member and returns the expected value' do expect(@subject).to respond_to(:nlwp) expect(@subject.nlwp).to be_kind_of(Integer) end end context 'custom structs' do it 'contains a cgroup member and returns the expected value' do expect(@subject).to respond_to(:cgroup) expect(@subject.cgroup).to be_kind_of(Array) expect(@subject.cgroup.first).to be_kind_of(Sys::ProcTable::CgroupEntry) end it 'contains a smaps member and returns the expected value' do expect(@subject).to respond_to(:cgroup) expect(@subject.smaps).to be_kind_of(Sys::ProcTable::Smaps) end end context 'fields' do it 'has a fields method that returns the expected results' do expect(described_class).to respond_to(:fields) expect(described_class.fields).to be_kind_of(Array) expect(described_class.fields).to match_array(fields) end end end <file_sep>#!/usr/bin/env ruby require 'json' require 'optparse' require 'rbconfig' require 'benchmark/ips' @source, @gem = false OptionParser.new do |opt| opt.banner = "Usage: #{File.basename $0} [--gem|--source]" opt.separator "" opt.separator "Benchmark IPS (iterations per second) changes between" opt.separator "source version of sys-proctable and previous gem" opt.separator "version." opt.separator "" opt.separator "Requires that the both the source version of the gem" opt.separator "be installed (run `rake install` to do this after" opt.separator "each of your changes) and version installed via" opt.separator "rubygems." opt.separator "" opt.separator "To run, call with `--gem` two times, and then with " opt.separator "`--source` two times again." opt.separator "" opt.on("--source") { @source = true } opt.on("--gem") { @gem = true } end.parse! if @source && !@gem # Being paranoid here and making sure we get the version installed to # sitelibdir require File.join(RbConfig::CONFIG["sitelibdir"], "sys", "proctable") else @gem = true require 'sys-proctable' end Benchmark.ips do |bench| bench.report("Block form - pre patch") do (puts "ERR: Please run with --gem"; exit 1) unless @gem Sys::ProcTable.ps {} end bench.report("Non-block form - pre patch") do (puts "ERR: Please run with --gem"; exit 1) unless @gem Sys::ProcTable.ps end bench.report("Block form - post patch") do (puts "ERR: Please run with --source"; exit 1) unless @source Sys::ProcTable.ps {} end bench.report("Non-block form - post patch") do (puts "ERR: Please run with --source"; exit 1) unless @source Sys::ProcTable.ps end bench.hold! "bench_ips_ps.results" bench.compare! end <file_sep>module Sys module ProcTableConstants WMESGLEN = 8 MAXCOMLEN = 16 NGROUPS = 16 MAXLOGNAME = 33 KERN_PROC_ALL = 0 KERN_PROC_PID = 1 end end <file_sep>############################################################################## # sys_top_spec.rb # # Test suite for the sys-top library that is included with this distribution. ############################################################################## require 'spec_helper' RSpec.describe Sys::Top do context 'constants' do it 'sets the version to the expected value' do expect(Sys::Top::VERSION).to eql('1.0.5') end end context 'top' do it 'defines a top method' do expect(described_class).to respond_to(:top) end it 'returns an array' do expect(described_class.top).to be_kind_of(Array) end it 'works with no arguments' do expect{ described_class.top }.not_to raise_error end it 'accepts a maximum of two arguments' do expect{ described_class.top(1, 'foo', 2) }.to raise_error(ArgumentError) end it 'accepts optional arguments' do expect{ described_class.top(5) }.not_to raise_error expect{ described_class.top(5, 'cmdline') }.not_to raise_error end it 'returns the expected results with no arguments' do expect(described_class.top.size).to be(10) expect(described_class.top.first).to be_kind_of(Struct::ProcTableStruct) end it 'returns the expected result with a size argument' do expect(described_class.top(5).size).to be(5) end it 'returns the expected result with a size and sort_by argument' do expect(described_class.top(5, :cmdline).size).to be(5) end end end <file_sep>case RbConfig::CONFIG['host_os'] when /freebsd/i require_relative 'freebsd/sys/proctable' when /dragonfly/i require_relative 'dragonfly/sys/proctable' else raise "Unsupported version of BSD" end <file_sep># frozen_string_literal: true ############################################################################ # sys_proctable_windows_spec.rb # # Test suite for the sys-proctable library for MS Windows. This should be # run via the 'rake spec' task. ############################################################################ require 'spec_helper' require 'socket' RSpec.describe Sys::ProcTable, :windows do let(:hostname) { Socket.gethostname } let(:fields) { %w[ caption cmdline comm creation_class_name creation_date cs_creation_class_name cs_name description executable_path execution_state handle handle_count install_date kernel_mode_time maximum_working_set_size minimum_working_set_size name os_creation_class_name os_name other_operation_count other_transfer_count page_faults page_file_usage ppid peak_page_file_usage peak_virtual_size peak_working_set_size priority private_page_count pid quota_non_paged_pool_usage quota_paged_pool_usage quota_peak_non_paged_pool_usage quota_peak_paged_pool_usage read_operation_count read_transfer_count session_id status termination_date thread_count user_mode_time virtual_size windows_version working_set_size write_operation_count write_transfer_count ] } context 'fields' do it 'responds to a fields method' do expect(described_class).to respond_to(:fields) end it 'returns the expected results for the fields method' do expect(described_class.fields).to be_kind_of(Array) expect(described_class.fields).to eql(fields) end end context 'ps' do it 'accepts an optional host' do expect{ described_class.ps(:host => hostname) }.not_to raise_error end it 'ignores unused options' do expect{ described_class.ps(:smaps => false) }.not_to raise_error end end context 'ProcTable::Struct members' do subject(:process){ described_class.ps.first } it 'has a write_transfer_count struct member with the expected data type' do expect(process).to respond_to(:write_transfer_count) expect(process.write_transfer_count).to be_kind_of(Integer) end it 'has a write_operation_count struct member with the expected data type' do expect(process).to respond_to(:write_operation_count) expect(process.write_operation_count).to be_kind_of(Integer) end it 'has a working_set_size struct member with the expected data type' do expect(process).to respond_to(:working_set_size) expect(process.working_set_size).to be_kind_of(Integer) end it 'has a windows_version struct member with the expected data type' do expect(process).to respond_to(:windows_version) expect(process.windows_version).to be_kind_of(String) end it 'has a virtual_size struct member with the expected data type' do expect(process).to respond_to(:virtual_size) expect(process.virtual_size).to be_kind_of(Integer) end it 'has a user_mode_time struct member with the expected data type' do expect(process).to respond_to(:user_mode_time) expect(process.user_mode_time).to be_kind_of(Integer) end it 'has a thread_count struct member with the expected data type' do expect(process).to respond_to(:thread_count) expect(process.thread_count).to be_kind_of(Integer) end it 'has a termination_date struct member with the expected data type' do expect(process).to respond_to(:termination_date) expect(process.termination_date).to be_kind_of(Date) if process.termination_date end it 'has a status struct member with the expected data type' do expect(process).to respond_to(:status) expect(process.status).to be_nil # Always nil according to MSDN end it 'has a session_id struct member with the expected data type' do expect(process).to respond_to(:session_id) expect(process.session_id).to be_kind_of(Integer) end it 'has a read_transfer_count struct member with the expected data type' do expect(process).to respond_to(:read_transfer_count) expect(process.read_transfer_count).to be_kind_of(Integer) end it 'has a read_operation_count struct member with the expected data type' do expect(process).to respond_to(:read_operation_count) expect(process.read_operation_count).to be_kind_of(Integer) end it 'has a quota_peak_paged_pool_usage struct member with the expected data type' do expect(process).to respond_to(:quota_peak_paged_pool_usage) expect(process.quota_peak_paged_pool_usage).to be_kind_of(Integer) end it 'has a quota_peak_non_paged_pool_usage struct member with the expected data type' do expect(process).to respond_to(:quota_peak_non_paged_pool_usage) expect(process.quota_peak_non_paged_pool_usage).to be_kind_of(Integer) end it 'has a quota_paged_pool_usage struct member with the expected data type' do expect(process).to respond_to(:quota_paged_pool_usage) expect(process.quota_paged_pool_usage).to be_kind_of(Integer) end it 'has a quota_non_paged_pool_usage struct member with the expected data type' do expect(process).to respond_to(:quota_non_paged_pool_usage) expect(process.quota_non_paged_pool_usage).to be_kind_of(Integer) end it 'has a pid struct member with the expected data type' do expect(process).to respond_to(:pid) expect(process.pid).to be_kind_of(Integer) end it 'has a private_page_count struct member with the expected data type' do expect(process).to respond_to(:private_page_count) expect(process.private_page_count).to be_kind_of(Integer) end it 'has a priority struct member with the expected data type' do expect(process).to respond_to(:priority) expect(process.priority).to be_kind_of(Integer) end it 'has a peak_working_set_size struct member with the expected data type' do expect(process).to respond_to(:peak_working_set_size) expect(process.peak_working_set_size).to be_kind_of(Integer) end it 'has a peak_virtual_size struct member with the expected data type' do expect(process).to respond_to(:peak_virtual_size) expect(process.peak_virtual_size).to be_kind_of(Integer) end it 'has a peak_page_file_usage struct member with the expected data type' do expect(process).to respond_to(:peak_page_file_usage) expect(process.peak_page_file_usage).to be_kind_of(Integer) end it 'has a ppid struct member with the expected data type' do expect(process).to respond_to(:ppid) expect(process.ppid).to be_kind_of(Integer) end it 'has a page_file_usage struct member with the expected data type' do expect(process).to respond_to(:page_file_usage) expect(process.page_file_usage).to be_kind_of(Integer) end it 'has a page_faults struct member with the expected data type' do expect(process).to respond_to(:page_faults) expect(process.page_faults).to be_kind_of(Integer) end it 'has a other_transfer_count struct member with the expected data type' do expect(process).to respond_to(:other_transfer_count) expect(process.other_transfer_count).to be_kind_of(Integer) end it 'has a other_operation_count struct member with the expected data type' do expect(process).to respond_to(:other_operation_count) expect(process.other_operation_count).to be_kind_of(Integer) end it 'has a os_name struct member with the expected data type' do expect(process).to respond_to(:os_name) expect(process.os_name).to be_kind_of(String) end it 'has a os_creation_class_name struct member with the expected data type' do expect(process).to respond_to(:os_creation_class_name) expect(process.os_creation_class_name).to be_kind_of(String) end it 'has a name struct member with the expected data type' do expect(process).to respond_to(:name) expect(process.name).to be_kind_of(String) end it 'has a minimum_working_set_size struct member with the expected data type' do expect(process).to respond_to(:minimum_working_set_size) expect(process.minimum_working_set_size).to be_kind_of(Integer) if process.minimum_working_set_size end it 'has a maximum_working_set_size struct member with the expected data type' do expect(process).to respond_to(:maximum_working_set_size) expect(process.maximum_working_set_size).to be_kind_of(Integer) if process.maximum_working_set_size end it 'has a kernel_mode_time struct member with the expected data type' do expect(process).to respond_to(:kernel_mode_time) expect(process.kernel_mode_time).to be_kind_of(Integer) end it 'has a install_date struct member with the expected data type' do expect(process).to respond_to(:install_date) expect(process.install_date).to be_kind_of(Date) if process.install_date end it 'has a handle_count struct member with the expected data type' do expect(process).to respond_to(:handle_count) expect(process.handle_count).to be_kind_of(Integer) end it 'has a handle struct member with the expected data type' do expect(process).to respond_to(:handle) expect(process.handle).to be_kind_of(String) end it 'has a execution_state struct member with the expected data type' do expect(process).to respond_to(:execution_state) expect(process.execution_state).to be_nil end it 'has a executable_path struct member with the expected data type' do expect(process).to respond_to(:executable_path) expect(process.executable_path).to be_kind_of(String) if process.executable_path end it 'has a description struct member with the expected data type' do expect(process).to respond_to(:description) expect(process.description).to be_kind_of(String) end it 'has a cs_name struct member with the expected data type' do expect(process).to respond_to(:cs_name) expect(process.cs_name).to be_kind_of(String) end it 'has a cs_creation_class_name struct member with the expected data type' do expect(process).to respond_to(:cs_creation_class_name) expect(process.cs_creation_class_name).to be_kind_of(String) end it 'has a creation_date struct member with the expected data type' do expect(process).to respond_to(:creation_date) expect(process.creation_date).to be_kind_of(Date) if process.creation_date end it 'has a creation_class_name struct member with the expected data type' do expect(process).to respond_to(:creation_class_name) expect(process.creation_class_name).to be_kind_of(String) end it 'has a comm struct member with the expected data type' do expect(process).to respond_to(:comm) expect(process.comm).to be_kind_of(String) end it 'has a cmdline struct member with the expected data type' do expect(process).to respond_to(:cmdline) expect(process.cmdline).to be_kind_of(String) if process.cmdline end it 'has a caption struct member with the expected data type' do expect(process).to respond_to(:caption) expect(process.caption).to be_kind_of(String) end end end <file_sep>require 'rake' require 'rake/clean' require 'rake/testtask' require 'rbconfig' require 'rspec/core/rake_task' require 'rubocop/rake_task' include RbConfig CLEAN.include('**/*.gem', '**/*.rbc', '**/*.lock') RuboCop::RakeTask.new desc 'Install the sys-proctable library' task :install do file = nil dir = File.join(CONFIG['sitelibdir'], 'sys') Dir.mkdir(dir) unless File.exists?(dir) case CONFIG['host_os'] when /mswin|win32|msdos|cygwin|mingw|windows/i file = 'lib/windows/sys/proctable.rb' when /linux/i file = 'lib/linux/sys/proctable.rb' when /sunos|solaris/i file = 'lib/sunos/sys/proctable.rb' when /aix/i file = 'lib/aix/sys/proctable.rb' when /freebsd/i file = 'lib/freebsd/sys/proctable.rb' when /darwin/i file = 'lib/darwin/sys/proctable.rb' end cp(file, dir, :verbose => true) if file end desc 'Uninstall the sys-proctable library' task :uninstall do dir = File.join(CONFIG['sitelibdir'], 'sys') file = File.join(dir, 'proctable.rb') rm(file) end desc 'Run the benchmark suite' task :bench do sh "ruby -Ilib benchmarks/bench_ps.rb" end desc 'Run the example program' task :example do sh 'ruby -Ilib -Iext examples/example_ps.rb' end desc 'Run the test suite for the sys-proctable library' RSpec::Core::RakeTask.new(:spec) do |t| t.pattern = ['spec/sys_proctable_all_spec.rb', 'spec/sys_top_spec.rb'] case CONFIG['host_os'] when /aix/i t.rspec_opts = '-Ilib/aix' t.pattern << 'spec/sys_proctable_aix.rb' when /darwin/i t.rspec_opts = '-Ilib/darwin' t.pattern << 'spec/sys_proctable_darwin_spec.rb' when /bsd|dragonfly/i t.rspec_opts = '-Ilib/bsd' t.pattern << 'spec/sys_proctable_bsd_spec.rb' when /linux/i t.rspec_opts = '-Ilib/linux' t.pattern << 'spec/sys_proctable_linux_spec.rb' when /sunos|solaris/i t.rspec_opts = '-Ilib/sunos' t.pattern << 'spec/sys_proctable_sunos_spec.rb' when /mswin|msdos|cygwin|mingw|windows/i t.rspec_opts = '-Ilib/windows' t.pattern << 'spec/sys_proctable_windows_spec.rb' end end namespace :gem do desc 'Create a gem for the specified OS, or your current OS by default' task :create => [:clean] do require 'rubygems/package' spec = Gem::Specification.load('sys-proctable.gemspec') spec.signing_key = File.join(Dir.home, '.ssh', 'gem-private_key.pem') Gem::Package.build(spec) end desc 'Install the sys-proctable library as a gem' task :install => [:create] do gem_name = Dir['*.gem'].first sh "gem install -l #{gem_name}" end end task :default => :spec <file_sep>####################################################################### # example_ps.rb # # Generic test program that demonstrates the use of ProcTable.ps. You # can run this via the 'rake example' task. # # Modify as you see fit ####################################################################### require 'sys/proctable' include Sys puts "VERSION: " + ProcTable::VERSION sleep 2 ProcTable.ps{ |s| ProcTable.fields.each{ |field| puts "#{field}: " + s.send(field).to_s } puts '=' * 30 } <file_sep>################################################################ # sys_proctable_bsd_rspec.rb # # Specs for BSD related operating systems for the sys-proctable # library. You should run these tests via the 'rake spec' task. ################################################################ require 'spec_helper' require 'mkmf-lite' RSpec.describe Sys::ProcTable, :bsd do let(:fields_freebsd){ %w[ pid ppid pgid tpgid sid tsid jobc uid ruid rgid ngroups groups size rssize swrss tsize dsize ssize xstat acflag pctcpu estcpu slptime swtime runtime start flag state nice lock rqindex oncpu lastcpu wmesg login lockname comm ttynum ttydev jid priority usrpri cmdline utime stime maxrss ixrss idrss isrss minflt majflt nswap inblock oublock msgsnd msgrcv nsignals nvcsw nivcsw ] } let(:fields_dragonfly){ %w[ paddr flags stat lock acflag traceflag fd siglist sigignore sigcatch sigflag start comm uid ngroups groups ruid svuid rgid svgid pid ppid pgid jobc sid login tdev tpgid tsid exitstat nthreads nice swtime vm_map_size vm_rssize vm_swrss vm_tsize vm_dsize vm_ssize vm_prssize jailid ru cru auxflags lwp ktaddr ] } context 'fields singleton method' do it 'responds to a fields method' do expect(described_class).to respond_to(:fields) end it 'returns the expected results for the fields method' do fields = RbConfig::CONFIG['host_os'] =~ /freebsd/i ? fields_freebsd : fields_dragonfly expect(described_class.fields).to be_kind_of(Array) expect(described_class.fields).to eql(fields) end end context 'ProcTable::Struct members' do subject(:process){ described_class.ps(:pid => Process.pid) } it 'contains a pid member and returns the expected value' do expect(process).to respond_to(:pid) expect(process.pid).to be_kind_of(Numeric) expect(process.pid).to eql(Process.pid) end it 'contains a ppid member and returns the expected value' do expect(process).to respond_to(:ppid) expect(process.ppid).to be_kind_of(Integer) end it 'contains a pgid member and returns the expected value' do expect(process).to respond_to(:pgid) expect(process.pgid).to be_kind_of(Integer) end it 'contains a ruid member and returns the expected value' do expect(process).to respond_to(:ruid) expect(process.ruid).to be_kind_of(Integer) end it 'contains a rgid member and returns the expected value' do expect(process).to respond_to(:rgid) expect(process.rgid).to be_kind_of(Integer) end it 'contains a comm member and returns the expected value' do expect(process).to respond_to(:comm) expect(process.comm).to be_kind_of(String) end it 'contains a state member and returns the expected value', :freebsd do expect(process).to respond_to(:state) expect(process.state).to be_kind_of(String) end it 'contains a pctcpu member and returns the expected value', :freebsd do expect(process).to respond_to(:pctcpu) expect(process.pctcpu).to be_kind_of(Float) end it 'contains a oncpu member and returns the expected value', :freebsd do expect(process).to respond_to(:oncpu) expect(process.oncpu).to be_kind_of(Integer) end it 'contains a ttynum member and returns the expected value', :freebsd do expect(process).to respond_to(:ttynum) expect(process.ttynum).to be_kind_of(Integer) end it 'contains a ttydev member and returns the expected value', :freebsd do expect(process).to respond_to(:ttydev) expect(process.ttydev).to be_kind_of(String) end it 'contains a wmesg member and returns the expected value', :freebsd do expect(process).to respond_to(:wmesg) expect(process.wmesg).to be_kind_of(String) end it 'contains a runtime member and returns the expected value', :freebsd do expect(process).to respond_to(:runtime) expect(process.runtime).to be_kind_of(Integer) end it 'contains a priority member and returns the expected value', :freebsd do expect(process).to respond_to(:priority) expect(process.priority).to be_kind_of(Integer) end it 'contains a usrpri member and returns the expected value', :freebsd do expect(process).to respond_to(:usrpri) expect(process.usrpri).to be_kind_of(Integer) end it 'contains a nice member and returns the expected value' do expect(process).to respond_to(:nice) expect(process.nice).to be_kind_of(Integer) end it 'contains a cmdline member and returns the expected value' do expect(process).to respond_to(:cmdline) expect(process.cmdline).to be_kind_of(String) end it 'contains a start member and returns the expected value' do expect(process).to respond_to(:start) expect(process.start).to be_kind_of(Time) end it 'contains a maxrss member and returns the expected value', :freebsd do expect(process).to respond_to(:maxrss) expect(process.maxrss).to be_kind_of(Integer) end it 'contains a ixrss member and returns the expected value', :freebsd do expect(process).to respond_to(:ixrss) expect(process.ixrss).to be_kind_of(Integer) end # TODO: The value returned on PC BSD 10 does not appear to be valid. Investigate. it 'contains a idrss member and returns the expected value', :freebsd do expect(process).to respond_to(:idrss) expect(process.idrss).to be_kind_of(Numeric) end it 'contains a isrss member and returns the expected value', :freebsd do expect(process).to respond_to(:isrss) expect(process.isrss).to be_kind_of(Integer) end it 'contains a minflt member and returns the expected value', :freebsd do expect(process).to respond_to(:minflt) expect(process.minflt).to be_kind_of(Integer) end it 'contains a majflt member and returns the expected value', :freebsd do expect(process).to respond_to(:majflt) expect(process.majflt).to be_kind_of(Integer) end it 'contains a nswap member and returns the expected value', :freebsd do expect(process).to respond_to(:nswap) expect(process.nswap).to be_kind_of(Integer) end it 'contains a inblock member and returns the expected value', :freebsd do expect(process).to respond_to(:inblock) expect(process.inblock).to be_kind_of(Integer) end it 'contains a oublock member and returns the expected value', :freebsd do expect(process).to respond_to(:oublock) expect(process.oublock).to be_kind_of(Integer) end it 'contains a msgsnd member and returns the expected value', :freebsd do expect(process).to respond_to(:msgsnd) expect(process.msgsnd).to be_kind_of(Integer) end it 'contains a msgrcv member and returns the expected value', :freebsd do expect(process).to respond_to(:msgrcv) expect(process.msgrcv).to be_kind_of(Integer) end it 'contains a nsignals member and returns the expected value', :freebsd do expect(process).to respond_to(:nsignals) expect(process.nsignals).to be_kind_of(Integer) end it 'contains a nvcsw member and returns the expected value', :freebsd do expect(process).to respond_to(:nvcsw) expect(process.nvcsw).to be_kind_of(Integer) end it 'contains a nivcsw member and returns the expected value', :freebsd do expect(process).to respond_to(:nivcsw) expect(process.nivcsw).to be_kind_of(Integer) end it 'contains a utime member and returns the expected value', :freebsd do expect(process).to respond_to(:utime) expect(process.utime).to be_kind_of(Integer) end it 'contains a stime member and returns the expected value', :freebsd do expect(process).to respond_to(:stime) expect(process.stime).to be_kind_of(Integer) end end context 'C struct verification' do let(:dummy){ Class.new{ extend Mkmf::Lite } } it 'has a timeval struct of the expected size' do expect(Sys::ProcTableStructs::Timeval.size).to eq(dummy.check_sizeof('struct timeval', 'sys/time.h')) end it 'has an rtprio struct of the expected size' do expect(Sys::ProcTableStructs::RTPrio.size).to eq(dummy.check_sizeof('struct rtprio', 'sys/rtprio.h')) end it 'has an rusage struct of the expected size' do expect(Sys::ProcTableStructs::Rusage.size).to eq(dummy.check_sizeof('struct rusage', 'sys/resource.h')) end it 'has an kinfo_lwp struct of the expected size' do expect(Sys::ProcTableStructs::KInfoLWP.size).to eq(dummy.check_sizeof('struct kinfo_lwp', 'sys/kinfo.h')) end it 'has an kinfo_proc struct of the expected size' do expect(Sys::ProcTableStructs::KInfoProc.size).to eq(dummy.check_sizeof('struct kinfo_proc', 'sys/kinfo.h')) end end end <file_sep>require 'sys/proctable' # The Sys module serves as a namespace only module Sys # The Top class serves as a toplevel name for the 'top' method. class Top # The version of the sys-top library VERSION = '1.0.5'.freeze # Returns an array of Struct::ProcTableStruct elements containing up # to +num+ elements, sorted by +field+. The default number of elements # is 10, while the default field is 'pctcpu'. # # Exception: the default sort field is 'pid' on AIX, Darwin and Windows. # def self.top(num = 10, field = 'pctcpu') field = field.to_s if field.is_a?(Symbol) aix = RbConfig::CONFIG['host_os'] =~ /aix/i darwin = RbConfig::CONFIG['host_os'] =~ /darwin/i dragonfly = RbConfig::CONFIG['host_os'] =~ /dragonfly/i # Sort by pid on Windows and AIX by default if (File::ALT_SEPARATOR || aix || darwin) && field == 'pctcpu' field = 'pid' end if dragonfly && field == 'pctcpu' Sys::ProcTable.ps.sort_by{ |obj| obj.lwp.pctcpu }[0..num-1] else Sys::ProcTable.ps.sort_by{ |obj| obj.send(field) || '' }[0..num-1] end end end end <file_sep>module Sys class ProcTable # The version of the sys-proctable library VERSION = '1.3.0'.freeze end end <file_sep>####################################################################### # proctable.rb # # A pure Ruby version of sys-proctable for AIX 5.3 or later. ######################################################################## require 'sys/proctable/version' # The Sys module serves as a namespace only. module Sys # The ProcTable class encapsulates process table information. class ProcTable class Error < StandardError; end # There is no constructor private_class_method :new private @fields = [ # --- psinfo_t --- :flag, # process flags from proc struct p_flag :flag2, # process flags from proc struct p_flag2 :nlwp, # number of threads in process #:pad1, # reserved for future use :uid, # real user id :euid, # effective user id :gid, # real group id :egid, # effective group id :pid, # unique process id :ppid, # process id of parent :pgid, # pid of process group leader :sid, # session id :ttydev, # controlling tty device (device #) :s_ttydev, # controlling tty device name or '-' :addr, # internal address of proc struct :size, # process image size in KB (1024) units :rssize, # resident set size in KB (1024) units :start, # process start time, time since epoch :time, # usr+sys cpu time for this process :cid, # corral id #:pad2, # reserved for future use :argc, # initial argument count :argv, # address of initial argument vector in user process :envp, # address of initial environment vector in user process :fname, # last component of exec()ed pathname :psargs, # initial characters of arg list #:pad, # reserved for future use # --- lwpsinfo_t --- :lwpid, # thread id #:addr, # internal address of thread :wchan, # wait addr for sleeping thread #:flag, # thread flags :wtype, # type of thread wait :state, # thread state :sname, # printable thread state character :nice, # nice for cpu usage :pri, # priority, high value = high priority :policy, # scheduling policy :clname, # printable scheduling policy string :onpro, # processor on which thread last ran :bindpro, # processor to which thread is bound :ptid, # pthread id #:pad1, # reserved for future use #:pad, # reserved for future use # --- prmap_t --- :map, # array of prmap_t structures # --- lwp --- #:lwp # array of lwp information # other... :fd, # array of used file descriptors :cmd_args, # array of command line arguments :environ, # hash of environment associated with the process :cmdline, # joined cmd_args if present, otherwise psargs :cwd, # current working directory ] @psinfo_pack_directive = [ 'L', # pr_flag 'L', # pr_flag2 'L', # pr_nlwp 'L', # pr__pad1 'Q', # pr_uid 'Q', # pr_euid 'Q', # pr_gid 'Q', # pr_egid 'Q', # pr_pid 'Q', # pr_ppid 'Q', # pr_pgid 'Q', # pr_sid 'Q', # pr_ttydev 'Q', # pr_addr 'Q', # pr_size 'Q', # pr_rssize 'QlL', # pr_start 'QlL', # pr_time 'S', # pr_cid 'S', # pr__pad2 'L', # pr_argc 'Q', # pr_argv 'Q', # pr_envp 'A16', # pr_fname[PRFNSZ] 'A80', # pr_psargs[PRARGSZ] 'Q8', # pr__pad[8] # --- lwpsinfo_t --- pr_lwp 'Q', # pr_lwpid 'Q', # pr_addr 'Q', # pr_wchan 'L', # pr_flag 'C', # pr_wtype 'c', # pr_state 'A', # pr_sname 'C', # pr_nice 'l', # pr_pri 'L', # pr_policy 'A8', # pr_clname 'l', # pr_onpro 'l', # pr_bindpro 'L', # pr_ptid 'L', # pr__pad1 'Q7' # pr__pad[7] ].join # --- prmap_t --- @map_fields = [ :size, :vaddr, :mapname, :off, :mflags, :s_mflags, :pathoff, :alias, :gp, #:pad, :path, ] @prmap_pack_directive = [ 'Q', # pr_size 'Q', # pr_vaddr 'A64', # pr_mapname[PRMAPSZ] 'Q', # pr_off 'L', # pr_mflags 'L', # pr_pathoff 'Q', # pr_alias 'Q', # pr_gp 'Q8', # pr__pad[8] ].join # prmap_t pr_mflags PR_MFLAGS = [ [ 0x80000000, 'main' ], # MA_MAINEXEC - main executable [ 0x40000000, 'kernel' ], # MA_KERNTEXT - kernel text [ 0x00000004, 'read' ], # MA_READ - readable [ 0x00000002, 'write' ], # MA_WRITE - writable [ 0x00000001, 'exec' ], # MA_EXEC - executable [ 0x00000008, 'shared' ], # MA_SHARED - shared memory region [ 0x00000010, 'heap' ], # MA_BREAK - heap -- grown by brk [ 0x00000020, 'stack' ], # MA_STACK - stack -- grows on stack faults ] @devs = {} Dir['/dev/**/*'].map do |filename| begin rdev = File.stat(filename).rdev rescue next end @devs[rdev] = filename[5..-1] if rdev.nonzero? end public ProcTableStruct = Struct.new("ProcTableStruct", *@fields) do alias comm fname end ProcTableMapStruct = Struct.new("ProcTableMapStruct", *@map_fields) # In block form, yields a ProcTableStruct for each process entry that you # have rights to. This method returns an array of ProcTableStruct's in # non-block form. # # If a +pid+ is provided, then only a single ProcTableStruct is yielded or # returned, or nil if no process information is found for that +pid+. # # Example: # # # Iterate over all processes # ProcTable.ps do |proc_info| # p proc_info # end # # # Print process table information for only pid 1001 # p ProcTable.ps(pid: 1001) # def self.ps(**kwargs) pid = kwargs[:pid] raise TypeError unless pid.is_a?(Numeric) if pid array = block_given? ? nil : [] struct = nil Dir.foreach("/proc") do |file| next if file =~ /\D/ # Skip non-numeric entries under /proc # Only return information for a given pid, if provided if pid next unless file.to_i == pid end # Skip over any entries we don't have permissions to read next unless File.readable?("/proc/#{file}/psinfo") psinfo = IO.read("/proc/#{file}/psinfo") rescue next psinfo_array = psinfo.unpack(@psinfo_pack_directive) struct = ProcTableStruct.new struct.flag = psinfo_array[0] # pr_flag struct.flag2 = psinfo_array[1] # pr_flag2 struct.nlwp = psinfo_array[2] # pr_nlwp # pr__pad1 struct.uid = psinfo_array[4] # pr_uid struct.euid = psinfo_array[5] # pr_euid struct.gid = psinfo_array[6] # pr_gid struct.egid = psinfo_array[7] # pr_egid struct.pid = psinfo_array[8] # pr_pid struct.ppid = psinfo_array[9] # pr_ppid struct.pgid = psinfo_array[10] # pr_pgid struct.sid = psinfo_array[11] # pr_sid struct.ttydev = psinfo_array[12] # pr_ttydev # convert from 64-bit dev_t to 32-bit dev_t and then map the device # number to a name ttydev = struct.ttydev ttydev = (((ttydev & 0x0000FFFF00000000) >> 16) | (ttydev & 0xFFFF)) struct.s_ttydev = @devs.has_key?(ttydev) ? @devs[ttydev] : '-' struct.addr = psinfo_array[13] # pr_addr struct.size = psinfo_array[14] * 1024 # pr_size struct.rssize = psinfo_array[15] * 1024 # pr_rssize struct.start = Time.at(psinfo_array[16], psinfo_array[17]) # pr_start # skip pr_start.__pad struct.time = psinfo_array[19] # pr_time # skip pr_time.tv_nsec and pr_time.__pad struct.cid = psinfo_array[22] # pr_cid # skip pr__pad2 struct.argc = psinfo_array[24] # pr_argc struct.argv = psinfo_array[25] # pr_argv struct.envp = psinfo_array[26] # pr_envp struct.fname = psinfo_array[27] # pr_fname struct.psargs = psinfo_array[28] # pr_psargs # skip pr__pad ### lwpsinfo_t info struct.lwpid = psinfo_array[37] # pr_lwpid # skip pr_addr struct.wchan = psinfo_array[39] # pr_wchan # skip pr_flag struct.wtype = psinfo_array[41] # pr_wtype struct.state = psinfo_array[42] # pr_state struct.sname = psinfo_array[43] # pr_sname struct.nice = psinfo_array[44] # pr_nice struct.pri = psinfo_array[45] # pr_pri struct.policy = psinfo_array[46] # pr_policy struct.clname = psinfo_array[47] # pr_clname struct.onpro = psinfo_array[48] # pr_onpro struct.bindpro = psinfo_array[49] # pr_bindpro struct.ptid = psinfo_array[50] # pr_ptid # skip pr__pad1 # skip pr__pad # Get the full command line out of /proc/<pid>/as. begin File.open("/proc/#{file}/as", 'rb') do |fd| np = fd.sysseek(struct.argv, IO::SEEK_SET) if np != struct.argv raise Error, "argv seek to #{struct.argv}, result #{np}", caller end argv = fd.sysread(4).unpack('L')[0] np = fd.sysseek(argv, IO::SEEK_SET) if np != argv raise Error, "*argv seek to #{argv}, result #{np}", caller end argv = fd.sysread(4 * struct.argc).unpack("L#{struct.argc}") struct.cmd_args = [] argv.each_with_index do |address, i| np = fd.sysseek(address, IO::SEEK_SET) if np != address raise Error, "argv[#{i}] seek to #{address}, result #{np}", caller end data = fd.sysread(512)[/^[^\0]*/] # Null strip struct.cmd_args << data end # Get the environment hash associated with the process. struct.environ = {} # First have to go to the address given by struct.envp. That will # give us the address of the environment pointer array. np = fd.sysseek(struct.envp, IO::SEEK_SET) if np != struct.envp raise Error, "envp seek to #{struct.envp}, result #{np}", caller end envloc = fd.sysread(4).unpack('L')[0] n = 0 loop do np = fd.sysseek(envloc, IO::SEEK_SET) if np != envloc raise Error, "envp[#{n}] seek to #{envloc}, result #{np}", caller end envp = fd.sysread(4).unpack("L")[0] break if envp.zero? np = fd.sysseek(envp, IO::SEEK_SET) data = fd.sysread(1024)[/^[^\0]*/] # Null strip key, value = data.split('=') struct.environ[key] = value envloc += 4 n += 1 end end rescue Errno::EACCES, Errno::EOVERFLOW, EOFError # Skip this if we don't have proper permissions, if there's # no associated environment, or if there's a largefile issue. rescue Errno::ENOENT next # The process has terminated. Bail out! end # Information from /proc/<pid>/fd. This returns an array of # numeric file descriptors used by the process. struct.fd = Dir["/proc/#{file}/fd/*"].map { |f| File.basename(f).to_i } # Use the cmd_args as the cmdline if available. Otherwise use # the psargs. This struct member is provided to provide a measure # of consistency with the other platform implementations. if struct.cmd_args.nil? || struct.cmd_args.empty? struct.cmdline = struct.psargs else struct.cmdline = struct.cmd_args.join(' ') end # get current working directory from /proc/<pid>/cwd struct.cwd = File.readlink("/proc/#{file}/cwd") rescue nil # get virtual address map from /proc/<pid>/map begin struct.map = [] File.open("/proc/#{file}/map", 'rb') do |fd| loop do prmap_array = fd.sysread(176).unpack(@prmap_pack_directive) break if prmap_array[0].zero? map_struct = ProcTableMapStruct.new map_struct.size = prmap_array[0] # pr_size map_struct.vaddr = prmap_array[1] # pr_vaddr map_struct.mapname = prmap_array[2] # pr_mapname map_struct.off = prmap_array[3] # pr_off map_struct.mflags = prmap_array[4] # pr_mflags # convert pr_mflags value to string sort of like procmap outputs mflags = map_struct.mflags map_struct.s_mflags = '' sep = '' PR_MFLAGS.each do |flag| if (mflags & flag[0]).nonzero? map_struct.s_mflags << sep << flag[1] sep = '/' mflags &= ~flag[0] end end if mflags.nonzero? map_struct.s_mflags << sep << sprintf('%08x', mflags) end map_struct.pathoff = prmap_array[5] # pr_pathoff map_struct.alias = prmap_array[6] # pr_alias map_struct.gp = prmap_array[7] # pr_gp struct.map << map_struct end struct.map.each do |m| next if m.pathoff.zero? fd.sysseek(m.pathoff, IO::SEEK_SET) buf = fd.sysread(4096) buf =~ /^([^\0]*)\0([^\0]*)\0/ m.path = $2.empty? ? $1 : "#{$1}(#{$2})" end end struct.map = nil if struct.map.empty? rescue struct.map = nil end # This is read-only data struct.freeze if block_given? yield struct else array << struct end end pid ? struct : array end # Returns an array of fields that each ProcTableStruct will contain. This # may be useful if you want to know in advance what fields are available # without having to perform at least one read of the /proc table. # # Example: # # Sys::ProcTable.fields.each do |field| # puts "Field: #{field}" # end # def self.fields @fields.map{ |f| f.to_s } end end end <file_sep># frozen_string_literal: true module Sys class ProcTable # Smaps represents a process' memory size for all mapped files # # A single mapped file memory entry looks like this: # # 00400000-004d4000 r-xp 00000000 fd:00 785 /bin/bash # Size: 848 kB # Rss: 572 kB # Pss: 572 kB # Shared_Clean: 0 kB # Shared_Dirty: 0 kB # Private_Clean: 572 kB # Private_Dirty: 0 kB # Referenced: 572 kB # Anonymous: 0 kB # AnonHugePages: 0 kB # Swap: 0 kB # KernelPageSize: 4 kB # MMUPageSize: 4 kB # # Have a look at `man 5 proc` on a linux distribution, to get some more # information about the lines and fields in `/proc/[pid]/smaps`. # # Example: # # smaps = Smaps.new(123, IO.read("/proc/1234/smaps") # # # result # # #<Sys::ProcTable::Smaps:0x007f8ac5930768 # @pid=123, # @pss=107000, # @rss=368000, # @uss=96000, # @swap=192000, # @vss=136752000 # > # # smaps.pss # => 109568 # smaps.rss # => 376832 # smaps.uss # => 98304 # smaps.swap # => 196608 # smaps.vss # => 140034048 # class Smaps # Process ID for this smaps attr_reader :pid # Proportional set size # # PSS is the size of private pages added to each shared mapping's size # divided by the number of processes that share it. It is meant to # provide a better representation of the amount of memory actually used # by a process. # # If a process has 4k of private pages, 4k of shared pages shared with one # other process, and 3k of pages shared with two other processes, the PSS # is: # # 4k + (4k / 2) + (3k / 3) = 7k # attr_reader :pss alias proportional_set_size pss # Resident set size # # RSS is the total size of all pages, shared or not, mapped to a process. attr_reader :rss alias resident_set_size rss # Unique set size # # USS is the total size of all private pages mapped to a process. attr_reader :uss alias unique_set_size uss # Swap # # Swap is the total size of all swapped pages mapped to a process. attr_reader :swap # Virtual set size # # VSS is the total accessible address space in a process. Since files are # lazily loaded, this value represents the total size of all mapped files # if they were all loaded. attr_reader :vss alias virtual_set_size vss # Create a new smaps object # # # This expects a process id and a string containing the contents of # /proc/PID/smaps - see `man 5 proc` for a reference. # # The smaps contents are parsed and memory sizes are calculated in bytes. def initialize(pid, smaps_contents) @pid = pid @pss = 0 @rss = 0 @uss = 0 @swap = 0 @vss = 0 smaps_contents.each_line { |line| parse_smaps_line(line) } end alias to_s inspect private def parse_smaps_line(line) case line when /^Pss:\s+?(\d+)/ @pss += Regexp.last_match[1].to_i * 1000 when /^Rss:\s+?(\d+)/ @rss += Regexp.last_match[1].to_i * 1000 when /^Size:\s+?(\d+)/ @vss += Regexp.last_match[1].to_i * 1000 when /^Swap:\s+?(\d+)/ @swap += Regexp.last_match[1].to_i * 1000 when /^Private_(Clean|Dirty):\s+?(\d+)/ @uss += Regexp.last_match[2].to_i * 1000 end end end end end <file_sep>####################################################################### # sys_proctable_sunos_spec.rb # # Test suite for sys-proctable for SunOS/Solaris. This should be run # run via the 'rake spec' task. ####################################################################### require 'spec_helper' RSpec.describe Sys::ProcTable, :sunos do let(:fields){ %w[ flag nlwp pid ppid pgid sid uid euid gid egid addr size rssize ttydev pctcpu pctmem start time ctime fname psargs wstat argc argv envp dmodel taskid projid nzomb poolid zoneid contract lwpid wchan stype state sname nice syscall pri clname name onpro bindpro bindpset count tstamp create term rtime utime stime ttime tftime dftime kftime ltime slptime wtime stoptime minf majf nswap inblk oublk msnd mrcv sigs vctx ictx sysc ioch path contracts fd cmd_args environ cmdline ] } context 'fields singleton method' do it 'responds to a fields method' do expect(described_class).to respond_to(:fields) end it 'returns the expected results for the fields method' do expect(described_class.fields).to be_kind_of(Array) expect(described_class.fields).to eql(fields) end end context 'ProcTable::Struct members' do subject(:process){ described_class.ps(:pid => Process.pid) } it 'contains a pid member and returns the expected value' do expect(process).to respond_to(:pid) expect(process.pid).to be_kind_of(Numeric) expect(process.pid).to eql(Process.pid) end it 'contains a ppid member and returns the expected value' do expect(process).to respond_to(:ppid) expect(process.ppid).to be_kind_of(Numeric) expect(process.ppid).to eql(Process.ppid) end it 'contains a pgid member and returns the expected value' do expect(process).to respond_to(:pgid) expect(process.pgid).to be_kind_of(Numeric) expect(process.pgid).to eql(Process.getpgrp) end it 'has a flag member that returns the expected value' do expect(process).to respond_to(:flag) expect(process.flag).to be_kind_of(Integer) end it 'has an nlwp member that returns the expected value' do expect(process).to respond_to(:nlwp) expect(process.nlwp).to be_kind_of(Integer) expect(process.nlwp).to be >= 0 end it 'has a sid member that returns the expected value' do expect(process).to respond_to(:sid) expect(process.sid).to be_kind_of(Integer) expect(process.sid).to be >= 0 end it 'has a uid member that returns the expected value' do expect(process).to respond_to(:uid) expect(process.uid).to be_kind_of(Integer) expect(process.uid).to eql(Process.uid) end it 'has a euid member that returns the expected value' do expect(process).to respond_to(:euid) expect(process.euid).to be_kind_of(Integer) expect(process.euid).to eql(Process.euid) end it 'has a gid member that returns the expected value' do expect(process).to respond_to(:gid) expect(process.gid).to be_kind_of(Integer) expect(process.gid).to eql(Process.gid) end it 'has a egid member that returns the expected value' do expect(process).to respond_to(:egid) expect(process.egid).to be_kind_of(Integer) expect(process.egid).to eql(Process.egid) end it 'has an addr member that returns the expected value' do expect(process).to respond_to(:addr) expect(process.addr).to be_kind_of(Integer) expect(process.addr).to be >= 0 end it 'has a size member that returns the expected value' do expect(process).to respond_to(:size) expect(process.size).to be_kind_of(Integer) expect(process.size).to be >= 0 end it 'has a rssize member that returns the expected value' do expect(process).to respond_to(:rssize) expect(process.rssize).to be_kind_of(Integer) expect(process.rssize).to be >= 0 end it 'has a ttydev member that returns the expected value' do expect(process).to respond_to(:ttydev) expect(process.ttydev).to be_kind_of(Integer) expect(process.ttydev).to be >= -1 end it 'has a pctcpu member that returns the expected value' do expect(process).to respond_to(:pctcpu) expect(process.pctcpu).to be_kind_of(Float) expect(process.pctcpu).to be >= 0.0 end it 'has a pctmem member that returns the expected value' do expect(process).to respond_to(:pctmem) expect(process.pctmem).to be_kind_of(Float) expect(process.pctmem).to be >= 0.0 end it 'has a start member that returns the expected value' do expect(process).to respond_to(:start) expect(process.start).to be_kind_of(Time) end it 'has a time member that returns the expected value' do expect(process).to respond_to(:time) expect(process.time).to be_kind_of(Integer) expect(process.time).to be >= 0 end it 'has a ctime member that returns the expected value' do expect(process).to respond_to(:ctime) expect(process.ctime).to be_kind_of(Integer) expect(process.ctime).to be >= 0 end it 'has a fname member that returns the expected value' do expect(process).to respond_to(:fname) expect(process.fname).to be_kind_of(String) expect(process.fname.size).to be > 0 end it 'has a comm alias member' do expect(process.method(:comm)).to eql(process.method(:fname)) end it 'has a psargs member that returns the expected value' do expect(process).to respond_to(:psargs) expect(process.psargs).to be_kind_of(String) expect(process.psargs.size).to be > 0 end it 'has a wstat member that returns the expected value' do expect(process).to respond_to(:wstat) expect(process.wstat).to be_kind_of(Integer) expect(process.wstat).to be >= 0 end it 'has an args member that returns the expected value' do expect(process).to respond_to(:argc) expect(process.argc).to be_kind_of(Integer) expect(process.argc).to be >= 0 end it 'has an argv member that returns the expected value' do expect(process).to respond_to(:argv) expect(process.argv).to be_kind_of(Integer) expect(process.argv).to be >= 0 end it 'has a envp member that returns the expected value' do expect(process).to respond_to(:envp) expect(process.envp).to be_kind_of(Integer) expect(process.envp).to be >= 0 end it 'has a dmodel member that returns the expected value' do expect(process).to respond_to(:dmodel) expect(process.dmodel).to be_kind_of(Integer) expect(process.dmodel).to be >= 0 end it 'has a taskid member that returns the expected value' do expect(process).to respond_to(:taskid) expect(process.taskid).to be_kind_of(Integer) expect(process.taskid).to be >= 0 end it 'has a projid member that returns the expected value' do expect(process).to respond_to(:projid) expect(process.projid).to be_kind_of(Integer) expect(process.projid).to be >= 0 end it 'has a nzomb member that returns the expected value' do expect(process).to respond_to(:nzomb) expect(process.nzomb).to be_kind_of(Integer) expect(process.nzomb).to be >= 0 end it 'has a poolid member that returns the expected value' do expect(process).to respond_to(:poolid) expect(process.poolid).to be_kind_of(Integer) expect(process.poolid).to be >= 0 end it 'has a zoneid member that returns the expected value' do expect(process).to respond_to(:zoneid) expect(process.zoneid).to be_kind_of(Integer) expect(process.zoneid).to be >= 0 end it 'has a contract member that returns the expected value' do expect(process).to respond_to(:contract) expect(process.contract).to be_kind_of(Integer) expect(process.contract).to be >= 0 end end context 'lwpsinfo struct' do process { described_class.ps(:pid => Process.pid) } it 'has a lwpid member that returns the expected value' do expect(process).to respond_to(:lwpid) expect(process.lwpid).to be_kind_of(Integer) expect(process.lwpid).to be >= 0 end it 'has a wchan member that returns the expected value' do expect(process).to respond_to(:wchan) expect(process.wchan).to be_kind_of(Integer) expect(process.wchan).to be >= 0 end it 'has a stype member that returns the expected value' do expect(process).to respond_to(:stype) expect(process.stype).to be_kind_of(Integer) expect(process.stype).to be >= 0 end it 'has a state member that returns the expected value' do expect(process).to respond_to(:state) expect(process.state).to be_kind_of(Integer) expect(process.state).to be >= 0 end it 'has a sname member that returns the expected value' do expect(process).to respond_to(:sname) expect(process.sname).to be_kind_of(String) expect(%w[S R Z T I O]).to include(process.sname) end it 'has a nice member that returns the expected value' do expect(process).to respond_to(:nice) expect(process.nice).to be_kind_of(Integer) expect(process.nice).to be >= 0 end it 'has a syscall member that returns the expected value' do expect(process).to respond_to(:syscall) expect(process.syscall).to be_kind_of(Integer) expect(process.syscall).to be >= 0 end it 'has a pri member that returns the expected value' do expect(process).to respond_to(:pri) expect(process.pri).to be_kind_of(Integer) expect(process.pri).to be >= 0 end it 'has a clname member that returns the expected value' do expect(process).to respond_to(:clname) expect(process.clname).to be_kind_of(String) expect(process.clname.size).to be_between(0, 8) end it 'has a name member that returns the expected value' do expect(process).to respond_to(:name) expect(process.name).to be_kind_of(String) expect(process.name.size).to be_between(0, 16) end it 'has an onpro member that returns the expected value' do expect(process).to respond_to(:onpro) expect(process.onpro).to be_kind_of(Integer) expect(process.onpro).to be >= 0 end it 'has a bindpro member that returns the expected value' do expect(process).to respond_to(:bindpro) expect(process.bindpro).to be_kind_of(Integer) expect(process.bindpro).to be >= -1 end it 'has a bindpset member that returns the expected value' do expect(process).to respond_to(:bindpset) expect(process.bindpset).to be_kind_of(Integer) expect(process.bindpset).to be >= -1 end end end <file_sep>######################################################################## # bench_ps.rb # # Benchmark program to show overall speed and compare the block form # versus the non-block form. You should run this benchmark via the # 'rake bench' Rake task. ######################################################################## require 'benchmark' require 'sys/proctable' MAX = 10 Benchmark.bm do |bench| bench.report("Block form"){ MAX.times{ Sys::ProcTable.ps{} } } bench.report("Non-block form"){ MAX.times{ Sys::ProcTable.ps } } end <file_sep>require 'ffi' require 'sys/proctable/version' module Sys class ProcTable extend FFI::Library # Error typically raised if the ProcTable.ps method fails. class Error < StandardError; end # There is no constructor private_class_method :new private ffi_lib :kvm attach_function :devname, [:dev_t, :mode_t], :string attach_function :kvm_open, [:string, :string, :string, :int, :string], :pointer attach_function :kvm_close, [:pointer], :int attach_function :kvm_getprocs, [:pointer, :int, :int, :pointer], :pointer attach_function :kvm_getargv, [:pointer, :pointer, :int], :pointer POSIX_ARG_MAX = 4096 KERN_PROC_PID = 1 KERN_PROC_PROC = 8 S_IFCHR = 0020000 WMESGLEN = 8 LOCKNAMELEN = 8 OCOMMLEN = 16 COMMLEN = 19 KI_EMULNAMELEN = 16 KI_NGROUPS = 16 LOGNAMELEN = 17 KI_NSPARE_INT = 9 KI_NSPARE_LONG = 12 KI_NSPARE_PTR = 6 class Timeval < FFI::Struct layout(:tv_sec, :time_t, :tv_usec, :suseconds_t) end class Priority < FFI::Struct layout( :pri_class, :uchar, :pri_level, :uchar, :pri_native, :uchar, :pri_user, :uchar ) end class Rusage < FFI::Struct layout( :ru_utime, Timeval, :ru_stime, Timeval, :ru_maxrss, :long, :ru_ixrss, :long, :ru_idrss, :long, :ru_isrss, :long, :ru_minflt, :long, :ru_majflt, :long, :ru_nswap, :long, :ru_inblock, :long, :ru_oublock, :long, :ru_msgsnd, :long, :ru_msgrcv, :long, :ru_nsignals, :long, :ru_nvcsw, :long, :ru_nivcsw, :long ) end class Pargs < FFI::Struct layout( :ar_ref, :uint, :ar_length, :uint, :ar_args, [:uchar, 1] ) end class KInfoProc < FFI::Struct layout( :ki_structsize, :int, :ki_layout, :int, :ki_args, :pointer, :ki_paddr, :pointer, :ki_addr, :pointer, :ki_tracep, :pointer, :ki_textvp, :pointer, :ki_fd, :pointer, :ki_vmspace, :pointer, :ki_wchan, :pointer, :ki_pid, :pid_t, :ki_ppid, :pid_t, :ki_pgid, :pid_t, :ki_tpgid, :pid_t, :ki_sid, :pid_t, :ki_tsid, :pid_t, :ki_jobc, :short, :ki_spare_short1, :short, :ki_tdev, :dev_t, :ki_siglist, [:uint32_t, 4], :ki_sigmask, [:uint32_t, 4], :ki_sigignore, [:uint32_t, 4], :ki_sigcatch, [:uint32_t, 4], :ki_uid, :uid_t, :ki_ruid, :uid_t, :ki_svuid, :uid_t, :ki_rgid, :gid_t, :ki_svgid, :gid_t, :ki_ngroups, :short, :ki_spare_short2, :short, :ki_groups, [:gid_t, KI_NGROUPS], :ki_size, :uint32_t, :ki_rssize, :segsz_t, :ki_swrss, :segsz_t, :ki_tsize, :segsz_t, :ki_dsize, :segsz_t, :ki_ssize, :segsz_t, :ki_xstat, :u_short, :ki_acflag, :u_short, :ki_pctcpu, :fixpt_t, :ki_estcpu, :uint, :ki_slptime, :uint, :ki_swtime, :uint, :ki_swtime, :int, :ki_runtime, :uint64_t, :ki_start, Timeval, :ki_childtime, Timeval, :ki_flag, :long, :ki_kiflag, :long, :ki_traceflag, :int, :ki_stat, :char, :ki_nice, :char, :ki_lock, :char, :ki_rqindex, :char, :ki_oncpu, :uchar, :ki_lastcpu, :uchar, :ki_ocomm, [:char, OCOMMLEN+1], :ki_wmesg, [:char, WMESGLEN+1], :ki_login, [:char, LOGNAMELEN+1], :ki_lockname, [:char, LOCKNAMELEN+1], :ki_comm, [:char, COMMLEN+1], :ki_emul, [:char, KI_EMULNAMELEN+1], :ki_sparestrings, [:char, 68], :ki_spareints, [:int, KI_NSPARE_INT], :ki_cr_flags, :uint, :ki_jid, :int, :ki_numthreads, :int, :ki_tid, :pid_t, :ki_pri, Priority, :ki_rusage, Rusage, :ki_rusage_ch, Rusage, :ki_pcb, :pointer, :ki_kstack, :pointer, :ki_udata, :pointer, :ki_tdaddr, :pointer, :ki_spareptrs, [:pointer, KI_NSPARE_PTR], :ki_sparelongs, [:long, KI_NSPARE_LONG], :ki_sflags, :long, :ki_tdflags, :long ) end @fields = %w[ pid ppid pgid tpgid sid tsid jobc uid ruid rgid ngroups groups size rssize swrss tsize dsize ssize xstat acflag pctcpu estcpu slptime swtime runtime start flag state nice lock rqindex oncpu lastcpu wmesg login lockname comm ttynum ttydev jid priority usrpri cmdline utime stime maxrss ixrss idrss isrss minflt majflt nswap inblock oublock msgsnd msgrcv nsignals nvcsw nivcsw ] ProcTableStruct = Struct.new('ProcTableStruct', *@fields) public # In block form, yields a ProcTableStruct for each process entry that you # have rights to. This method returns an array of ProcTableStruct's in # non-block form. # # If a +pid+ is provided, then only a single ProcTableStruct is yielded or # returned, or nil if no process information is found for that +pid+. # # Example: # # # Iterate over all processes # ProcTable.ps do |proc_info| # p proc_info # end # # # Print process table information for only pid 1001 # p ProcTable.ps(1001) # def self.ps(**kwargs) pid = kwargs[:pid] begin kd = kvm_open(nil, nil, nil, 0, nil) if kd.null? raise SystemCallError.new('kvm_open', FFI.errno) end ptr = FFI::MemoryPointer.new(:int) # count if pid procs = kvm_getprocs(kd, KERN_PROC_PID, pid, ptr) else procs = kvm_getprocs(kd, KERN_PROC_PROC, 0, ptr) end if procs.null? if pid && FFI.errno == Errno::ESRCH::Errno return nil else raise SystemCallError.new('kvm_getprocs', FFI.errno) end end count = ptr.read_int array = [] 0.upto(count-1){ |i| cmd = nil kinfo = KInfoProc.new(procs[i * KInfoProc.size]) args = kvm_getargv(kd, kinfo, 0) unless args.null? cmd = [] until ((ptr = args.read_pointer).null?) cmd << ptr.read_string args += FFI::Type::POINTER.size end cmd = cmd.join(' ') end struct = ProcTableStruct.new( kinfo[:ki_pid], kinfo[:ki_ppid], kinfo[:ki_pgid], kinfo[:ki_tpgid], kinfo[:ki_sid], kinfo[:ki_tsid], kinfo[:ki_jobc], kinfo[:ki_uid], kinfo[:ki_ruid], kinfo[:ki_rgid], kinfo[:ki_ngroups], kinfo[:ki_groups].to_a[0...kinfo[:ki_ngroups]], kinfo[:ki_size], kinfo[:ki_rssize], kinfo[:ki_swrss], kinfo[:ki_tsize], kinfo[:ki_dsize], kinfo[:ki_ssize], kinfo[:ki_xstat], kinfo[:ki_acflag], kinfo[:ki_pctcpu].to_f, kinfo[:ki_estcpu], kinfo[:ki_slptime], kinfo[:ki_swtime], kinfo[:ki_runtime], Time.at(kinfo[:ki_start][:tv_sec]), kinfo[:ki_flag], get_state(kinfo[:ki_stat]), kinfo[:ki_nice], kinfo[:ki_lock], kinfo[:ki_rqindex], kinfo[:ki_oncpu], kinfo[:ki_lastcpu], kinfo[:ki_wmesg].to_s, kinfo[:ki_login].to_s, kinfo[:ki_lockname].to_s, kinfo[:ki_comm].to_s, kinfo[:ki_tdev], devname(kinfo[:ki_tdev], S_IFCHR), kinfo[:ki_jid], kinfo[:ki_pri][:pri_level], kinfo[:ki_pri][:pri_user], cmd, kinfo[:ki_rusage][:ru_utime][:tv_sec], kinfo[:ki_rusage][:ru_stime][:tv_sec], kinfo[:ki_rusage][:ru_maxrss], kinfo[:ki_rusage][:ru_ixrss], kinfo[:ki_rusage][:ru_idrss], kinfo[:ki_rusage][:ru_isrss], kinfo[:ki_rusage][:ru_minflt], kinfo[:ki_rusage][:ru_majflt], kinfo[:ki_rusage][:ru_nswap], kinfo[:ki_rusage][:ru_inblock], kinfo[:ki_rusage][:ru_oublock], kinfo[:ki_rusage][:ru_msgsnd], kinfo[:ki_rusage][:ru_msgrcv], kinfo[:ki_rusage][:ru_nsignals], kinfo[:ki_rusage][:ru_nvcsw], kinfo[:ki_rusage][:ru_nivcsw] ) struct.freeze # This is readonly data if block_given? yield struct else array << struct end } ensure kvm_close(kd) unless kd.null? end if block_given? nil else pid ? array.first : array end end # Returns an array of fields that each ProcTableStruct will contain. This # may be useful if you want to know in advance what fields are available # without having to perform at least one read of the /proc table. # # Example: # # Sys::ProcTable.fields.each{ |field| # puts "Field: #{field}" # } # def self.fields @fields end private SIDL = 1 SRUN = 2 SSLEEP = 3 SSTOP = 4 SZOMB = 5 SWAIT = 6 SLOCK = 7 def self.get_state(int) case int when SIDL; "idle" when SRUN; "run" when SSLEEP; "sleep" when SSTOP; "stop" when SZOMB; "zombie" when SWAIT; "waiting" when SLOCK; "locked" else; "unknown" end end end end <file_sep>require 'sys/proctable/version' require 'ffi' module Sys class ProcTable extend FFI::Library # Error typically raised if the ProcTable.ps method fails. class Error < StandardError; end # There is no constructor private_class_method :new PROC_PIDTASKALLINFO = 2 PROC_PIDTHREADINFO = 5 PROC_PIDLISTTHREADS = 6 private_constant :PROC_PIDTASKALLINFO private_constant :PROC_PIDTHREADINFO private_constant :PROC_PIDLISTTHREADS CTL_KERN = 1 KERN_PROCARGS = 38 KERN_PROCARGS2 = 49 MAXCOMLEN = 16 MAXPATHLEN = 256 private_constant :CTL_KERN private_constant :KERN_PROCARGS private_constant :KERN_PROCARGS2 private_constant :MAXCOMLEN private_constant :MAXPATHLEN MAXTHREADNAMESIZE = 64 PROC_PIDPATHINFO_MAXSIZE = MAXPATHLEN * 4 private_constant :MAXTHREADNAMESIZE private_constant :PROC_PIDPATHINFO_MAXSIZE # JRuby/Truffleruby on Mac unless defined? FFI::StructLayout::CharArray if defined? FFI::StructLayout::CharArrayProxy FFI::StructLayout::CharArray = FFI::StructLayout::CharArrayProxy else FFI::StructLayout::CharArray = FFI::Struct::CharArray end end class ProcBsdInfo < FFI::Struct layout( :pbi_flags, :uint32_t, :pbi_status, :uint32_t, :pbi_xstatus, :uint32_t, :pbi_pid, :uint32_t, :pbi_ppid, :uint32_t, :pbi_uid, :uid_t, :pbi_gid, :uid_t, :pbi_ruid, :uid_t, :pbi_rgid, :gid_t, :pbi_svuid, :uid_t, :pbi_svgid, :gid_t, :rfu1, :uint32_t, :pbi_comm, [:char, MAXCOMLEN], :pbi_name, [:char, MAXCOMLEN * 2], :pbi_nfiles, :uint32_t, :pbi_pgid, :uint32_t, :pbi_pjobc, :uint32_t, :e_tdev, :uint32_t, :e_tpgid, :uint32_t, :pbi_nice, :int32_t, :pbi_start_tvsec, :uint64_t, :pbi_start_tvusec, :uint64_t ) end private_constant :ProcBsdInfo class ProcTaskInfo < FFI::Struct layout( :pti_virtual_size, :uint64_t, :pti_resident_size, :uint64_t, :pti_total_user, :uint64_t, :pti_total_system, :uint64_t, :pti_threads_user, :uint64_t, :pti_threads_system, :uint64_t, :pti_policy, :int32_t, :pti_faults, :int32_t, :pti_pageins, :int32_t, :pti_cow_faults, :int32_t, :pti_messages_sent, :int32_t, :pti_messages_received, :int32_t, :pti_syscalls_mach, :int32_t, :pti_syscalls_unix, :int32_t, :pti_csw, :int32_t, :pti_threadnum, :int32_t, :pti_numrunning, :int32_t, :pti_priority, :int32_t ) end private_constant :ProcTaskInfo class ProcThreadInfo < FFI::Struct layout( :pth_user_time, :uint64_t, :pth_system_time, :uint64_t, :pth_cpu_usage, :int32_t, :pth_policy, :int32_t, :pth_run_state, :int32_t, :pth_flags, :int32_t, :pth_sleep_time, :int32_t, :pth_curpri, :int32_t, :pth_priority, :int32_t, :pth_maxpriority, :int32_t, :pth_name, [:char, MAXTHREADNAMESIZE] ) end private_constant :ProcThreadInfo # Map the fields from the FFI::Structs to the Sys::ProcTable struct on # class load to reduce the amount of objects needing to be generated for # each invocation of Sys::ProcTable.ps all_members = ProcBsdInfo.members + ProcTaskInfo.members + ProcThreadInfo.members PROC_STRUCT_FIELD_MAP = all_members.map do |member| temp = member.to_s.split('_') sproperty = temp.size > 1 ? temp[1..-1].join('_') : temp.first [member, sproperty.to_sym] end.to_h class ProcTaskAllInfo < FFI::Struct layout(:pbsd, ProcBsdInfo, :ptinfo, ProcTaskInfo) end private_constant :ProcTaskAllInfo ffi_lib 'proc' attach_function :proc_listallpids, %i[pointer int], :int attach_function :proc_pidinfo, %i[int int uint64_t pointer int], :int ffi_lib FFI::Library::LIBC attach_function :sysctl, %i[pointer uint pointer pointer pointer size_t], :int private_class_method :proc_listallpids private_class_method :proc_pidinfo private_class_method :sysctl # These mostly mimic the struct members, but we've added a few custom ones as well. @fields = %w[ flags status xstatus pid ppid uid gid ruid rgid svuid svgid rfu1 comm name nfiles pgid pjobc tdev tpgid nice start_tvsec start_tvusec virtual_size resident_size total_user total_system threads_user threads_system policy faults pageins cow_faults messages_sent messages_received syscalls_mach syscalls_unix csw threadnum numrunning priority cmdline exe environ threadinfo ] # Add a couple aliases to make it similar to Linux ProcTableStruct = Struct.new("ProcTableStruct", *@fields) do alias_method :vsize, :virtual_size alias_method :rss, :resident_size end private_constant :ProcTableStruct ThreadInfoStruct = Struct.new("ThreadInfo", :user_time, :system_time, :cpu_usage, :policy, :run_state, :flags, :sleep_time, :curpri, :priority, :maxpriority, :name ) private_constant :ThreadInfoStruct # Returns an array of fields that each ProcTableStruct will contain. This # may be useful if you want to know in advance what fields are available # without having to perform at least one read of the process table. # # Example: # # Sys::ProcTable.fields.each{ |field| # puts "Field: #{field}" # } # def self.fields @fields end # In block form, yields a ProcTableStruct for each process entry that you # have rights to. This method returns an array of ProcTableStruct's in # non-block form. # # If a +pid+ is provided, then only a single ProcTableStruct is yielded or # returned, or nil if no process information is found for that +pid+. # # Example: # # # Iterate over all processes # ProcTable.ps do |proc_info| # p proc_info # end # # # Print process table information for only pid 1001 # p ProcTable.ps(pid: 1001) # # # Same as above, but do not include thread information # p ProcTable.ps(pid: 1001, thread_info: false) # def self.ps(**kwargs) pid = kwargs[:pid] thread_info = kwargs[:thread_info] if pid raise TypeError unless pid.is_a?(Numeric) info = ProcTaskAllInfo.new nb = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, info, info.size) if nb <= 0 if [Errno::EPERM::Errno, Errno::ESRCH::Errno].include?(FFI.errno) return # Either we don't have permission, or the pid no longer exists else raise SystemCallError.new('proc_pidinfo', FFI.errno) end end return nil if nb != info.size # Invalid data struct = ProcTableStruct.new # Pass by reference get_cmd_args_and_env(pid, struct) get_thread_info(pid, struct, info[:ptinfo]) unless thread_info == false apply_info_to_struct(info, struct) struct.freeze yield struct if block_given? struct else num = proc_listallpids(nil, 0) ptr = FFI::MemoryPointer.new(:pid_t, num) num = proc_listallpids(ptr, ptr.size) raise SystemCallError.new('proc_listallpids', FFI.errno) if num == 0 pids = ptr.get_array_of_int32(0, num).sort array = block_given? ? nil : [] pids.each do |lpid| next if pid && pid != lpid info = ProcTaskAllInfo.new nb = proc_pidinfo(lpid, PROC_PIDTASKALLINFO, 0, info, info.size) if nb <= 0 if [Errno::EPERM::Errno, Errno::ESRCH::Errno].include?(FFI.errno) next # Either we don't have permission, or the pid no longer exists else raise SystemCallError.new('proc_pidinfo', FFI.errno) end end # Avoid potentially invalid data next if nb != info.size struct = ProcTableStruct.new # Pass by reference get_cmd_args_and_env(lpid, struct) get_thread_info(lpid, struct, info[:ptinfo]) unless thread_info == false apply_info_to_struct(info, struct) struct.freeze if block_given? yield struct else array << struct end end array end end # Pass by reference method that updates the Ruby struct based on the FFI struct. # def self.apply_info_to_struct(info, struct) # Chop the leading xx_ from the FFI struct members for our ruby struct. info.members.each do |nested| info[nested].members.each do |member| if info[nested][member].is_a?(FFI::StructLayout::CharArray) struct[PROC_STRUCT_FIELD_MAP[member]] = info[nested][member].to_s else struct[PROC_STRUCT_FIELD_MAP[member]] = info[nested][member] end end end end private_class_method :apply_info_to_struct # Returns an array of ThreadInfo objects for the given pid. # def self.get_thread_info(pid, struct, ptinfo) buf = FFI::MemoryPointer.new(:uint64_t, ptinfo[:pti_threadnum]) num = proc_pidinfo(pid, PROC_PIDLISTTHREADS, 0, buf, buf.size) if num <= 0 if [Errno::EPERM::Errno, Errno::ESRCH::Errno].include?(FFI.errno) return # Either we don't have permission, or the pid no longer exists else raise SystemCallError.new('proc_pidinfo', FFI.errno) end end max = ptinfo[:pti_threadnum] struct[:threadinfo] = [] 0.upto(max - 1) do |index| tinfo = ProcThreadInfo.new # Use read_array_of_uint64 for compatibility with JRuby if necessary. if buf[index].respond_to?(:read_uint64) nb = proc_pidinfo(pid, PROC_PIDTHREADINFO, buf[index].read_uint64, tinfo, tinfo.size) else nb = proc_pidinfo(pid, PROC_PIDTHREADINFO, buf[index].read_array_of_uint64(1).first, tinfo, tinfo.size) end if nb <= 0 if [Errno::EPERM::Errno, Errno::ESRCH::Errno].include?(FFI.errno) next # Either we don't have permission, or the pid no longer exists else raise SystemCallError.new('proc_pidinfo', FFI.errno) end end tinfo_struct = ThreadInfoStruct.new( tinfo[:pth_user_time], tinfo[:pth_system_time], tinfo[:pth_cpu_usage], tinfo[:pth_policy], tinfo[:pth_run_state], tinfo[:pth_flags], tinfo[:pth_sleep_time], tinfo[:pth_curpri], tinfo[:pth_priority], tinfo[:pth_maxpriority], tinfo[:pth_name].to_s ) struct[:threadinfo] << tinfo_struct end end private_class_method :get_thread_info # Get the command line arguments, as well as the environment settings, # for the given PID. #-- # Note that on Big Sur and later it seems that you cannot get environment # variable information on spawned processes except in certain circumstances, # e.g. SIP has been disabled, the kernel is in debug mode, etc. # def self.get_cmd_args_and_env(pid, struct) len = FFI::MemoryPointer.new(:size_t) mib = FFI::MemoryPointer.new(:int, 3) # Since we may not have access to the process information due # to improper privileges, just bail if we see a failure here. # First use KERN_PROCARGS2 to discover the argc value of the running process. mib.write_array_of_int([CTL_KERN, KERN_PROCARGS2, pid]) return if sysctl(mib, 3, nil, len, nil, 0) < 0 buf = FFI::MemoryPointer.new(:char, len.read_ulong) return if sysctl(mib, 3, buf, len, nil, 0) < 0 # The argc value is located in the first byte of buf argc = buf.read_bytes(1).ord buf.free # Now use KERN_PROCARGS to fetch the rest of the process information mib.write_array_of_int([CTL_KERN, KERN_PROCARGS, pid]) return if sysctl(mib, 3, nil, len, nil, 0) < 0 buf = FFI::MemoryPointer.new(:char, len.read_ulong) return if sysctl(mib, 3, buf, len, nil, 0) < 0 exe = buf.read_string # Read up to first null, does not include args struct[:exe] = exe # Parse the rest of the information out of a big, ugly string array = buf.read_bytes(len.read_ulong).split(0.chr) array.delete('') # Delete empty strings # The format that sysctl outputs is as follows: # # [full executable path] # [executable name] # [arguments] # [environment variables] # ... # \FF\BF # [full executable path] # # Strip the first executable path and the last two entries from the array. # What is left is the name, arguments, and environment variables array = array[1..-3] # It seems that argc sometimes returns a bogus value. In that case, delete # any environment variable strings, and reset the argc value. # if argc > array.size array.delete_if{ |e| e.include?('=') } argc = array.size end cmdline = '' # Extract the full command line and its arguments from the array argc.times do cmdline << ' ' << array.shift end struct[:cmdline] = cmdline.strip # Anything remaining at this point is a collection of key=value # pairs which we convert into a hash. environ = array.each_with_object({}) do |string, hash| if string && string.include?('=') key, value = string.split('=') hash[key] = value end end struct[:environ] = environ end private_class_method :get_cmd_args_and_env end end <file_sep>######################################################################## # proctable.rb # # A pure Ruby version of sys-proctable for SunOS 5.8 or later. ######################################################################## require 'ffi' require 'sys/proctable/version' # The Sys module serves as a namespace only. module Sys # The ProcTable class encapsulates process table information. class ProcTable extend FFI::Library class Error < StandardError; end # There is no constructor private_class_method :new private class Timeval < FFI::Struct layout(:tv_sec, :time_t, :tv_usec, :time_t) end class LWPSInfo < FFI::Struct layout( :pr_flag, :int, :pr_lwpid, :id_t, :pr_addr, :uintptr_t, :pr_wchan, :uintptr_t, :pr_stype, :char, :pr_state, :char, :pr_sname, :char, :pr_nice, :char, :pr_syscall, :short, :pr_oldpri, :char, :pr_cpu, :char, :pr_pri, :int, :pr_pctcpu, :ushort_t, :pr_pad, :ushort_t, :pr_start, Timeval, :pr_time, Timeval, :pr_clname, [:char, 8], :pr_name, [:char, 16], :pr_onpro, :int, :pr_bindpro, :int, :pr_bindpset, :int, :pr_filler, [:int, 5] ) end class PSInfo < FFI::Struct layout( :pr_flag, :int, :pr_nlwp, :int, :pr_pid, :pid_t, :pr_ppid, :pid_t, :pr_pgid, :pid_t, :pr_sid, :pid_t, :pr_uid, :uid_t, :pr_euid, :uid_t, :pr_gid, :gid_t, :pr_egid, :gid_t, :pr_addr, :uintptr_t, :pr_size, :size_t, :pr_rssize, :size_t, :pr_pad1, :size_t, :pr_ttydev, :dev_t, :pr_pctcpu, :ushort_t, :pr_pctmem, :ushort_t, :pr_start, Timeval, :pr_time, Timeval, :pr_ctime, Timeval, :pr_fname, [:char, 16], :pr_psargs, [:char, 80], :pr_wstat, :int, :pr_argc, :int, :pr_argv, :uintptr_t, :pr_envp, :uintptr_t, :pr_dmodel, :char, :pr_pad2, [:char, 3], :pr_taskid, :taskid_t, :pr_projid, :projid_t, :pr_nzomb, :int, :pr_poolid, :poolid_t, :pr_zoneid, :zoneid_t, :pr_contract, :id_t, :pr_filler, [:int, 1], :pr_lwp, LWPSInfo ) end class PRUsage < FFI::Struct layout( :pr_lwpid, :id_t, :pr_count, :int, :pr_tstamp, Timeval, :pr_create, Timeval, :pr_term, Timeval, :pr_rtime, Timeval, :pr_utime, Timeval, :pr_stime, Timeval, :pr_ttime, Timeval, :pr_tftime, Timeval, :pr_dftime, Timeval, :pr_kftime, Timeval, :pr_ltime, Timeval, :pr_slptime, Timeval, :pr_wtime, Timeval, :pr_stoptime, Timeval, :pr_filetime, [Timeval, 6], :pr_minf, :ulong_t, :pr_majf, :ulong_t, :pr_nswap, :ulong_t, :pr_inblk, :ulong_t, :pr_oublk, :ulong_t, :pr_msnd, :ulong_t, :pr_mrcv, :ulong_t, :pr_sigs, :ulong_t, :pr_vctx, :ulong_t, :pr_ictx, :ulong_t, :pr_sysc, :ulong_t, :pr_ioch, :ulong_t, :filler, [:ulong_t, 10] ) end PRNODEV = (1<<FFI::Platform::ADDRESS_SIZE)-1 @fields = [ :flag, # process flags (deprecated) :nlwp, # number of active lwp's in the process :pid, # unique process id :ppid, # process id of parent :pgid, # pid of session leader :sid, # session id :uid, # real user id :euid, # effective user id :gid, # real group id :egid, # effective group id :addr, # address of the process :size, # size of process in kbytes :rssize, # resident set size in kbytes :ttydev, # tty device (or PRNODEV) :pctcpu, # % of recent cpu used by all lwp's :pctmem, # % of system memory used by process :start, # absolute process start time :time, # usr + sys cpu time for this process :ctime, # usr + sys cpu time for reaped children :fname, # name of the exec'd file :psargs, # initial characters argument list - same as cmdline :wstat, # if a zombie, the wait status :argc, # initial argument count :argv, # address of initial argument vector :envp, # address of initial environment vector :dmodel, # data model of the process :taskid, # task id :projid, # project id :nzomb, # number of zombie lwp's in the process :poolid, # pool id :zoneid, # zone id :contract, # process contract :lwpid, # lwp id :wchan, # wait address for sleeping lwp :stype, # synchronization event type :state, # numeric lwp state :sname, # printable character for state :nice, # nice for cpu usage :syscall, # system call number (if in syscall) :pri, # priority :clname, # scheduling class name :name, # name of system lwp :onpro, # processor which last ran thsi lwp :bindpro, # processor to which lwp is bound :bindpset, # processor set to which lwp is bound :count, # number of contributing lwp's :tstamp, # current time stamp :create, # process/lwp creation time stamp :term, # process/lwp termination time stamp :rtime, # total lwp real (elapsed) time :utime, # user level cpu time :stime, # system call cpu time :ttime, # other system trap cpu time :tftime, # text page fault sleep time :dftime, # text page fault sleep time :kftime, # kernel page fault sleep time :ltime, # user lock wait sleep time :slptime, # all other sleep time :wtime, # wait-cpu (latency) time :stoptime, # stopped time :minf, # minor page faults :majf, # major page faults :nswap, # swaps :inblk, # input blocks :oublk, # output blocks :msnd, # messages sent :mrcv, # messages received :sigs, # signals received :vctx, # voluntary context switches :ictx, # involuntary context switches :sysc, # system calls :ioch, # chars read and written :path, # array of symbolic link paths from /proc/<pid>/path :contracts, # array symbolic link paths from /proc/<pid>/contracts :fd, # array of used file descriptors :cmd_args, # array of command line arguments :environ, # hash of environment associated with the process, :cmdline # joined cmd_args if present, otherwise psargs ] public ProcTableStruct = Struct.new("ProcTableStruct", *@fields) do alias comm fname end # In block form, yields a ProcTableStruct for each process entry that you # have rights to. This method returns an array of ProcTableStruct's in # non-block form. # # If a +pid+ is provided, then only a single ProcTableStruct is yielded or # returned, or nil if no process information is found for that +pid+. # # Example: # # # Iterate over all processes # ProcTable.ps do |proc_info| # p proc_info # end # # # Print process table information for only pid 1001 # p ProcTable.ps(pid: 1001) # # # Skip prusage information # p ProcTable.ps(prusage: false) # def self.ps(**kwargs) pid = kwargs[:pid] prusage_info = kwargs[:prusage] raise TypeError unless pid.is_a?(Numeric) if pid array = block_given? ? nil : [] struct = nil Dir.foreach("/proc") do |file| next if file =~ /\D/ # Skip non-numeric entries under /proc # Only return information for a given pid, if provided next unless file.to_i == pid if pid # Skip over any entries we don't have permissions to read next unless File.readable?("/proc/#{file}/psinfo") data = IO.read("/proc/#{file}/psinfo") rescue next psinfo = PSInfo.new(FFI::MemoryPointer.from_string(data)) struct = ProcTableStruct.new struct.flag = psinfo[:pr_flag] struct.nlwp = psinfo[:pr_nlwp] struct.pid = psinfo[:pr_pid] struct.ppid = psinfo[:pr_ppid] struct.pgid = psinfo[:pr_pgid] struct.sid = psinfo[:pr_sid] struct.uid = psinfo[:pr_uid] struct.euid = psinfo[:pr_euid] struct.gid = psinfo[:pr_gid] struct.egid = psinfo[:pr_egid] struct.addr = psinfo[:pr_addr] struct.size = psinfo[:pr_size] * 1024 # bytes struct.rssize = psinfo[:pr_rssize] * 1024 # bytes struct.ttydev = psinfo[:pr_ttydev] == PRNODEV ? -1 : psinfo[:pr_ttydev] struct.pctcpu = (psinfo[:pr_pctcpu] * 100).to_f / 0x8000 struct.pctmem = (psinfo[:pr_pctmem] * 100).to_f / 0x8000 struct.start = Time.at(psinfo[:pr_start][:tv_sec]) struct.time = psinfo[:pr_time][:tv_sec] struct.ctime = psinfo[:pr_ctime][:tv_sec] struct.fname = psinfo[:pr_fname].to_s struct.psargs = psinfo[:pr_psargs].to_s struct.wstat = psinfo[:pr_wstat] struct.argc = psinfo[:pr_argc] struct.argv = psinfo[:pr_argv] struct.envp = psinfo[:pr_envp] struct.dmodel = psinfo[:pr_dmodel] struct.taskid = psinfo[:pr_taskid] struct.projid = psinfo[:pr_projid] struct.nzomb = psinfo[:pr_nzomb] struct.poolid = psinfo[:pr_poolid] struct.zoneid = psinfo[:pr_zoneid] struct.contract = psinfo[:pr_contract] ### LWPSINFO struct info struct.lwpid = psinfo[:pr_lwp][:pr_lwpid] struct.wchan = psinfo[:pr_lwp][:pr_wchan] struct.stype = psinfo[:pr_lwp][:pr_stype] struct.state = psinfo[:pr_lwp][:pr_state] struct.sname = psinfo[:pr_lwp][:pr_sname].chr struct.nice = psinfo[:pr_lwp][:pr_nice] struct.syscall = psinfo[:pr_lwp][:pr_syscall] struct.pri = psinfo[:pr_lwp][:pr_pri] struct.clname = psinfo[:pr_lwp][:pr_clname].to_s struct.name = psinfo[:pr_lwp][:pr_name].to_s struct.onpro = psinfo[:pr_lwp][:pr_onpro] struct.bindpro = psinfo[:pr_lwp][:pr_bindpro] struct.bindpset = psinfo[:pr_lwp][:pr_bindpset] # Get the full command line out of /proc/<pid>/as. begin File.open("/proc/#{file}/as") do |fd| fd.sysseek(struct.argv, IO::SEEK_SET) address = fd.sysread(struct.argc * 4).unpack("L")[0] struct.cmd_args = [] 0.upto(struct.argc - 1){ |i| fd.sysseek(address, IO::SEEK_SET) data = fd.sysread(128)[/^[^\0]*/] # Null strip struct.cmd_args << data address += data.length + 1 # Add 1 for the space } # Get the environment hash associated with the process. struct.environ = {} fd.sysseek(struct.envp, IO::SEEK_SET) env_address = fd.sysread(128).unpack("L")[0] # TODO: Optimization potential here. loop do fd.sysseek(env_address, IO::SEEK_SET) data = fd.sysread(1024)[/^[^\0]*/] # Null strip break if data.empty? key, value = data.split('=') struct.environ[key] = value env_address += data.length + 1 # Add 1 for the space end end rescue Errno::EACCES, Errno::EBADF, Errno::EOVERFLOW, EOFError, RangeError # Skip this if we don't have proper permissions, if there's # no associated environment, or if there's a largefile issue. rescue Errno::ENOENT next # The process has terminated. Bail out! end ### struct prusage if prusage_info != false begin data = IO.read("/proc/#{file}/usage") prusage = PRUsage.new(FFI::MemoryPointer.from_string(data)) struct.count = prusage[:pr_count] struct.tstamp = prusage[:pr_tstamp][:tv_sec] struct.create = prusage[:pr_create][:tv_sec] struct.term = prusage[:pr_term][:tv_sec] struct.rtime = prusage[:pr_rtime][:tv_sec] struct.utime = prusage[:pr_utime][:tv_sec] struct.stime = prusage[:pr_stime][:tv_sec] struct.ttime = prusage[:pr_ttime][:tv_sec] struct.tftime = prusage[:pr_tftime][:tv_sec] struct.dftime = prusage[:pr_dftime][:tv_sec] struct.kftime = prusage[:pr_kftime][:tv_sec] struct.ltime = prusage[:pr_ltime][:tv_sec] struct.slptime = prusage[:pr_slptime][:tv_sec] struct.wtime = prusage[:pr_wtime][:tv_sec] struct.stoptime = prusage[:pr_stoptime][:tv_sec] struct.minf = prusage[:pr_minf] struct.majf = prusage[:pr_majf] struct.nswap = prusage[:pr_nswap] struct.inblk = prusage[:pr_inblk] struct.oublk = prusage[:pr_oublk] struct.msnd = prusage[:pr_msnd] struct.mrcv = prusage[:pr_mrcv] struct.sigs = prusage[:pr_sigs] struct.vctx = prusage[:pr_vctx] struct.ictx = prusage[:pr_ictx] struct.sysc = prusage[:pr_sysc] struct.ioch = prusage[:pr_ioch] rescue Errno::EACCES # Do nothing if we lack permissions. Just move on. rescue Errno::ENOENT next # The process has terminated. Bail out! end end # Information from /proc/<pid>/path. This is represented as a hash, # with the symbolic link name as the key, and the file it links to # as the value, or nil if it cannot be found. #-- # Note that cwd information can be gathered from here, too. struct.path = {} Dir["/proc/#{file}/path/*"].each{ |entry| link = File.readlink(entry) rescue nil struct.path[File.basename(entry)] = link } # Information from /proc/<pid>/contracts. This is represented as # a hash, with the symbolic link name as the key, and the file # it links to as the value. struct.contracts = {} Dir["/proc/#{file}/contracts/*"].each{ |entry| link = File.readlink(entry) rescue nil struct.contracts[File.basename(entry)] = link } # Information from /proc/<pid>/fd. This returns an array of # numeric file descriptors used by the process. struct.fd = Dir["/proc/#{file}/fd/*"].map{ |f| File.basename(f).to_i } # Use the cmd_args as the cmdline if available. Otherwise use # the psargs. This struct member is provided to provide a measure # of consistency with the other platform implementations. if struct.cmd_args && struct.cmd_args.length > 0 struct.cmdline = struct.cmd_args.join(' ') else struct.cmdline = struct.psargs end # This is read-only data struct.freeze if block_given? yield struct else array << struct end end pid ? struct : array end # Returns an array of fields that each ProcTableStruct will contain. This # may be useful if you want to know in advance what fields are available # without having to perform at least one read of the /proc table. # # Example: # # Sys::ProcTable.fields.each{ |field| # puts "Field: #{field}" # } # def self.fields @fields.map(&:to_s) end end end <file_sep>* CHANGES * LICENSE * MANIFEST * Rakefile * README * sys-proctable.gemspec * benchmarks/bench_ps.rb * benchmarks/bench_ips_ps.rb * example/example_ps.rb * lib/sys-proctable.rb * lib/sys-top.rb * lib/sys/proctable.rb * lib/sys/top.rb * lib/sys/proctable/version.rb * lib/aix/sys/proctable.rb * lib/darwin/sys/proctable.rb * lib/bsd/sys/dragonfly/sys/proctable.rb * lib/bsd/sys/dragonfly/sys/proctable/constants.rb * lib/bsd/sys/dragonfly/sys/proctable/functions.rb * lib/bsd/sys/dragonfly/sys/proctable/structs.rb * lib/bsd/sys/freebsd/sys/proctable.rb * lib/bsd/sys/freebsd/sys/proctable/constants.rb * lib/bsd/sys/freebsd/sys/proctable/functions.rb * lib/bsd/sys/freebsd/sys/proctable/structs.rb * lib/linux/sys/proctable.rb * lib/sunos/sys/proctable.rb * lib/windows/sys/proctable.rb * spec/spec_helper.rb * spec/sys_proctable_aix_spec.rb * spec/sys_proctable_all_spec.rb * spec/sys_proctable_darwin_spec.rb * spec/sys_proctable_freebsd_spec.rb * spec/sys_proctable_linux_spec.rb * spec/sys_proctable_sunos_spec.rb * spec/sys_proctable_windows_spec.rb * spec/sys_top_spec.rb <file_sep># frozen_string_literal: true require 'win32ole' require 'socket' require 'date' require 'sys/proctable/version' # The Sys module serves as a namespace only module Sys # The ProcTable class encapsulates process table information class ProcTable # There is no constructor private_class_method :new # Error typically raised if one of the Sys::ProcTable methods fails class Error < StandardError; end # The comm field corresponds to the 'name' field. The 'cmdline' field # is the CommandLine attribute on Windows XP or later, or the # 'executable_path' field on Windows 2000 or earlier. # @fields = %w[ caption cmdline comm creation_class_name creation_date cs_creation_class_name cs_name description executable_path execution_state handle handle_count install_date kernel_mode_time maximum_working_set_size minimum_working_set_size name os_creation_class_name os_name other_operation_count other_transfer_count page_faults page_file_usage ppid peak_page_file_usage peak_virtual_size peak_working_set_size priority private_page_count pid quota_non_paged_pool_usage quota_paged_pool_usage quota_peak_non_paged_pool_usage quota_peak_paged_pool_usage read_operation_count read_transfer_count session_id status termination_date thread_count user_mode_time virtual_size windows_version working_set_size write_operation_count write_transfer_count ] ProcTableStruct = Struct.new("ProcTableStruct", *@fields) # call-seq: # ProcTable.fields # # Returns an array of fields that each ProcTableStruct will contain. This # may be useful if you want to know in advance what fields are available # without having to perform at least one read of the /proc table. # class << self attr_reader :fields end # call-seq: # ProcTable.ps(pid=nil) # ProcTable.ps(pid=nil){ |ps| ... } # # In block form, yields a ProcTableStruct for each process entry that you # have rights to. This method returns an array of ProcTableStruct's in # non-block form. # # If a +pid+ is provided, then only a single ProcTableStruct is yielded or # returned, or nil if no process information is found for that +pid+. # def self.ps(**kwargs) pid = kwargs[:pid] host = kwargs[:host] || Socket.gethostname if pid && !pid.is_a?(Numeric) raise TypeError end array = block_given? ? nil : [] struct = nil begin wmi = WIN32OLE.connect("winmgmts://#{host}/root/cimv2") rescue WIN32OLERuntimeError => err raise Error, err # Re-raise as ProcTable::Error else wmi.InstancesOf("Win32_Process").each do |wproc| if pid && wproc.ProcessId != pid next end # Some fields are added later, and so are nil initially struct = ProcTableStruct.new( wproc.Caption, nil, # Added later, based on OS version wproc.Name, wproc.CreationClassName, parse_ms_date(wproc.CreationDate), wproc.CSCreationClassName, wproc.CSName, wproc.Description, wproc.ExecutablePath, wproc.ExecutionState, wproc.Handle, wproc.HandleCount, parse_ms_date(wproc.InstallDate), convert(wproc.KernelModeTime), wproc.MaximumWorkingSetSize, wproc.MinimumWorkingSetSize, wproc.Name, wproc.OSCreationClassName, wproc.OSName, convert(wproc.OtherOperationCount), convert(wproc.OtherTransferCount), wproc.PageFaults, wproc.PageFileUsage, wproc.ParentProcessId, convert(wproc.PeakPageFileUsage), convert(wproc.PeakVirtualSize), convert(wproc.PeakWorkingSetSize), wproc.Priority, convert(wproc.PrivatePageCount), wproc.ProcessId, wproc.QuotaNonPagedPoolUsage, wproc.QuotaPagedPoolUsage, wproc.QuotaPeakNonPagedPoolUsage, wproc.QuotaPeakPagedPoolUsage, convert(wproc.ReadOperationCount), convert(wproc.ReadTransferCount), wproc.SessionId, wproc.Status, parse_ms_date(wproc.TerminationDate), wproc.ThreadCount, convert(wproc.UserModeTime), convert(wproc.VirtualSize), wproc.WindowsVersion, convert(wproc.WorkingSetSize), convert(wproc.WriteOperationCount), convert(wproc.WriteTransferCount) ) ############################################################### # On Windows XP or later, set the cmdline to the CommandLine # attribute. Otherwise, set it to the ExecutablePath # attribute. ############################################################### if wproc.WindowsVersion.to_f < 5.1 struct.cmdline = wproc.ExecutablePath else struct.cmdline = wproc.CommandLine end struct.freeze # This is read-only data if block_given? yield struct else array << struct end end end pid ? struct : array end ####################################################################### # Converts a string in the format '20040703074625.015625-360' into a # Ruby Time object. ####################################################################### def self.parse_ms_date(str) return if str.nil? DateTime.parse(str) end private_class_method :parse_ms_date ##################################################################### # There is a bug in win32ole where uint64 types are returned as a # String instead of a Fixnum. This method deals with that for now. ##################################################################### def self.convert(str) return nil if str.nil? # Return nil, not 0 str.to_i end private_class_method :convert end end <file_sep>####################################################################### # sys_proctable_all_spec.rb # # Test suite for methods common to all platforms. Generally speaking # you should run these specs using the 'rake spec' task. ####################################################################### require 'spec_helper' RSpec.describe 'common' do let(:windows) { File::ALT_SEPARATOR } before(:all) do @pid = Process.pid end context 'constants' do it 'has a VERSION constant set to the expected value' do expect(Sys::ProcTable::VERSION).to eql('1.3.0') expect(Sys::ProcTable::VERSION).to be_frozen end it 'defines a custom error class' do expect{ Sys::ProcTable::Error }.not_to raise_error expect(Sys::ProcTable::Error.new).to be_kind_of(StandardError) end end context 'fields' do it 'has a fields singleton method' do expect(Sys::ProcTable).to respond_to(:fields) end it 'returns the expected data type for the fields singleton method' do expect(Sys::ProcTable.fields).to be_kind_of(Array) expect(Sys::ProcTable.fields.first).to be_kind_of(String) end end context 'ps' do it 'defines a ps singleton method' do expect(Sys::ProcTable).to respond_to(:ps) end it 'allows a pid option as an argument' do expect{ Sys::ProcTable.ps(:pid => 0) }.not_to raise_error end it 'allows the pid to be nil' do expect{ Sys::ProcTable.ps(:pid => nil) }.not_to raise_error expect(Sys::ProcTable.ps(:pid => nil)).to be_kind_of(Array) end it 'returns expected results with no arguments' do expect(Sys::ProcTable.ps).to be_kind_of(Array) end it 'returns expected results with a pid argument' do expect(Sys::ProcTable.ps(:pid => @pid)).to be_kind_of(Struct::ProcTableStruct) end it 'returns nil if the process does not exist' do expect(Sys::ProcTable.ps(:pid => 999999999)).to be_nil end it 'returns nil in block form whether or not a pid was provided' do expect(Sys::ProcTable.ps{}).to be_nil expect(Sys::ProcTable.ps(:pid => 999999999){}).to be_nil end it 'returns frozen structs' do expect(Sys::ProcTable.ps.first.frozen?).to be(true) end it 'expects a numeric pid argument if present' do expect{ Sys::ProcTable.ps(:pid => 'vim') }.to raise_error(TypeError) end it 'accepts keyword arguments only' do expect{ Sys::ProcTable.ps(0, 'localhost') }.to raise_error(ArgumentError) end it 'disables the traditional constructor' do expect{ Sys::ProcTable.new }.to raise_error(NoMethodError) end it 'works within a thread' do expect{ Thread.new{ Sys::ProcTable.ps }.value }.not_to raise_error end end end <file_sep>####################################################################### # sys_proctable_aix_spec.rb # # Test suite for the AIX version of the sys-proctable library. You # should run these tests via the 'rake spec' task. ####################################################################### require 'spec_helper' RSpec.describe Sys::ProcTable, :aix do let(:fields){ %w[ addr argc argv bindpro cid clname cmd_args cmdline cwd egid environ envp euid fd flag flag2 fname gid lwpid map nice nlwp onpro pgid pid policy ppid pri psargs ptid rssize sid size sname start state time ttydev uid wchan wtype s_ttydev ] } let(:map_fields){ %w[size vaddr mapname off mflags pathoff alias gp s_mflags path] } before(:all) do File.open('aix-child.rb', 'w') do |out| out.puts 'trap("HUP") { exit }' out.puts 'trap("TERM") { exit }' out.puts 'sleep(60)' end @myenv = ENV.to_hash @p1args = %w[aix-child.rb testing how well this works 1] @p2args = %w[aix-child.rb testing how well this works 2] @pid1 = fork do exec('ruby', *@p1args) end @pid2 = fork do exec('ruby', *@p2args) end sleep(2) # wait to make sure the above execs have completed in children @p1info = ProcTable.ps(@pid1) @p2info = ProcTable.ps.select { |e| e.pid == @pid2 } if @p2info.size == 1 @p2info = @p2info[0] else $stderr.puts "expected a single process, have #{@p2info.size}" exit 1 end end after(:all) do Process.kill('TERM', @pid1) Process.kill('TERM', @pid2) File.unlink('aix-child.rb') rescue nil end context 'fields singleton method' do it 'responds to a fields method' do expect(described_class).to respond_to(:fields) end it 'returns the expected results for the fields method' do expect(described_class.fields).to be_kind_of(Array) expect(described_class.fields).to eql(fields) end end context 'ProcTable::Struct members' do it 'contains a flag member and returns the expected value' do expect(@p1info).to respond_to(:flag) expect(@p1info.flag).to be_kind_of(Integer) end it 'contains a flag2 member and returns the expected value' do expect(@p1info).to respond_to(:flag2) expect(@p1info.flag2).to be_kind_of(Integer) end it 'contains a nlwp member and returns the expected value' do expect(@p1info).to respond_to(:nlwp) expect(@p1info.nlwp).to be_kind_of(Integer) end it 'contains a uid member and returns the expected value' do expect(@p1info).to respond_to(:uid) expect(@p1info.uid).to be_kind_of(Integer) expect(@p1info.uid).to eql(Process.uid) end it 'contains a euid member and returns the expected value' do expect(@p1info).to respond_to(:euid) expect(@p1info.euid).to be_kind_of(Integer) expect(@p1info.euid).to eql(Process.euid) end it 'contains a gid member and returns the expected value' do expect(@p1info).to respond_to(:gid) expect(@p1info.gid).to be_kind_of(Integer) expect(@p1info.gid).to eql(Process.gid) end it 'contains a egid member and returns the expected value' do expect(@p1info).to respond_to(:egid) expect(@p1info.egid).to be_kind_of(Integer) expect(@p1info.egid).to eql(Process.egid) end it 'contains a pid member and returns the expected value' do expect(@p1info).to respond_to(:pid) expect(@p1info.pid).to be_kind_of(Integer) expect(@p1info.pid).to eql(@pid1) end it 'contains a ppid member and returns the expected value' do expect(@p1info).to respond_to(:ppid) expect(@p1info.ppid).to be_kind_of(Integer) expect(@p1info.ppid).to eql(Process.pid) end it 'contains a pgid member and returns the expected value' do expect(@p1info).to respond_to(:pgid) expect(@p1info.pgid).to be_kind_of(Integer) expect(@p1info.pgid).to eql(Process.getpgrp) end it 'contains a sid member and returns the expected value' do expect(@p1info).to respond_to(:sid) expect(@p1info.sid).to be_kind_of(Integer) end it 'contains a ttydev member and returns the expected value' do expect(@p1info).to respond_to(:ttydev) expect(@p1info.ttydev).to be_kind_of(Integer) end it 'contains a addr member and returns the expected value' do expect(@p1info).to respond_to(:addr) expect(@p1info.addr).to be_kind_of(Integer) end it 'contains a size member and returns the expected value' do expect(@p1info).to respond_to(:size) expect(@p1info.size).to be_kind_of(Integer) end it 'contains a rssize member and returns the expected value' do expect(@p1info).to respond_to(:rssize) expect(@p1info.rssize).to be_kind_of(Integer) end it 'contains a start member and returns the expected value' do expect(@p1info).to respond_to(:start) expect(@p1info.start).to be_kind_of(Time) end it 'contains a time member and returns the expected value' do expect(@p1info).to respond_to(:time) expect(@p1info.time).to be_kind_of(Time) end it 'contains a cid member and returns the expected value' do expect(@p1info).to respond_to(:cid) expect(@p1info.cid).to be_kind_of(Integer) end it 'contains an argc member and returns the expected value' do expect(@p1info).to respond_to(:argc) expect(@p1info.argc).to be_kind_of(Integer) expect(@p1info.argc).to eql(@p1args.size + 1) end it 'contains an argv member and returns the expected value' do expect(@p1info).to respond_to(:argv) expect(@p1info.argv).to be_kind_of(Integer) end it 'contains an envp member and returns the expected value' do expect(@p1info).to respond_to(:envp) expect(@p1info.envp).to be_kind_of(Integer) end it 'contains an fname member and returns the expected value' do expect(@p1info).to respond_to(:fname) expect(@p1info.fname).to be_kind_of(String) end it 'contains an psargs member and returns the expected value' do expect(@p1info).to respond_to(:psargs) expect(@p1info.psargs).to be_kind_of(String) end it 'contains an lwpid member and returns the expected value' do expect(@p1info).to respond_to(:lwpid) expect(@p1info.lwpid).to be_kind_of(Integer) end it 'contains a wchan member and returns the expected value' do expect(@p1info).to respond_to(:wchan) expect(@p1info.wchan).to be_kind_of(Integer) end it 'contains a wtype member and returns the expected value' do expect(@p1info).to respond_to(:wtype) expect(@p1info.wchan).to be_kind_of(Integer) end it 'contains a state member and returns the expected value' do expect(@p1info).to respond_to(:state) expect(@p1info.state).to be_kind_of(Integer) end it 'contains an sname member and returns the expected value' do expect(@p1info).to respond_to(:sname) expect(@p1info.sname).to be_kind_of(String) end it 'contains a nice member and returns the expected value' do expect(@p1info).to respond_to(:nice) expect(@p1info.nice).to be_kind_of(Integer) end it 'contains a pri member and returns the expected value' do expect(@p1info).to respond_to(:pri) expect(@p1info.pri).to be_kind_of(Integer) end it 'contains a policy member and returns the expected value' do expect(@p1info).to respond_to(:policy) expect(@p1info.policy).to be_kind_of(Integer) end it 'contains a clname member and returns the expected value' do expect(@p1info).to respond_to(:clname) expect(@p1info.clname).to be_kind_of(String) end it 'contains an onpro member and returns the expected value' do expect(@p1info).to respond_to(:onpro) expect(@p1info.onpro).to be_kind_of(Integer) end it 'contains a bindpro member and returns the expected value' do expect(@p1info).to respond_to(:bindpro) expect(@p1info.bindpro).to be_kind_of(Integer) end it 'contains a ptid member and returns the expected value' do expect(@p1info).to respond_to(:ptid) expect(@p1info.ptid).to be_kind_of(Integer) end it 'contains a comm member and returns the expected value' do expect(@p1info).to respond_to(:comm) expect(@p1info.comm).to be_kind_of(String) end it 'contains a fd member and returns the expected value' do expect(@p1info).to respond_to(:fd) expect(@p1info.fd).to be_kind_of(Array) end it 'contains a cmd_args member and returns the expected value' do expect(@p1info).to respond_to(:cmd_args) expect(@p1info.cmd_args).to be_kind_of(Array) expect(@p1info.cmd_args).to_eql(['ruby', @p1args].flatten) expect(@p2info).to respond_to(:cmd_args) expect(@p2info.cmd_args).to be_kind_of(Array) expect(@p2info.cmd_args).to_eql(['ruby', @p2args].flatten) end it 'contains an environ member and returns the expected value' do expect(@p1info).to respond_to(:environ) expect(@p1info.environ).to be_kind_of(Hash) expect(@p1info.environ).to eql(@myenv) expect(@p2info).to respond_to(:environ) expect(@p2info.environ).to be_kind_of(Hash) expect(@p2info.environ).to eql(@myenv) end it 'contains a cmdline member and returns the expected value' do expect(@p1info).to respond_to(:cmdline) expect(@p1info.cmdline).to be_kind_of(String) end it 'contains a cwd member and returns the expected value' do expect(@p1info).to respond_to(:cwd) expect(@p1info.cwd).to be_kind_of(String) if @p1info.cwd end it 'contains a map member and returns the expected value' do expect(@p1info).to respond_to(:map) expect(@p1info.map).to be_kind_of(Array) if @p1info.map end end context 'Struct::ProcTableMapStruct' do it 'contains the expected members' do expect(@p1info.map).to be_kind_of(Array) expect(map_fields.sort).to eql(@p1info.map[0].members.sort) end it 'has members of the expected type' do expect(@p1info.map).to be_kind_of(Array) p1info_map = @p1info.map expect(p1info_map).to be_kind_of(Struct::ProcTableMapStruct) expect(p1info_map.size).to be_kind_of(Integer) expect(p1info_map.vaddr).to be_kind_of(Integer) expect(p1info_map.mapname).to be_kind_of(String) expect(p1info_map.off).to be_kind_of(Integer) expect(p1info_map.mflags).to be_kind_of(Integer) expect(p1info_map.s_mflags).to be_kind_of(String) expect(p1info_map.pathoff).to be_kind_of(Integer) expect(p1info_map.alias).to be_kind_of(Integer) expect(p1info_map.gp).to be_kind_of(Integer) expect(p1info_map.path).to be_kind_of(String) end end end <file_sep>require 'ffi' require_relative 'constants' module Sys module ProcTableStructs extend FFI::Library class Timeval < FFI::Struct layout(:tv_sec, :time_t, :tv_usec, :suseconds_t) end class RTPrio < FFI::Struct layout(:type, :ushort, :prio, :ushort) end class Rusage < FFI::Struct layout( :ru_utime, Timeval, :ru_stime, Timeval, :ru_maxrss, :long, :ru_ixrss, :long, :ru_idrss, :long, :ru_isrss, :long, :ru_minflt, :long, :ru_majflt, :long, :ru_nswap, :long, :ru_inblock, :long, :ru_oublock, :long, :ru_msgsnd, :long, :ru_msgrcv, :long, :ru_nsignals, :long, :ru_nvcsw, :long, :ru_nivcsw, :long ) def utime Time.at(self[:ru_utime][:tv_sec]) end def stime Time.at(self[:ru_stime][:tv_sec]) end def maxrss self[:ru_maxrss] end def ixrss self[:ru_ixrss] end def idrss self[:ru_idrss] end def isrss self[:ru_isrss] end def minflt self[:ru_minflt] end def majflt self[:ru_majflt] end def nswap self[:ru_nswap] end def inblock self[:ru_inblock] end def oublock self[:ru_oublock] end def msgsnd self[:ru_msgsnd] end def msgrcv self[:ru_msgrcv] end def nsignals self[:ru_nsignals] end def nvcsw self[:ru_nivcsw] end def nivcsw self[:ru_nivcsw] end end enum :lwpstat, [:LSRUN, 1, :LSSTOP, :LSSLEEP] enum :procstat, [:SIDL, 1, :SACTIVE, :SSTOP, :SZOMB, :SCORE] class Sigset < FFI::Struct layout(:__bits, [:uint, 4]) def bits self[:__bits].to_a end end class KInfoLWP < FFI::Struct include Sys::ProcTableConstants layout( :kl_pid, :pid_t, :kl_tid, :lwpid_t, :kl_flags, :int, :kl_stat, :lwpstat, :kl_lock, :int, :kl_tdflags, :int, :kl_mpcount, :int, :kl_prio, :int, :kl_tdprio, :int, :kl_rtprio, RTPrio, :kl_uticks, :uint64_t, :kl_sticks, :uint64_t, :kl_iticks, :uint64_t, :kl_cpticks, :uint64_t, :kl_pctcpu, :uint, :kl_slptime, :uint, :kl_origcpu, :int, :kl_estcpu, :int, :kl_cpuid, :int, :kl_ru, Rusage, :kl_siglist, Sigset, :kl_sigmask, Sigset, :kl_wchan, :uintptr_t, :kl_wmesg, [:char, WMESGLEN+1], :kl_comm, [:char, MAXCOMLEN+1] ) def pid self[:kl_pid] end def tid self[:kl_tid] end def flags self[:kl_flags] end def stat self[:kl_stat] end def lock self[:kl_lock] end def tdflags self[:kl_tdflags] end def prio self[:kl_prio] end def tdprio self[:kl_tdprio] end def rtprio self[:kl_rtprio] end def uticks self[:kl_uticks] end def sticks self[:kl_sticks] end def iticks self[:kl_iticks] end def cpticks self[:kl_cpticks] end def pctcpu self[:kl_pctcpu] end def slptime self[:kl_slptime] end def origcpu self[:kl_origcpu] end def estcpu self[:kl_estcpu] end def cpuid self[:kl_cpuid] end def ru self[:kl_ru] end def siglist self[:kl_siglist] end def sigmask self[:kl_sigmask] end def wchan self[:kl_wchan] end def wmesg self[:kl_wmesg].to_s end def comm self[:kl_comm].to_s end end class KInfoProc < FFI::Struct include Sys::ProcTableConstants def self.roundup(x, y) ((x + y-1) / y) * y end layout( :kp_paddr, :uintptr_t, :kp_flags, :int, :kp_stat, :procstat, :kp_lock, :int, :kp_acflag, :int, :kp_traceflag, :int, :kp_fd, :uintptr_t, :kp_siglist, Sigset, :kp_sigignore, Sigset, :kp_sigcatch, Sigset, :kp_sigflag, :int, :kp_start, Timeval, :kp_comm, [:char, MAXCOMLEN+1], :kp_uid, :uid_t, :kp_ngroups, :short, :kp_groups, [:gid_t, NGROUPS], :kp_ruid, :uid_t, :kp_svuid, :uid_t, :kp_rgid, :gid_t, :kp_svgid, :gid_t, :kp_pid, :pid_t, :kp_ppid, :pid_t, :kp_pgid, :pid_t, :kp_jobc, :int, :kp_sid, :pid_t, :kp_login, [:char, roundup(MAXLOGNAME, FFI::Type::LONG.size)], :kp_tdev, :dev_t, :kp_tpgid, :pid_t, :kp_tsid, :pid_t, :kp_exitstat, :ushort, :kp_nthreads, :int, :kp_nice, :int, :kp_swtime, :uint, :kp_vm_map_size, :size_t, :kp_vm_rssize, :segsz_t, :kp_vm_swrss, :segsz_t, :kp_vm_tsize, :segsz_t, :kp_vm_dsize, :segsz_t, :kp_vm_ssize, :segsz_t, :kp_vm_prssize, :uint, :kp_jailid, :int, :kp_ru, Rusage, :kp_cru, Rusage, :kp_auxflags, :int, :kp_lwp, KInfoLWP, :kp_ktaddr, :uintptr_t, :kp_spare, [:int, 2] ) end end end <file_sep>require 'rbconfig' case RbConfig::CONFIG['host_os'] when /aix/i require_relative '../aix/sys/proctable' when /darwin/i require_relative '../darwin/sys/proctable' when /freebsd|dragonfly/i require_relative '../bsd/sys/proctable' when /linux/i require_relative '../linux/sys/proctable' when /sunos|solaris/i require_relative '../sunos/sys/proctable' when /mswin|win32|dos|cygwin|mingw|windows/i require_relative '../windows/sys/proctable' else raise "Unsupported platform" end <file_sep>require_relative 'proctable/constants' require_relative 'proctable/structs' require_relative 'proctable/functions' require 'sys/proctable/version' module Sys class ProcTable include Sys::ProcTableConstants include Sys::ProcTableStructs extend Sys::ProcTableFunctions # Error typically raised if the ProcTable.ps method fails. class Error < StandardError; end # There is no constructor private_class_method :new @fields = %w[ paddr flags stat lock acflag traceflag fd siglist sigignore sigcatch sigflag start comm uid ngroups groups ruid svuid rgid svgid pid ppid pgid jobc sid login tdev tpgid tsid exitstat nthreads nice swtime vm_map_size vm_rssize vm_swrss vm_tsize vm_dsize vm_ssize vm_prssize jailid ru cru auxflags lwp ktaddr ] ProcTableStruct = Struct.new('ProcTableStruct', *@fields) do alias cmdline comm end # In block form, yields a ProcTableStruct for each process entry that you # have rights to. This method returns an array of ProcTableStruct's in # non-block form. # # If a +pid+ is provided, then only a single ProcTableStruct is yielded or # returned, or nil if no process information is found for that +pid+. # # Example: # # # Iterate over all processes # ProcTable.ps do |proc_info| # p proc_info # end # # # Print process table information for only pid 1001 # p ProcTable.ps(pid: 1001) # def self.ps(**kwargs) pid = kwargs[:pid] begin kd = kvm_open(nil, nil, nil, 0, nil) if kd.null? raise SystemCallError.new('kvm_open', FFI.errno) end ptr = FFI::MemoryPointer.new(:int) # count if pid procs = kvm_getprocs(kd, KERN_PROC_PID, pid, ptr) else procs = kvm_getprocs(kd, KERN_PROC_ALL, 0, ptr) end if procs.null? if pid && FFI.errno == Errno::ESRCH::Errno return nil else raise SystemCallError.new('kvm_getprocs', FFI.errno) end end count = ptr.read_int array = [] 0.upto(count-1){ |i| cmd = nil kinfo = KInfoProc.new(procs[i * KInfoProc.size]) args = kvm_getargv(kd, kinfo, 0) unless args.null? cmd = [] until ((ptr = args.read_pointer).null?) cmd << ptr.read_string args += FFI::Type::POINTER.size end cmd = cmd.join(' ') end struct = ProcTableStruct.new( kinfo[:kp_paddr], kinfo[:kp_flags], kinfo[:kp_stat], kinfo[:kp_lock], kinfo[:kp_acflag], kinfo[:kp_traceflag], kinfo[:kp_fd], kinfo[:kp_siglist].bits, kinfo[:kp_sigignore].bits, kinfo[:kp_sigcatch].bits, kinfo[:kp_sigflag], Time.at(kinfo[:kp_start][:tv_sec]), kinfo[:kp_comm].to_s, kinfo[:kp_uid], kinfo[:kp_ngroups], kinfo[:kp_groups].to_a[0..kinfo[:kp_ngroups]-1], kinfo[:kp_ruid], kinfo[:kp_svuid], kinfo[:kp_rgid], kinfo[:kp_svgid], kinfo[:kp_pid], kinfo[:kp_ppid], kinfo[:kp_pgid], kinfo[:kp_jobc], kinfo[:kp_sid], kinfo[:kp_login].to_s, kinfo[:kp_tdev], kinfo[:kp_tpgid], kinfo[:kp_tsid], kinfo[:kp_exitstat], kinfo[:kp_nthreads], kinfo[:kp_nice], kinfo[:kp_swtime], kinfo[:kp_vm_map_size], kinfo[:kp_vm_rssize], kinfo[:kp_vm_swrss], kinfo[:kp_vm_tsize], kinfo[:kp_vm_dsize], kinfo[:kp_vm_ssize], kinfo[:kp_vm_prssize], kinfo[:kp_jailid], kinfo[:kp_ru], kinfo[:kp_cru], kinfo[:kp_auxflags], kinfo[:kp_lwp], kinfo[:kp_ktaddr], ) struct.freeze # This is readonly data if block_given? yield struct else array << struct end } ensure kvm_close(kd) unless kd.null? end if block_given? nil else pid ? array.first : array end end # Returns an array of fields that each ProcTableStruct will contain. This # may be useful if you want to know in advance what fields are available # without having to perform at least one read of the /proc table. # # Example: # # Sys::ProcTable.fields.each{ |field| # puts "Field: #{field}" # } # def self.fields @fields end end end <file_sep># frozen_string_literal: true module Sys class ProcTable # This represents a cgroup entry # # Have a look at `man 5 proc` on a linux distribution, to get some more # information about the lines and their fields in `/proc/[pid]/cgroup`. # # Example: # # entry = CgroupEntry.new '7:devices:/init.scope' # entry.hierarchy_id # => 7 # entry.subsystems # => ['devices'] # entry.control_group # => '/init.scope' # class CgroupEntry # Create a new cgroup entry object # # This expects a string of '7:devices:/init.scope' - see `man 5 proc` for a # reference. def initialize(string) @string = string.chomp @fields = @string.split(/:/) rescue StandardError @fields = [] end # This returns the hierarchy id of the cgroup entry def hierarchy_id @fields[0].to_i end # Return sets of subsystems bound to the hierarchy def subsystems @fields[1].split(/,/) rescue StandardError [] end # control group in the hierarchy to which the process belongs def control_group @fields[2] end # Return the line itself def to_s @string end end end end <file_sep>require 'sys/top' <file_sep># frozen_string_literal: true require 'sys/proctable/version' require_relative 'proctable/cgroup_entry' require_relative 'proctable/smaps' # The Sys module serves as a namespace only. module Sys # The ProcTable class encapsulates process table information. class ProcTable # Error typically raised if the ProcTable.ps method fails. class Error < StandardError; end # There is no constructor private_class_method :new @mem_total = File.read("/proc/meminfo")[/MemTotal.*/].split[1].to_i * 1024 rescue nil @boot_time = File.read("/proc/stat")[/btime.*/].split.last.to_i rescue nil @fields = [ 'cmdline', # Complete command line 'cwd', # Current working directory 'environ', # Environment 'exe', # Actual pathname of the executed command 'fd', # File descriptors open by process 'root', # Root directory of process 'pid', # Process ID 'comm', # Filename of executable 'state', # Single character state abbreviation 'ppid', # Parent process ID 'pgrp', # Process group 'session', # Session ID 'tty_nr', # TTY (terminal) associated with the process 'tpgid', # Group ID of the TTY 'flags', # Kernel flags 'minflt', # Number of minor faults 'cminflt', # Number of minor faults of waited-for children 'majflt', # Number of major faults 'cmajflt', # Number of major faults of waited-for children 'utime', # Number of user mode jiffies 'stime', # Number of kernel mode jiffies 'cutime', # Number of children's user mode jiffies 'cstime', # Number of children's kernel mode jiffies 'priority', # Nice value plus 15 'nice', # Nice value 'num_threads', # Number of threads in this process 'itrealvalue', # Time in jiffies before next SIGALRM 'starttime', # Time in jiffies since system boot 'vsize', # Virtual memory size in bytes 'rss', # Resident set size 'rlim', # Current limit on the rss in bytes (old) 'rsslim', # Current limit on the rss in bytes (current) 'startcode', # Address above which program text can run 'endcode', # Address below which program text can run 'startstack', # Address of the startstack 'kstkesp', # Kernel stack page address 'kstkeip', # Kernel instruction pointer 'signal', # Bitmap of pending signals 'blocked', # Bitmap of blocked signals 'sigignore', # Bitmap of ignored signals 'sigcatch', # Bitmap of caught signals 'wchan', # Channel in which the process is waiting 'nswap', # Number of pages swapped 'cnswap', # Cumulative nswap for child processes 'exit_signal', # Signal to be sent to parent when process dies 'processor', # CPU number last executed on 'rt_priority', # Real time scheduling priority 'policy', # Scheduling policy 'delayacct_blkio_ticks', # Aggregated block I/O delays 'guest_time', # Guest time of the process 'cguest_time', # Guest time of the process's children 'name', # Process name 'uid', # Real user ID 'euid', # Effective user ID 'gid', # Real group ID 'egid', # Effective group ID 'pctcpu', # Percent of CPU usage (custom field) 'pctmem', # Percent of Memory usage (custom field) 'nlwp', # Number of Light-Weight Processes associated with the process (threads) 'cgroup', # Control groups to which the process belongs 'smaps' # Process memory size for all mapped files ] ProcTableStruct = Struct.new('ProcTableStruct', *@fields) private_constant :ProcTableStruct # In block form, yields a ProcTableStruct for each process entry that you # have rights to. This method returns an array of ProcTableStruct's in # non-block form. # # If a +pid+ is provided, then only a single ProcTableStruct is yielded or # returned, or nil if no process information is found for that +pid+. # # Example: # # # Iterate over all processes # ProcTable.ps do |proc_info| # p proc_info # end # # # Print process table information for only pid 1001 # p ProcTable.ps(pid: 1001) # # # Skip smaps collection and/or cgroup collection # p ProcTable.ps(smaps: false, cgroup: false) # #-- # It's possible that a process could terminate while gathering # information for that process. When that happens, this library # will simply skip to the next record. In short, this library will # either return all information for a process, or none at all. # def self.ps(**kwargs) pid = kwargs[:pid] smaps = kwargs[:smaps] cgroup = kwargs[:cgroup] array = block_given? ? nil : [] struct = nil raise TypeError if pid && !pid.is_a?(Numeric) Dir.foreach("/proc") do |file| next if file =~ /\D/ # Skip non-numeric directories next if pid && file.to_i != pid struct = ProcTableStruct.new # Get /proc/<pid>/cmdline information. Strip out embedded nulls. begin data = File.read("/proc/#{file}/cmdline").tr("\000", ' ').strip struct.cmdline = data rescue StandardError next # Process terminated, on to the next process end # Get /proc/<pid>/cwd information struct.cwd = File.readlink("/proc/#{file}/cwd") rescue nil # Get /proc/<pid>/environ information. Environment information # is represented as a Hash, with the environment variable as the # key and its value as the hash value. struct.environ = {} begin File.read("/proc/#{file}/environ").force_encoding("UTF-8").split("\0").each do |str| key, value = str.split('=') struct.environ[key] = value end rescue Errno::EACCES, Errno::ESRCH, Errno::ENOENT # Ignore and move on. end # Get /proc/<pid>/exe information struct.exe = File.readlink("/proc/#{file}/exe") rescue nil # Get /proc/<pid>/fd information. File descriptor information # is represented as a Hash, with the fd as the key, and its # symlink as the value. struct.fd = {} begin Dir["/proc/#{file}/fd/*"].each do |fd| struct.fd[File.basename(fd)] = File.readlink(fd) rescue nil end rescue StandardError # Ignore and move on end # Get /proc/<pid>/root information struct.root = File.readlink("/proc/#{file}/root") rescue nil # Get /proc/<pid>/stat information stat = File.read("/proc/#{file}/stat") rescue next # Get number of LWP, one directory for each in /proc/<pid>/task/ # Every process has at least one thread, so if we fail to read the task directory, set nlwp to 1. struct.nlwp = Dir.glob("/proc/#{file}/task/*").length rescue struct.nlwp = 1 # Get control groups to which the process belongs unless cgroup == false struct.cgroup = File.readlines("/proc/#{file}/cgroup").map { |l| CgroupEntry.new(l) } rescue [] end # Read smaps, returning a parsable string if we don't have permissions. # Note: We're blindly rescuing because File.readable?/readable_real? # are true for a file in the /proc fileystem but raises a Errno:EACCESS # when your try to read it without permissions. unless smaps == false smaps_contents = File.read("/proc/#{file}/smaps") rescue "" struct.smaps = Smaps.new(file, smaps_contents) end # Deal with spaces in comm name. This isn't supposed to happen, but in # rare cases - the original offending case was "(xzen thread)" - it can # occur. So we parse it out, replace the spaces with hyphens, and # re-insert it into the stat string so that it splits properly later on. # # Courtesy of <NAME>. # re = /\([^)]+\)/ comm = stat[re] comm.tr!(' ', '-') stat[re] = comm stat = stat.split struct.pid = stat[0].to_i struct.comm = stat[1].tr('()', '') # Remove parens struct.state = stat[2] struct.ppid = stat[3].to_i struct.pgrp = stat[4].to_i struct.session = stat[5].to_i struct.tty_nr = stat[6].to_i struct.tpgid = stat[7].to_i struct.flags = stat[8].to_i struct.minflt = stat[9].to_i struct.cminflt = stat[10].to_i struct.majflt = stat[11].to_i struct.cmajflt = stat[12].to_i struct.utime = stat[13].to_i struct.stime = stat[14].to_i struct.cutime = stat[15].to_i struct.cstime = stat[16].to_i struct.priority = stat[17].to_i struct.nice = stat[18].to_i struct.num_threads = stat[19].to_i struct.itrealvalue = stat[20].to_i struct.starttime = stat[21].to_i struct.vsize = stat[22].to_i struct.rss = stat[23].to_i struct.rlim = stat[24].to_i # Old name for backwards compatibility struct.rsslim = stat[24].to_i struct.startcode = stat[25].to_i struct.endcode = stat[26].to_i struct.startstack = stat[27].to_i struct.kstkesp = stat[28].to_i struct.kstkeip = stat[29].to_i struct.signal = stat[30].to_i struct.blocked = stat[31].to_i struct.sigignore = stat[32].to_i struct.sigcatch = stat[33].to_i struct.wchan = stat[34].to_i struct.nswap = stat[35].to_i struct.cnswap = stat[36].to_i struct.exit_signal = stat[37].to_i struct.processor = stat[38].to_i struct.rt_priority = stat[39].to_i struct.policy = stat[40].to_i struct.delayacct_blkio_ticks = stat[41].to_i struct.guest_time = stat[42].to_i struct.cguest_time = stat[43].to_i # Get /proc/<pid>/status information (name, uid, euid, gid, egid) begin File.foreach("/proc/#{file}/status") do |line| case line when /Name:\s*?(\w+)/ struct.name = Regexp.last_match(1) when /Uid:\s*?(\d+)\s*?(\d+)/ struct.uid = Regexp.last_match(1).to_i struct.euid = Regexp.last_match(2).to_i when /Gid:\s*?(\d+)\s*?(\d+)/ struct.gid = Regexp.last_match(1).to_i struct.egid = Regexp.last_match(2).to_i end end rescue Errno::ESRCH, Errno::ENOENT next end # If cmdline is empty use comm instead struct.cmdline = struct.comm if struct.cmdline.empty? # Manually calculate CPU and memory usage struct.pctcpu = get_pctcpu(struct.utime, struct.starttime) struct.pctmem = get_pctmem(struct.rss) struct.freeze # This is read-only data if block_given? yield struct else array << struct end end pid ? struct : array end # Returns an array of fields that each ProcTableStruct will contain. This # may be useful if you want to know in advance what fields are available # without having to perform at least one read of the /proc table. # # Example: # # Sys::ProcTable.fields.each{ |field| # puts "Field: #{field}" # } # class << self attr_reader :fields end # Calculate the percentage of memory usage for the given process. # def self.get_pctmem(rss) return nil unless @mem_total page_size = 4096 rss_total = rss * page_size format("%3.2f", (rss_total.to_f / @mem_total) * 100).to_f end private_class_method :get_pctmem # Calculate the percentage of CPU usage for the given process. # def self.get_pctcpu(utime, start_time) return nil unless @boot_time hertz = 100.0 utime = (utime * 10000).to_f stime = (start_time.to_f / hertz) + @boot_time format("%3.2f", (utime / 10000.0) / (Time.now.to_i - stime)).to_f end private_class_method :get_pctcpu end end <file_sep>require_relative 'sys/proctable' <file_sep>## 1.3.0 - 26-Dec-2022 * Added DragonflyBSD support. * Reorganized the BSD code so that FreeBSD and Dragonfly BSD live in their own space for easier maintenance. ## 1.2.7 - 28-Oct-2022 * Fix bug on Solaris where it would fail trying to read zero-byte pseudo-kernel processes. Thanks go to <NAME> for the spot and the patch. * Fixed a bug for MacOS that potentially caused it to miss thread info. * Fixed specs for AIX that had gotten mangled when I switched to rspec * Some gemspec updates, including the addition of rubocop as a development dependency, and mandatory MFA. * Lots of rubocop related updates, mostly stylistic, but in some cases things that were always meant to be private (like C struct wrappers) have been explicitly marked as private. * Lots of general spec refactoring, including updates for MacOS since Catalina and later that no longer allow you to collect env information for spawned processes. * Switched to github actions. ## 1.2.6 - 25-Aug-2020 * Made some updates so that it worked properly with TruffleRuby on Mac. * Fixed an issue on Linux where non-ascii environ strings could cause failure. Thanks go to deemytch for the spot and original patch. * Removed the spec_helper.rb file, just use Process.spawn instead of messing around with custom fork implementations. This also helps with implementations that don't support fork. * Updated the MANIFEST. ## 1.2.5 - 19-Jun-2020 * Added the delayacct_blkio_ticks, guest_time, and cguest_time fields on Linux. These require 2.6.18 or later, but will simply be nil on earlier versions. * Added the rsslim synonym for the rlim field for Linux. ## 1.2.4 - 18-Jun-2020 * Added the num_threads field for Linux. This was originally a dead field in older versions of Linux that was skipped, but as of Linux 2.6+ it actually holds meaningful data. * Updated the specs for Linux. ## 1.2.3 - 17-Mar-2020 * Properly include a copy of Apache-2.0 in LICENSE file as part of library. * Add explicit .rdoc extensions to CHANGES and MANIFEST files. ## 1.2.2 - 12-Aug-2019 * Added compatibility for JRuby on Mac which apparently doesn't define a read_uint64 method, nor a CharArray. Thanks go to <NAME> for the spot. * Refactored the specs a bit, adding a spec_helper.rb. This was mainly for JRuby compatibility. * Updates to the travis.yml file for both Ruby and JRuby versions. * Removed the doc directory and all the files it contained. It was redundant, and some of the information was wrong. All of the documentation you need is on the wiki. * Cleaned up the MANIFEST file, updated the gemspec, and fixed the license name, which was missing a hyphen. ## 1.2.1 - 8-Jun-2018 * The code for OSX is now more efficient when a pid argument is provided. Thanks go to <NAME> for his efforts. * Added metadata to the gemspec. * Switched the README (now README.md) to markdown format. Thanks go to <NAME> for the update. * Updated the cert. Should be good for ten years now. ## 1.2.0 - 20-Feb-2018 * There has been an API change. The ProcTable.ps method now uses keyword arguments. The 'pid' option is universal, the rest depend on the platform. As part of this change, support for Ruby < 2.0 has been dropped. * Support for HP-UX has been dropped, both because it was the last remaining platform that still used C code, and because it's basically a dead platform. * There are no more platform-specific gems. There is now a single gem that will load the appropriate code based on your host's operating system. * The tests were switched from test-unit to rspec. * Lots of Rakefile updates based on the above changes. * The cert was updated. ## 1.1.5 - 10-Aug-2017 * Fixed a warning that cropped up in Ruby 2.4.x because I was type checking against Fixnum. Those have been replaced with Numeric. ## 1.1.4 - 30-Mar-2017 * Fixed a potential issue where OSX could return a struct with invalid data. * Set the default field to :pid for OSX when using Sys::Top. * Fixed a duplicate test warning for OSX. ## 1.1.3 - 28-Sep-2016 * Fixed an issue on OSX where the value returned for argc is invalid. ## 1.1.2 - 18-Sep-2016 * Fixed cmdline parsing and handling for OSX. Thanks go to <NAME> for the spot and the patch. ## 1.1.1 - 30-Jun-2016 * Added thread information for OS X. * Fixed VERSION constant for HP-UX. ## 1.1.0 - 27-Jun-2016 * License was changed to Apache 2.0. * The OS X version now requires OS X 10.7 or later. * Scrapped the C implementation for OS X, and replaced it with a libproc wrapper using FFI, so it is now pure Ruby. Note that some new struct members have been added, while others have been dropped. This includes pctcpu, so Sys::Top does not work at the moment. * Rakefile updates to accomodate the changes for OS X. * Some test suite updates and refactoring. ## 1.0.0 - 11-Jan-2016 * Added smaps information for Linux. Thanks go to <NAME> for the patch. * This really should not have been a major release, sorry. ## 0.9.9 - 8-Nov-2015 * Added support for cgroups on Linux. Thanks go to <NAME> for the patch. * Added a sys-proctable.rb file for convenience. * This gem is now signed. * Gem related tasks in the Rakefile now assume Rubygems 2.x. ## 0.9.8 - 18-Apr-2015 * Fixed a bug in the gemspec. Last version got yanked. ## 0.9.7 - 18-Apr-2015 * Fixed a bug in the OSX code that could cause the ps method to fail. Thanks go to Koshe<NAME>on for the spot. * Some internal refactoring of version handling. Now all platforms use a single version file. * Replaced vm_size_t and lwpid_t with universal data types on FreeBSD because FFI on FreeBSD 10 no longer understands them. Thanks go to <NAME> for the spot. ## 0.9.6 - 24-Feb-2015 * Added NLWP field on Linux. Thanks go to <NAME> for the patch. ## 0.9.5 - 10-Feb-2015 * Significant cleanup and memory reduction of the OSX code. Thanks go to Ivan (toy) for the patches. * Skip over /proc/<file>/status if unreadable on Linux. Thanks go to Jianjun Mao for the patch. ## 0.9.4 - 4-Mar-2014 * Added support for AIX 5.3 or later courtesy of <NAME>. * The Solaris version now uses FFI structs instead of a packed array. It solved issues with 64-bit versions of Ruby and it's self-documenting. * The FreeBSD version has been converted to use FFI. In addition, additional struct members have been added, and members that previously returned nil now return meaningful data. * Support for NetBSD and OpenBSD has been temporarily dropped. Considering that the C code did not build on those platforms anyway, I doubt most of you will notice. Patches for those platforms are welcome, but only using FFI. ## 0.9.3 - 17-Mar-2013 * Fixed a bug on OSX where a long command string arg could cause a segfault. Thanks go to <NAME> for the spot. * Changed the gem platform from mingw to mingw32 for Windows. ## 0.9.2 - 8-Oct-2012 * Added cmdline support for OS X. Thanks go to <NAME> for the patch. * Warning cleanup for 1.9. * Updated the gem platform handling. Replaced the borked string approach with a two element array for Gem::Platform.new. * MS date strings are now parse with DateTime instead of Date. ## 0.9.1 - 3-Aug-2011 * Added the pctcpu and pctmem members for Linux. * Added Errno::ESRCH to a rescue clause on Linux that fixed a bug where a missing entry wasn't being skipped when run as root. Thanks go to <NAME> for the spot and patch. * Fixed a build warning for Darwin. * Updates to the test suite for both Darwin and Linux. * Added an explicit type check for BSD for pids. * Added nicer error messages for BSD if kvm_open fails. * Added .core files to the clean task. * Altered the platform settings in the Rakefile so that generated gems use 'universal' platform architectures for any particular operating system. ## 0.9.0 - 14-Oct-2009 * Changed the license to Artistic 2.0. * Fixed a bug in the OS X code where a segfault would occur when an attempt was made to gather resource usage information on zombie processes. From now on that information is always set to nil for zombie processes. Thanks go to <NAME> for the spot and <NAME> for investigating the root cause of the failure. * Removed the FreeBSD code that read out of /proc. It was a pain from a maintenance point of view, and most FreeBSD installs do not mount /proc by default. The FreeBSD platform now uses the same code that the other BSD platforms use. * Fixed a bug in the BSD code where the ProcTable::Error class had the wrong parent class. * Some major gemspec updates, including an updated license. The platform handling logic is now in the Rakefile in the 'gem' task. * Updated the README file to include an additional acknowledgement, a license change and some minor formatting changes. * The test-unit library was changed from a runtime to a development dependency. ## 0.8.1 - 6-Apr-2009 * The Linux and Solaris libraries now handle the possibility of a process terminating in the middle of a read more gracefully. If that happens, they merely skip to the next record, i.e. it's all or nothing. Thanks go to <NAME> for the spot and patch. * Fixed a bug in the Linux version where embedded nulls were not being stripped out of the cmdline data. * Added the comm alias back to the Solaris version. Thanks go to <NAME> for the spot. ## 0.8.0 - 26-Jan-2009 * The Linux and Solaris versions of this library are now pure Ruby. Be warned, however, that only Solaris 8 and later are now supported. This may change in a future release if there's demand to support 2.6 and 2.7. * Some Struct::ProcTableStruct members have changed. As a general rule they now more closely match the C struct member name. See individual platforms for more details. * Bug fix for the cmd_args struct member on Solaris. * Bug fixes for OS X. Added a VERSION constant, fixed struct name, and changed pct_cpu to pctcpu. * The .new method is now explicitly illegal. * The Struct::ProcTableStruct instances are now frozen. This is read-only data. * Added the peak_page_file_usage and status members on MS Windows. The status member is always nil, but was added for completeness. * Fixed the quota_peak_paged_pool_usage member on MS Windows. * ProcTableError is now ProcTable::Error. * Minor test case fix for kvm/bsd based versions. * Added the 'time' library as a require for Windows (to parse MS date/time format strings). * The kvm (bsd.c) implementation now works for FreeBSD 7. * Added many more tests. * Added some benchmarking code in the 'benchmarks' directory. * Added a 'bench' Rake task. * Renamed the test_ps.rb file to example_ps.rb in order to avoid any possible confusion with actual test files. * Added an 'example' rake task to run the example file. ## 0.7.6 - 11-Jul-2007 * Fixed the starttime for Linux. Thanks go to <NAME> for the spot. * Fixed a bug in the MS Windows version within a private method that parsed an MS specific date format. This was caused by a backwards incompatible change in the Time.parse method in Ruby 1.8.6. See ruby-core: 11245 ff. * Fixed the gemspec (I hope). Please let me know if you have problems. * Added a Rakefile. Building, testing and installing should now be handled via Rake tasks. The install.rb file has been removed - that code is now integrated in the Rakefile. * Minor directory layout changes and cleanup (mostly for the extconf.rb file). * Side note - it seems that the code for OS X *does* work, at least on 10.4.10. I can only conclude that previous reports about it failing were related to bugs in OS X or were really just build issues. Apologies (and thanks, again) to David Felstead for the code. However, see the README for more information specific to OS X, as there are shortcomings. ## 0.7.5 - 23-Nov-2006 * Fixed int/long issues for Linux. Thanks go to <NAME> for the spot. * Minor documentation fixes and changes to the extconf.rb file. ## 0.7.4 - 20-Nov-2006 * Added a patch that deals with the large file compilation issue on Solaris. You no longer need to build Ruby with --disable-largefile, or build a 64 bit Ruby, in order for this package to work. Thanks go to <NAME> for the information that led to the patch. * Added inline rdoc to the source code. * Added a gemspec. * Fixed some potential 64 bit issues (struct declarations). * Added preliminary support for Darwin (OS X). The code was provided by <NAME>, but does not appear to compile successfully. Help wanted. ## 0.7.3 - 27-Oct-2005 * Fix for 1.8.3 and later (rb_pid_t). This should have only affected Solaris. ## 0.7.2 - 15-May-2005 * Bug fix for the FreeBSD version that reads from /proc. * Eliminated the test bug on Linux (inexplicably caused by File.copy). The test suite should now run without segfaulting. * Include bsd.c in tarball (oops). * Minor test updates for FreeBSD. * The 'pct_cpu' member for the BSD/kvm version has been changed to 'pctcpu' for consistency with other platforms. ## 0.7.1 - 8-May-2005 * Bug fixed for the cmdline info on Linux. Thanks go to <NAME> for the spot. * Added an example program. * Minor setup fix for Win32 in tc_all.rb. ## 0.7.0 - 25-Apr-2005 * Scrapped the C implementation for Windows in favor of an OLE + WMI pure Ruby approach. See documentation for details. * Added an optional lkvm implementation for BSD users. This is automatically used if the /proc filesystem isn't found. * Added prusage info for the Solaris version. * Added name, eid, euid, gid and guid information for Linux. Thanks go to <NAME> for the patch. * Fixed some potential bugs in the Linux version. Thanks go to James Hranicky for the spot. * Added the 'sys/top' package. * ProcTable.fields no longer supports a block form. * The BTIME (boot time) information has been removed from the Linux version. If you want that information, use sys-uptime instead. * The .html and .rd files have been removed. You can generate html on your own with rdoc if you like. * Some code cleanup on the C side of the house. * Most documents made rdoc friendly. * Renamed 'install_pure_ruby.rb' to just 'install.rb'. * Removed the 'INSTALL' file. Installation instructions are in the README. * Some test suite cleanup and reorganization. * Moved project to RubyForge. ## 0.6.4 - 31-Mar-2004 * Fixed a bug in the pure Ruby version for Win32. Thanks go to <NAME> for the spot. * Fixed a bug in the C implementation for Win32 where the cmdline and path values were sometimes wrong for running processes. Thanks go to <NAME> for the fix. * Updated the VERSION constant and removed the VERSION class method in the pure Ruby version for Win32. * Updated install_pure_ruby.rb and test.rb scripts. * Updated warranty information. * The extconf.rb script has been revamped. See the INSTALL and README files for important changes since the last release. * The start ProcInfo struct member on Solaris, HP-UX and FreeBSD is now a Time object, not a Fixnum/Bignum. * Modified linux.c yet again to make gcc happy when it comes to multi-line string literals. * Minor change to way process state is handled on HP-UX. * Documentation additions and updates, including warranty information. ## 0.6.3 - 24-Feb-2004 * Fixed a bug in the Solaris version where the cmd_args array did not necessarily contain data on 2.7 and later. The current patch still does not quite fix the problem for 2.6 and earlier but can be easily derived manually by parsing the cmdline string. ## 0.6.2 - 20-Jan-2004 * Fixed a small memory leak in the solaris version. ## 0.6.1 - 31-Dec-2003 * Fixed a minor bug in the cmdline field on Linux where a blank character was being appended to the end of the field. * Fixed a minor annoyance where the windows.rb file was being copied into the Ruby lib directory on install. * Added a test_memleak.rb file. Currently only supported on Linux and only does a file descriptor count check. I plan to expand this to other platforms in the future. * Minor test suite changes * MANIFEST correction and update. ## 0.6.0 - 22-Oct-2003 * Significant API change (and thus, a version jump) - only a single argument is now accepted to the ps() method, and only a PID (Fixnum) is regarded as a valid argument. * Calling ps() with a pid returns a single ProcTable struct (or nil if the pid is not found), instead of a one element array. * Argument to ps() now works properly on HP-UX and Win32. * Removed the '#include <sys/types32.h>' in sunos.h. It wasn't needed and you're not supposed to include it directly. * Fixed 2.6 compatibility issue with regards to cmdline on Solaris. * Removed the ProcStatException completely on Linux. There was no reason to fail on a directory read for /proc/xxx/stat. If the read fails (meaning the process died in the middle of collecting info for it), it is simply ignored. * The ttynum bug on HPUX has been fixed. In addition, the return value for this field is now a string rather than an int and the field name has been changed to "ttydev". * The ttynum field has been changed to ttydev on Solaris and HPUX. On Solaris, the ttydev is now reported as -1 if there is no associated tty. In a future release, Solaris and the other *nix platforms will be changed so that ttydev is always a device name (i.e String). * Added plain text documentation for all platforms. * Some test suite cleanup. * Changed .rd2 extension to just '.rd'. ## 0.5.2 - 18-Jul-2003 * Modified cmdline to extend past the traditional 80 character limit on Solaris, where possible (Solaris 2.6+ only). * Added the cmdline_args and num_args fields on Solaris, which returns an array of cmdline arguments and the number of cmdline arguments, respectively. * Minor modification to fields() method, in addition to warning cleanup for Solaris. * Changed "defunct" state string to "zombie" for Solaris. * Should cleanly compile with -Wall -W now (gcc) on Solaris. * Added solaris.txt to doc directory. * MANIFEST corrections. ## 0.5.1 - 16-Jul-2003 * Fixed a nasty file descriptor bug in the Linux code, where file descriptors were continuously being used up. * Added the BTIME (boot time) constant for Linux. * Fixed up the test/test.rb file a bit. * Added BTIME tests to tc_linux.rb. ## 0.5.0 - 11-Jul-200 * Added HP-UX support! * Note that passing PID's or strings as arguments to ps() is not supported in the HP-UX version. This functionality will be stripped out of the other versions in a future release. See the README file for more details. * Removed the VERSION() class method. Use the constant instead. * Separated the rd docs from their respective source files. Now in the doc directory. * Got rid of the interactive html generation in extconf.rb. * Changed License to Artistic. ## 0.4.3 - 30-May-2003 * Added a version.h file to store the version number. Modified all of the C source files to use that instead of hard coding the version everywhere. * Added a generic test.rb script for those without TestUnit installed, or just futzing in general. Modified the extconf.rb script to copy this instead of writing an inline HERE document. * Modified extconf.rb so that it builds with mingw or cygwin. Thanks go to <NAME> for the spot and patch. * Modified test suite to work with TestUnit 0.1.6 or 0.1.8. ## 0.4.2 - 14-Apr-2003 * Added pure Ruby version for Win32 - thanks <NAME>. * Modified extconf.rb file to handle pure Ruby versions. * Added install_pure_ruby.rb file, an alternate installation script for pure Ruby versions. ## 0.4.1 - 31-Mar-2003 * Added support for Solaris 2.5.x. * All exceptions are now a direct subclass of StandardError. * Value returned for wchan now more meaningful (2.5.x only for now). * Fixed the start, utime and ctime for FreeBSD. * Minor fix to FreeBSD test suite. * Some changes to extconf.rb. * Minor doc changes. * Added License and Copyright info. ## 0.4.0 - 10-Mar-2003 * Added MS Windows support (non-cygwin). * Added environment information for Linux version. * Added real exceptions (type depends on platform). * Added a test suite (for those with testunit installed). * Removed the sys-uname requirement. * Heavily modified the extconf.rb script. * Changed "Changelog" to "CHANGES" and "Manifest" to "MANIFEST". * Added a VERSION constant and class method. * Minor internal directory layout change (put 'os' under 'lib'). * Changed package name to lower case. * Doc changes, including license information. ## 0.3.1 - 16-Aug-2002 * Added a "comm" field to the sunos version. I am going to try to make this a common field for all platforms to help reduce RUBY_PLATFORM checking. * Fixed the release date for 0.3.0 (was accidentally marked *July*). * Added an INSTALL file. * Minor documentation change to the sunos.c source file. ## 0.3.0 - 11-Aug-2002 * Added FreeBSD support! * Struct name changed to just "ProcTableStruct" to be compliant with future versions of Ruby. * The ps() function now returns an array of ProcTableStruct's in lvalue context. * Fixed the ability to search by process name in Linux. * Modified Linux "comm" field to strip parenthesis. * Some doc changes/additions. * Added <NAME> to the "Acknowledgements" section. Sean provided me with access to a FreeBSD box, which is how I was able to provide FreeBSD support. Thanks Sean! ## 0.2.0 - 19-Jul-2002 * Added the ability to search by process name. * test.rb modified to be cross-platform. * Solaris - fixed bug with fname (was accidentally called "name"). ## 0.1.0 - 2-Jul-2002 - Initial release. <file_sep>require 'rspec' require 'sys-proctable' require 'sys-top' RSpec.configure do |config| config.filter_run_excluding(:aix) unless RbConfig::CONFIG['host_os'] =~ /aix/i config.filter_run_excluding(:darwin) unless RbConfig::CONFIG['host_os'] =~ /mac|darwin/i config.filter_run_excluding(:linux) unless RbConfig::CONFIG['host_os'] =~ /linux/i config.filter_run_excluding(:bsd) unless RbConfig::CONFIG['host_os'] =~ /bsd|dragonfly/i config.filter_run_excluding(:freebsd) unless RbConfig::CONFIG['host_os'] =~ /freebsd/i config.filter_run_excluding(:dragonfly) unless RbConfig::CONFIG['host_os'] =~ /dragonfly/i config.filter_run_excluding(:sunos) unless RbConfig::CONFIG['host_os'] =~ /sunos|solaris/i config.filter_run_excluding(:windows) unless Gem.win_platform? config.filter_run_excluding(:jruby) if RUBY_PLATFORM == 'java' end
75cb38504f1e36a796eb545a8ede7684a0c2883d
[ "Markdown", "Ruby" ]
35
Ruby
djberg96/sys-proctable
d35ba2fcf0d7ee81ca16c4e20fcd347e5cd07fd8
88de3e61340d640ed85941f1d20da9ed6e719762
refs/heads/master
<file_sep># Maintainer: jglaser set(COMPONENT_NAME metadynamics) set(_${COMPONENT_NAME}_sources module.cc IntegratorMetaDynamics.cc LamellarOrderParameter.cc LamellarOrderParameterGPU.cc OrderParameterMesh.cc OrderParameterMeshGPU.cc WellTemperedEnsemble.cc CollectiveWrapper.cc IndexGrid.cc CollectiveVariable.cc AspectRatio.cc Density.cc SteinhardtQl.cc ) set(_${COMPONENT_NAME}_cu_sources IntegratorMetaDynamics.cu LamellarOrderParameterGPU.cu OrderParameterMeshGPU.cu WellTemperedEnsemble.cu ) include_directories(${HOOMD_INCLUDE_DIR}/hoomd/extern/dfftlib/src) # Need to define NO_IMPORT_ARRAY in every file but module.cc set_source_files_properties(${_${COMPONENT_NAME}_sources} ${_${COMPONENT_NAME}_cu_sources} PROPERTIES COMPILE_DEFINITIONS NO_IMPORT_ARRAY) if (ENABLE_CUDA) CUDA_COMPILE(_CUDA_GENERATED_FILES ${_${COMPONENT_NAME}_cu_sources} OPTIONS ${CUDA_ADDITIONAL_OPTIONS} SHARED) endif (ENABLE_CUDA) pybind11_add_module (_${COMPONENT_NAME} SHARED ${_${COMPONENT_NAME}_sources} ${_CUDA_GENERATED_FILES} NO_EXTRAS) # link the library to its dependencies target_link_libraries(_${COMPONENT_NAME} ${HOOMD_LIBRARIES} ${HOOMD_MD_LIB}) # if we are compiling with MPI support built in, set appropriate # compiler/linker flags if (ENABLE_MPI) if(MPI_COMPILE_FLAGS) set_target_properties(_${COMPONENT_NAME} PROPERTIES COMPILE_FLAGS "${MPI_CXX_COMPILE_FLAGS}") endif(MPI_COMPILE_FLAGS) if(MPI_LINK_FLAGS) set_target_properties(_${COMPONENT_NAME} PROPERTIES LINK_FLAGS "${MPI_CXX_LINK_FLAGS}") endif(MPI_LINK_FLAGS) endif(ENABLE_MPI) ################################## # change the name of the library to be a valid python module # tweak the properties of the output to make a functional python module set_target_properties(_${COMPONENT_NAME} PROPERTIES PREFIX "" OUTPUT_NAME "_${COMPONENT_NAME}") # .dylib is not recognized as a python module by python on Mac OS X if(APPLE) set_target_properties(_${COMPONENT_NAME} PROPERTIES SUFFIX ".so") endif(APPLE) fix_cudart_rpath(_${COMPONENT_NAME}) # install the library install(TARGETS _${COMPONENT_NAME} LIBRARY DESTINATION ${PYTHON_MODULE_BASE_DIR}/${COMPONENT_NAME} ) ################ Python only modules # copy python modules to the build directory to make it a working python package MACRO(copy_file file) add_custom_command ( OUTPUT ${file} POST_BUILD COMMAND ${CMAKE_COMMAND} ARGS -E copy ${CMAKE_CURRENT_SOURCE_DIR}/${file} ${CMAKE_CURRENT_BINARY_DIR}/${file} COMMENT "Copy hoomd/${COMPONENT_NAME}/${file}" ) ENDMACRO(copy_file) set(files __init__.py integrate.py cv.py ) install(FILES ${files} DESTINATION ${PYTHON_MODULE_BASE_DIR}/${COMPONENT_NAME} ) foreach(file ${files}) copy_file(${file}) endforeach() add_custom_target(copy_${COMPONENT_NAME} ALL DEPENDS ${files}) if (BUILD_TESTING) add_subdirectory(test-py) endif() <file_sep>#include "CollectiveVariable.h" class AspectRatio : public CollectiveVariable { public: AspectRatio(std::shared_ptr<SystemDefinition> sysdef, const unsigned int dir1, unsigned int dir2); virtual ~AspectRatio() {} virtual Scalar getCurrentValue(unsigned int timestep); /*! Returns the names of provided log quantities. */ std::vector<std::string> getProvidedLogQuantities() { std::vector<std::string> list = CollectiveVariable::getProvidedLogQuantities(); list.push_back(m_log_name); return list; } /*! Returns the value of a specific log quantity. * \param quantity The name of the quantity to return the value of * \param timestep The current value of the time step */ Scalar getLogValue(const std::string& quantity, unsigned int timestep) { if (quantity == m_log_name) return getCurrentValue(timestep); return CollectiveVariable::getLogValue(quantity, timestep); } /*! Returns true if the collective variable can compute derivatives * w.r.t. particle coordinates */ virtual bool canComputeDerivatives() { return false; } private: /*! Compute the biased forces for this collective variable. The force that is written to the force arrays must be multiplied by the bias factor. \param timestep The current value of the time step */ virtual void computeBiasForces(unsigned int timestep); unsigned int m_dir1; //!< The cartesian index of the first direction unsigned int m_dir2; //!< The cartesian index of the second direction std::string m_log_name; //!< The name of the collective variable }; //! Export AspectRatio to Python void export_AspectRatio(pybind11::module& m); <file_sep>#ifndef __LAMELLAR_ORDER_PARAMETER_H__ #define __LAMELLAR_ORDER_PARAMETER_H__ /*! \file LamellarOrderParameter.h \brief Declares the LamellarOrderParameter class */ #include <string.h> #include "CollectiveVariable.h" // need to declare these classes with __host__ __device__ qualifiers when building in nvcc // HOSTDEVICE is __host__ __device__ when included in nvcc and blank when included into the host compiler #ifdef NVCC #define HOSTDEVICE __host__ __device__ #else #define HOSTDEVICE #endif //! Collective variable for studying phase transitions in block copolymer systems /*! This class implements a collective variable based on the Fourier modes of concentration fluctuations. The value of the collective variable \f$ s \f$ is given by \f$ s = \sum_{i = 1}^n \sum_{j = 1}^N a(type_j \cos(\mathbf{q}_i\mathbf{r_j} + \phi_i)) \f$, where \f$n\f$ is the number of modes supplied, \f$ \mathbf{q}_i = 2 \pi (n_{i,x}/L_x, n_{i,y}/L_y, n_{i,z}/L_z) \f$ is the wave vector associated with mode \f$i\f$, \f$\phi_i\f$ its phase shift, and $a(type_j)$ is the mode coefficient for a particle of type \f$type\f$. The force is calculated as minus the derivative of \f$s\f$ with respect to particle positions \f$\mathbf{r}_j\f$, multiplied by the bias factor. */ class LamellarOrderParameter : public CollectiveVariable { public: /*! Constructs the collective variable \param sysdef The system definition \param mode The per-type coefficients of the Fourier mode \param lattice_vectors The Miller indices of the mode vector \param suffix The suffix appended to the log name for this quantity */ LamellarOrderParameter(std::shared_ptr<SystemDefinition> sysdef, const std::vector<Scalar>& mode, const std::vector<int3>& lattice_vectors, const std::string& suffix = "" ); virtual ~LamellarOrderParameter() {} /*! Compute the forces for this collective variable. The force that is written to the force arrays must be multiplied by the bias factor. \param timestep The current value of the time step */ virtual void computeBiasForces(unsigned int timestep); /*! Returns the names of provided log quantities. */ std::vector<std::string> getProvidedLogQuantities() { std::vector<std::string> list = CollectiveVariable::getProvidedLogQuantities(); list.push_back(m_log_name); return list; } /*! Returns the value of a specific log quantity. * \param quantity The name of the quantity to return the value of * \param timestep The current value of the time step */ Scalar getLogValue(const std::string& quantity, unsigned int timestep); /*! Returns the current value of the collective variable * \param timestep The current value of the time step */ Scalar getCurrentValue(unsigned int timestep) { this->computeCV(timestep); return m_cv; } protected: std::string m_log_name; //!< The log name for this collective variable std::vector<Scalar> m_mode; //!< Stores the per-type mode coefficients Scalar m_cv; //!< The current value of the collective variable GPUArray<int3> m_lattice_vectors; //!< GPUArray of lattice vectors GPUArray<Scalar2> m_fourier_modes; //!< Fourier modes unsigned int m_cv_last_updated; //!< Timestep the collective variable was last updated //! Calculates the current value of the collective variable virtual void computeCV(unsigned int timestep); private: //! Helper function to calculate the Fourier modes void calculateFourierModes(); }; //! Export LamellarOrderParameter to python void export_LamellarOrderParameter(pybind11::module& m); #endif // __LAMELLAR_ORDER_PARAMETER_H__ <file_sep>#include "OrderParameterMeshGPU.h" namespace py = pybind11; #ifdef ENABLE_CUDA #include "OrderParameterMeshGPU.cuh" /*! \param sysdef The system definition \param nx Number of cells along first axis \param ny Number of cells along second axis \param nz Number of cells along third axis \param mode Per-type modes to multiply density \param zero_modes List of modes that should be zeroed */ OrderParameterMeshGPU::OrderParameterMeshGPU(std::shared_ptr<SystemDefinition> sysdef, const unsigned int nx, const unsigned int ny, const unsigned int nz, std::vector<Scalar> mode, std::vector<int3> zero_modes) : OrderParameterMesh(sysdef, nx, ny, nz, mode,zero_modes), m_local_fft(true), m_sum(m_exec_conf), m_block_size(256), m_gpu_q_max(m_exec_conf) { unsigned int n_blocks = m_mesh_points.x*m_mesh_points.y*m_mesh_points.z/m_block_size+1; GlobalArray<Scalar> sum_partial(n_blocks,m_exec_conf); m_sum_partial.swap(sum_partial); GlobalArray<Scalar> sum_virial_partial(6*n_blocks,m_exec_conf); m_sum_virial_partial.swap(sum_virial_partial); GlobalArray<Scalar> sum_virial(6,m_exec_conf); m_sum_virial.swap(sum_virial); GlobalArray<Scalar4> max_partial(n_blocks, m_exec_conf); m_max_partial.swap(max_partial); // initial value of number of particles per bin m_cell_size = 2; } OrderParameterMeshGPU::~OrderParameterMeshGPU() { if (m_local_fft) cufftDestroy(m_cufft_plan); #ifdef ENABLE_MPI else { dfft_destroy_plan(m_dfft_plan_forward); dfft_destroy_plan(m_dfft_plan_inverse); } #endif } void OrderParameterMeshGPU::initializeFFT() { #ifdef ENABLE_MPI m_local_fft = !m_pdata->getDomainDecomposition(); if (! m_local_fft) { // ghost cell communicator for charge interpolation m_gpu_grid_comm_forward = std::unique_ptr<CommunicatorGridGPUComplex>( new CommunicatorGridGPUComplex(m_sysdef, make_uint3(m_mesh_points.x, m_mesh_points.y, m_mesh_points.z), make_uint3(m_grid_dim.x, m_grid_dim.y, m_grid_dim.z), m_n_ghost_cells, true)); // ghost cell communicator for force mesh m_gpu_grid_comm_reverse = std::unique_ptr<CommunicatorGridGPUComplex >( new CommunicatorGridGPUComplex(m_sysdef, make_uint3(m_mesh_points.x, m_mesh_points.y, m_mesh_points.z), make_uint3(m_grid_dim.x, m_grid_dim.y, m_grid_dim.z), m_n_ghost_cells, false)); // set up distributed FFT int gdim[3]; int pdim[3]; Index3D decomp_idx = m_pdata->getDomainDecomposition()->getDomainIndexer(); pdim[0] = decomp_idx.getD(); pdim[1] = decomp_idx.getH(); pdim[2] = decomp_idx.getW(); gdim[0] = m_mesh_points.z*pdim[0]; gdim[1] = m_mesh_points.y*pdim[1]; gdim[2] = m_mesh_points.x*pdim[2]; int embed[3]; embed[0] = m_mesh_points.z+2*m_n_ghost_cells.z; embed[1] = m_mesh_points.y+2*m_n_ghost_cells.y; embed[2] = m_mesh_points.x+2*m_n_ghost_cells.x; m_ghost_offset = (m_n_ghost_cells.z*embed[1]+m_n_ghost_cells.y)*embed[2]+m_n_ghost_cells.x; uint3 pcoord = m_pdata->getDomainDecomposition()->getGridPos(); int pidx[3]; pidx[0] = pcoord.z; pidx[1] = pcoord.y; pidx[2] = pcoord.x; int row_m = 0; /* both local grid and proc grid are row major, no transposition necessary */ ArrayHandle<unsigned int> h_cart_ranks(m_pdata->getDomainDecomposition()->getCartRanks(), access_location::host, access_mode::read); #ifndef USE_HOST_DFFT dfft_cuda_create_plan(&m_dfft_plan_forward, 3, gdim, embed, NULL, pdim, pidx, row_m, 0, 1, m_exec_conf->getMPICommunicator(), (int *) h_cart_ranks.data); dfft_cuda_create_plan(&m_dfft_plan_inverse, 3, gdim, NULL, embed, pdim, pidx, row_m, 0, 1, m_exec_conf->getMPICommunicator(), (int *)h_cart_ranks.data); #else dfft_create_plan(&m_dfft_plan_forward, 3, gdim, embed, NULL, pdim, pidx, row_m, 0, 1, m_exec_conf->getMPICommunicator(), (int *) h_cart_ranks.data); dfft_create_plan(&m_dfft_plan_inverse, 3, gdim, NULL, embed, pdim, pidx, row_m, 0, 1, m_exec_conf->getMPICommunicator(), (int *) h_cart_ranks.data); #endif } #endif // ENABLE_MPI if (m_local_fft) { cufftPlan3d(&m_cufft_plan, m_mesh_points.z, m_mesh_points.y, m_mesh_points.x, CUFFT_C2C); } unsigned int n_particle_bins = m_grid_dim.x*m_grid_dim.y*m_grid_dim.z; m_bin_idx = Index2D(n_particle_bins,m_cell_size); m_scratch_idx = Index2D(n_particle_bins,(2*m_radius+1)*(2*m_radius+1)*(2*m_radius+1)); // allocate mesh and transformed mesh GlobalArray<cufftComplex> mesh(m_n_cells,m_exec_conf); m_mesh.swap(mesh); GlobalArray<cufftComplex> fourier_mesh(m_n_inner_cells, m_exec_conf); m_fourier_mesh.swap(fourier_mesh); GlobalArray<cufftComplex> fourier_mesh_G(m_n_inner_cells, m_exec_conf); m_fourier_mesh_G.swap(fourier_mesh_G); GlobalArray<cufftComplex> inv_fourier_mesh(m_n_cells, m_exec_conf); m_inv_fourier_mesh.swap(inv_fourier_mesh); GlobalArray<Scalar4> particle_bins(m_bin_idx.getNumElements(), m_exec_conf); m_particle_bins.swap(particle_bins); GlobalArray<unsigned int> n_cell(m_bin_idx.getW(), m_exec_conf); m_n_cell.swap(n_cell); GPUFlags<unsigned int> cell_overflowed(m_exec_conf); m_cell_overflowed.swap(cell_overflowed); m_cell_overflowed.resetFlags(0); // allocate scratch space for density reduction GlobalArray<Scalar> mesh_scratch(m_scratch_idx.getNumElements(), m_exec_conf); m_mesh_scratch.swap(mesh_scratch); } //! Assignment of particles to mesh using three-point scheme (triangular shaped cloud) /*! This is a second order accurate scheme with continuous value and continuous derivative */ void OrderParameterMeshGPU::assignParticles() { if (m_prof) m_prof->push(m_exec_conf, "assign"); ArrayHandle<Scalar4> d_postype(m_pdata->getPositions(), access_location::device, access_mode::read); ArrayHandle<cufftComplex> d_mesh(m_mesh, access_location::device, access_mode::overwrite); ArrayHandle<Scalar> d_mode(m_mode, access_location::device, access_mode::read); ArrayHandle<unsigned int> d_n_cell(m_n_cell, access_location::device, access_mode::overwrite); bool cont = true; while (cont) { cudaMemset(d_n_cell.data,0,sizeof(unsigned int)*m_n_cell.getNumElements()); { ArrayHandle<Scalar4> d_particle_bins(m_particle_bins, access_location::device, access_mode::overwrite); gpu_bin_particles(m_pdata->getN(), d_postype.data, d_particle_bins.data, d_n_cell.data, m_cell_overflowed.getDeviceFlags(), m_bin_idx, m_mesh_points, m_n_ghost_cells, d_mode.data, m_pdata->getBox()); if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); } unsigned int flags = m_cell_overflowed.readFlags(); if (flags) { // reallocate particle bins array m_cell_size = flags; m_bin_idx = Index2D(m_bin_idx.getW(),m_cell_size); GlobalArray<Scalar4> particle_bins(m_bin_idx.getNumElements(),m_exec_conf); m_particle_bins.swap(particle_bins); m_cell_overflowed.resetFlags(0); } else { cont = false; } // assign particles to mesh ArrayHandle<Scalar4> d_particle_bins(m_particle_bins, access_location::device, access_mode::read); ArrayHandle<Scalar> d_mesh_scratch(m_mesh_scratch, access_location::device, access_mode::overwrite); gpu_assign_binned_particles_to_mesh(m_mesh_points, m_n_ghost_cells, m_grid_dim, d_particle_bins.data, d_mesh_scratch.data, m_bin_idx, m_scratch_idx, d_n_cell.data, d_mesh.data); if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); } // reduce squares of mode amplitude m_mode_sq = gpu_compute_mode_sq(m_pdata->getN(), d_postype.data, d_mode.data, m_exec_conf->getCachedAllocator()); #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition()) { // reduce sum MPI_Allreduce(MPI_IN_PLACE, &m_mode_sq, 1, MPI_HOOMD_SCALAR, MPI_SUM, m_exec_conf->getMPICommunicator()); } #endif if (m_prof) m_prof->pop(m_exec_conf); } void OrderParameterMeshGPU::updateMeshes() { if (m_local_fft) { if (m_prof) m_prof->push(m_exec_conf,"FFT"); // locally transform the particle mesh ArrayHandle<cufftComplex> d_mesh(m_mesh, access_location::device, access_mode::read); ArrayHandle<cufftComplex> d_fourier_mesh(m_fourier_mesh, access_location::device, access_mode::overwrite); cufftExecC2C(m_cufft_plan, d_mesh.data, d_fourier_mesh.data, CUFFT_FORWARD); if (m_prof) m_prof->pop(m_exec_conf); } #ifdef ENABLE_MPI else { // update inner cells of particle mesh if (m_prof) m_prof->push(m_exec_conf,"ghost cell update"); m_exec_conf->msg->notice(8) << "cv.mesh: Ghost cell update" << std::endl; m_gpu_grid_comm_forward->communicate(m_mesh); if (m_prof) m_prof->pop(m_exec_conf); // perform a distributed FFT m_exec_conf->msg->notice(8) << "cv.mesh: Distributed FFT mesh" << std::endl; if (m_prof) m_prof->push(m_exec_conf,"FFT"); #ifndef USE_HOST_DFFT ArrayHandle<cufftComplex> d_mesh(m_mesh, access_location::device, access_mode::read); ArrayHandle<cufftComplex> d_fourier_mesh(m_fourier_mesh, access_location::device, access_mode::overwrite); if (m_exec_conf->isCUDAErrorCheckingEnabled()) dfft_cuda_check_errors(&m_dfft_plan_forward, 1); else dfft_cuda_check_errors(&m_dfft_plan_forward, 0); dfft_cuda_execute(d_mesh.data+m_ghost_offset, d_fourier_mesh.data, 0, &m_dfft_plan_forward); #else ArrayHandle<cufftComplex> h_mesh(m_mesh, access_location::host, access_mode::read); ArrayHandle<cufftComplex> h_fourier_mesh(m_fourier_mesh, access_location::host, access_mode::overwrite); dfft_execute((cpx_t *)(h_mesh.data+m_ghost_offset), (cpx_t *)h_fourier_mesh.data, 0,m_dfft_plan_forward); #endif if (m_prof) m_prof->pop(m_exec_conf); } #endif if (m_prof) m_prof->push(m_exec_conf,"update"); { ArrayHandle<cufftComplex> d_fourier_mesh(m_fourier_mesh, access_location::device, access_mode::readwrite); ArrayHandle<cufftComplex> d_fourier_mesh_G(m_fourier_mesh_G, access_location::device, access_mode::overwrite); ArrayHandle<Scalar> d_interpolation_f(m_interpolation_f, access_location::device, access_mode::read); ArrayHandle<Scalar3> d_k(m_k, access_location::device, access_mode::read); gpu_update_meshes(m_n_inner_cells, d_fourier_mesh.data, d_fourier_mesh_G.data, d_interpolation_f.data, m_mode_sq, d_k.data, m_pdata->getNGlobal()); if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); } if (m_prof) m_prof->pop(m_exec_conf); if (m_local_fft) { if (m_prof) m_prof->push(m_exec_conf, "FFT"); // do local inverse transform of force mesh ArrayHandle<cufftComplex> d_fourier_mesh_G(m_fourier_mesh_G, access_location::device, access_mode::read); ArrayHandle<cufftComplex> d_inv_fourier_mesh(m_inv_fourier_mesh, access_location::device, access_mode::overwrite); cufftExecC2C(m_cufft_plan, d_fourier_mesh_G.data, d_inv_fourier_mesh.data, CUFFT_INVERSE); if (m_prof) m_prof->pop(m_exec_conf); } #ifdef ENABLE_MPI else { if (m_prof) m_prof->push(m_exec_conf, "FFT"); // Distributed inverse transform of force mesh m_exec_conf->msg->notice(8) << "cv.mesh: Distributed iFFT" << std::endl; #ifndef USE_HOST_DFFT ArrayHandle<cufftComplex> d_fourier_mesh_G(m_fourier_mesh_G, access_location::device, access_mode::read); ArrayHandle<cufftComplex> d_inv_fourier_mesh(m_inv_fourier_mesh, access_location::device, access_mode::overwrite); if (m_exec_conf->isCUDAErrorCheckingEnabled()) dfft_cuda_check_errors(&m_dfft_plan_inverse, 1); else dfft_cuda_check_errors(&m_dfft_plan_inverse, 0); dfft_cuda_execute(d_fourier_mesh_G.data, d_inv_fourier_mesh.data+m_ghost_offset, 1, &m_dfft_plan_inverse); #else ArrayHandle<cufftComplex> h_fourier_mesh_G(m_fourier_mesh_G, access_location::host, access_mode::read); ArrayHandle<cufftComplex> h_inv_fourier_mesh(m_inv_fourier_mesh, access_location::host, access_mode::overwrite); dfft_execute((cpx_t *)h_fourier_mesh_G.data, (cpx_t *)h_inv_fourier_mesh.data+m_ghost_offset, 1, m_dfft_plan_inverse); #endif if (m_prof) m_prof->pop(m_exec_conf); } #endif #ifdef ENABLE_MPI if (! m_local_fft) { // update outer cells of inverse Fourier mesh using ghost cells from neighboring processors if (m_prof) m_prof->push("ghost cell update"); m_exec_conf->msg->notice(8) << "cv.mesh: Ghost cell update" << std::endl; m_gpu_grid_comm_reverse->communicate(m_inv_fourier_mesh); if (m_prof) m_prof->pop(); } #endif } void OrderParameterMeshGPU::interpolateForces() { if (m_prof) m_prof->push(m_exec_conf,"forces"); ArrayHandle<Scalar4> d_postype(m_pdata->getPositions(), access_location::device, access_mode::read); ArrayHandle<cufftComplex> d_inv_fourier_mesh(m_inv_fourier_mesh, access_location::device, access_mode::read); ArrayHandle<Scalar> d_mode(m_mode, access_location::device, access_mode::read); ArrayHandle<Scalar4> d_force(m_force, access_location::device, access_mode::overwrite); gpu_compute_forces(m_pdata->getN(), d_postype.data, d_force.data, m_bias, d_inv_fourier_mesh.data, m_grid_dim, m_n_ghost_cells, d_mode.data, m_pdata->getBox(), m_pdata->getGlobalBox(), m_pdata->getNGlobal(), 1.0); if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); if (m_prof) m_prof->pop(m_exec_conf); } void OrderParameterMeshGPU::computeVirial() { if (m_prof) m_prof->push(m_exec_conf,"virial"); ArrayHandle<cufftComplex> d_fourier_mesh(m_fourier_mesh, access_location::device, access_mode::read); ArrayHandle<cufftComplex> d_fourier_mesh_G(m_fourier_mesh_G, access_location::device, access_mode::read); ArrayHandle<Scalar3> d_k(m_k, access_location::device, access_mode::read); ArrayHandle<Scalar> d_virial_mesh(m_virial_mesh, access_location::device, access_mode::overwrite); bool exclude_dc = true; #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition()) { uint3 my_pos = m_pdata->getDomainDecomposition()->getGridPos(); exclude_dc = !my_pos.x && !my_pos.y && !my_pos.z; } #endif ArrayHandle<Scalar> d_table_D(m_table_d, access_location::device, access_mode::read); gpu_compute_mesh_virial(m_n_inner_cells, d_fourier_mesh.data, d_fourier_mesh_G.data, d_virial_mesh.data, d_k.data, exclude_dc, m_k_min, m_k_max, m_delta_k, d_table_D.data, m_use_table, m_pdata->getNGlobal(), 1.0); if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); { ArrayHandle<Scalar> d_sum_virial(m_sum_virial, access_location::device, access_mode::overwrite); ArrayHandle<Scalar> d_sum_virial_partial(m_sum_virial_partial, access_location::device, access_mode::overwrite); gpu_compute_virial(m_n_inner_cells, d_sum_virial_partial.data, d_sum_virial.data, d_virial_mesh.data, m_block_size); if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); } ArrayHandle<Scalar> h_sum_virial(m_sum_virial, access_location::host, access_mode::read); for (unsigned int i = 0; i<6; ++i) m_external_virial[i] = m_bias*h_sum_virial.data[i]; if (m_prof) m_prof->pop(m_exec_conf); } Scalar OrderParameterMeshGPU::computeCV() { if (m_prof) m_prof->push(m_exec_conf,"sum"); ArrayHandle<cufftComplex> d_fourier_mesh(m_fourier_mesh, access_location::device, access_mode::read); ArrayHandle<cufftComplex> d_fourier_mesh_G(m_fourier_mesh_G, access_location::device, access_mode::read); ArrayHandle<Scalar> d_interpolation_f(m_interpolation_f, access_location::device, access_mode::read); ArrayHandle<Scalar> d_sum_partial(m_sum_partial, access_location::device, access_mode::overwrite); bool exclude_dc = true; #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition()) { uint3 my_pos = m_pdata->getDomainDecomposition()->getGridPos(); exclude_dc = !my_pos.x && !my_pos.y && !my_pos.z; } #endif gpu_compute_cv(m_n_inner_cells, d_sum_partial.data, m_sum.getDeviceFlags(), d_fourier_mesh.data, d_fourier_mesh_G.data, m_block_size, m_mesh_points, d_interpolation_f.data, m_mode_sq, m_pdata->getNGlobal(), exclude_dc); if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); Scalar sum = m_sum.readFlags()*Scalar(1.0/2.0); #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition()) { // reduce sum MPI_Allreduce(MPI_IN_PLACE, &sum, 1, MPI_HOOMD_SCALAR, MPI_SUM, m_exec_conf->getMPICommunicator()); } #endif if (m_prof) m_prof->pop(m_exec_conf); return sum; } void OrderParameterMeshGPU::computeQmax(unsigned int timestep) { // compute Fourier grid getCurrentValue(timestep); if (timestep && m_q_max_last_computed == timestep) return; if (m_prof) m_prof->push("max q"); m_q_max_last_computed = timestep; ArrayHandle<cufftComplex> d_fourier_mesh(m_fourier_mesh, access_location::device, access_mode::read); ArrayHandle<Scalar3> d_k(m_k, access_location::device, access_mode::read); ArrayHandle<Scalar4> d_max_partial(m_max_partial, access_location::device, access_mode::overwrite); gpu_compute_q_max(m_n_inner_cells, d_max_partial.data, m_gpu_q_max.getDeviceFlags(), d_k.data, d_fourier_mesh.data, m_block_size); if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); Scalar4 q_max = m_gpu_q_max.readFlags(); #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition()) { // all processes send their results to all other processes // and then they determine the maximum wave vector Scalar4 *all_q_max = new Scalar4[m_exec_conf->getNRanks()]; MPI_Allgather(&q_max, sizeof(Scalar4), MPI_BYTE, all_q_max, sizeof(Scalar4), MPI_BYTE, m_exec_conf->getMPICommunicator()); for (unsigned int i = 0; i < m_exec_conf->getNRanks(); ++i) { if (all_q_max[i].w > q_max.w) { q_max = all_q_max[i]; } } delete[] all_q_max; } #endif if (m_prof) m_prof->pop(); m_q_max = make_scalar3(q_max.x,q_max.y,q_max.z); m_sq_max = q_max.w; // normalize with 1/V unsigned int n_global = m_pdata->getNGlobal(); m_sq_max *= (Scalar)n_global; } void export_OrderParameterMeshGPU(py::module& m) { py::class_<OrderParameterMeshGPU, std::shared_ptr<OrderParameterMeshGPU> >(m, "OrderParameterMeshGPU", py::base<OrderParameterMesh>()) .def(py::init< std::shared_ptr<SystemDefinition>, const unsigned int, const unsigned int, const unsigned int, const std::vector<Scalar>, const std::vector<int3> >()); } #endif // ENABLE_CUDA <file_sep>/*! \file SteinhardtQl.cc \brief Implements the Steinhardt Ql order parameter */ #include "SteinhardtQl.h" #include "spherical_harmonics.hpp" #include <cmath> namespace py = pybind11; SteinhardtQl::SteinhardtQl(std::shared_ptr<SystemDefinition> sysdef, Scalar rcut, Scalar ron, unsigned int lmax, std::shared_ptr<NeighborList> nlist, unsigned int type, const std::vector<Scalar>& Ql_ref, const std::string& log_suffix) : CollectiveVariable(sysdef,"steinhardt"+log_suffix), m_rcutsq(rcut*rcut), m_ronsq(ron*ron), m_lmax(lmax), m_nlist(nlist), m_type(type), m_cv_last_updated(0), m_have_computed(false), m_value(0.0) { m_prof_name = "steinhardt_Ql"+log_suffix; m_Ql = std::vector<Scalar>(m_lmax+1, Scalar(0.0)); if (Ql_ref.size() != m_lmax+1) { m_exec_conf->msg->error() << "List of reference Qlm needs to be exactly of length lmax = " << m_lmax+1 << std::endl; throw std::runtime_error("Error setting up Steinhardt CV"); } m_Ql_ref.resize(Ql_ref.size()); std::copy(Ql_ref.begin(), Ql_ref.end(), m_Ql_ref.begin()); } inline Scalar fSmooth(Scalar r_onsq, Scalar r_cutsq, Scalar rsq) { if (rsq <= r_onsq) return 1.0; if (rsq > r_cutsq) return 0.0; Scalar r = sqrt(rsq); Scalar r_on = sqrt(r_onsq); Scalar r_cut = sqrt(r_cutsq); return Scalar(0.5)*(cos(M_PI*(r-r_on)/(r_cut-r_on))+1); } inline Scalar fprimeSmooth_divr(Scalar r_onsq, Scalar r_cutsq, Scalar rsq) { if (rsq <= r_onsq || rsq > r_cutsq) return 0.0; Scalar r = sqrt(rsq); Scalar r_on = sqrt(r_onsq); Scalar r_cut = sqrt(r_cutsq); return -Scalar(0.5*M_PI)/r/(r_cut-r_on)*sin(M_PI*(r-r_on)/(r_cut-r_on)); } void SteinhardtQl::computeCV(unsigned int timestep) { if (m_cv_last_updated == timestep && m_have_computed) return; // start by updating the neighborlist m_nlist->compute(timestep); // start the profile for this compute if (m_prof) m_prof->push(m_prof_name); if (m_prof) m_prof->push("CV"); // depending on the neighborlist settings, we can take advantage of newton's third law // to reduce computations at the cost of memory access complexity: set that flag now bool third_law = m_nlist->getStorageMode() == NeighborList::half; // access the neighbor list, particle data, and system box ArrayHandle<unsigned int> h_n_neigh(m_nlist->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist(m_nlist->getNListArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_head_list(m_nlist->getHeadList(), access_location::host, access_mode::read); ArrayHandle<Scalar4> h_pos(m_pdata->getPositions(), access_location::host, access_mode::read); const BoxDim& box = m_pdata->getBox(); unsigned int sph_count = (m_lmax+1)*(m_lmax+1); std::vector<std::complex<Scalar> > Ylm_pp(sph_count,std::complex<Scalar>(0.0,0.0)); m_Qlm.resize(sph_count); std::fill(m_Qlm.begin(), m_Qlm.end(), std::complex<Scalar>(0.0,0.0)); // for each particle unsigned int N = m_pdata->getN(); for (int i = 0; i < (int)N; i++) { // access the particle's position and type (MEM TRANSFER: 4 scalars) Scalar3 pi = make_scalar3(h_pos.data[i].x, h_pos.data[i].y, h_pos.data[i].z); unsigned int typei = __scalar_as_int(h_pos.data[i].w); // sanity check assert(typei < m_pdata->getNTypes()); // only compute for a single particle type if (typei != m_type) continue; // loop over all of the neighbors of this particle const unsigned int myHead = h_head_list.data[i]; const unsigned int size = (unsigned int)h_n_neigh.data[i]; for (unsigned int k = 0; k < size; k++) { // access the index of this neighbor (MEM TRANSFER: 1 scalar) unsigned int j = h_nlist.data[myHead + k]; assert(j < m_pdata->getN() + m_pdata->getNGhosts()); // calculate dr_ji (MEM TRANSFER: 3 scalars / FLOPS: 3) Scalar3 pj = make_scalar3(h_pos.data[j].x, h_pos.data[j].y, h_pos.data[j].z); Scalar3 dx = pi - pj; // access the type of the neighbor particle (MEM TRANSFER: 1 scalar) unsigned int typej = __scalar_as_int(h_pos.data[j].w); assert(typej < m_pdata->getNTypes()); if (typej != m_type) continue; // apply periodic boundary conditions dx = box.minImage(dx); // calculate r_ij squared (FLOPS: 5) Scalar rsq = dot(dx, dx); if (rsq <= m_rcutsq) { Scalar f = fSmooth(m_ronsq, m_rcutsq, rsq); // compute theta, phi Scalar theta = acos(dx.z/sqrt(rsq)); Scalar phi = atan2(dx.y, dx.x); bool negative_m = true; // note switching theta and phi due to diffferent convention fsph::evaluate_SPH<Scalar>(&Ylm_pp.front(), m_lmax, &theta, &phi, 1, negative_m); int n = 0; for (int l = 0; l <= (int)m_lmax; ++l) { for (int p = 0; p < 2*l+1; ++p) { int m = (p <= l) ? p : (l-p); int phase = (m > 0 && m % 2) ? -1 : 1; // Condon-Shortley m_Qlm[n] += std::complex<Scalar>(phase)*Ylm_pp[n]*f; n++; } } } } } // need to reduce Qlm in MPI here // ... unsigned int Nglobal = m_pdata->getNGlobal(); unsigned int nc = 1; // for now unsigned int n = 0; for (int l = 0; l <= (int)m_lmax; ++l) { m_Ql[l] = Scalar(0.0); for (int p=0; p < 2*l+1; ++p) { if (third_law) { if (l % 2 == 0) m_Qlm[n] *= 2; // assume even parity else m_Qlm[n] = std::complex<Scalar>(0.0,0.0); } Scalar Qlm_sq = (std::conj(m_Qlm[n])*m_Qlm[n]).real(); Qlm_sq *= Scalar(4.0*M_PI/(2*l+1))/(Nglobal*Nglobal*nc*nc); m_Ql[l] += Qlm_sq; n++; } } // compute collective variable as normalizd dot product m_value = Scalar(0.0); for (unsigned int l = 0; l <= m_lmax; ++l) { m_value += m_Ql_ref[l]*m_Ql[l]; } m_have_computed = true; m_cv_last_updated = timestep; if (m_prof) m_prof->pop(); if (m_prof) m_prof->pop(); } void SteinhardtQl::computeBiasForces(unsigned int timestep) { // start by updating the neighborlist m_nlist->compute(timestep); // start the profile for this compute if (m_prof) m_prof->push(m_prof_name); if (m_prof) m_prof->push("Force"); // depending on the neighborlist settings, we can take advantage of newton's third law // to reduce computations at the cost of memory access complexity: set that flag now bool third_law = m_nlist->getStorageMode() == NeighborList::half; // access the force array ArrayHandle<Scalar4> h_force(m_force, access_location::host, access_mode::overwrite); // access the neighbor list, particle data, and system box ArrayHandle<unsigned int> h_n_neigh(m_nlist->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist(m_nlist->getNListArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_head_list(m_nlist->getHeadList(), access_location::host, access_mode::read); ArrayHandle<Scalar4> h_pos(m_pdata->getPositions(), access_location::host, access_mode::read); const BoxDim& box = m_pdata->getBox(); unsigned int sph_count = (m_lmax+1)*(m_lmax+1); //l = 0..lmax std::vector<std::complex<Scalar> > Ylm_pp(sph_count,std::complex<Scalar>(0.0,0.0)); unsigned int Nglobal = m_pdata->getNGlobal(); unsigned int nc = 1; // for now // reset force memset(h_force.data, 0, sizeof(Scalar4)*m_force.getNumElements()); // for each particle unsigned int N = m_pdata->getN(); for (int i = 0; i < (int)N; i++) { // access the particle's position and type (MEM TRANSFER: 4 scalars) Scalar3 pi = make_scalar3(h_pos.data[i].x, h_pos.data[i].y, h_pos.data[i].z); unsigned int typei = __scalar_as_int(h_pos.data[i].w); // sanity check assert(typei < m_pdata->getNTypes()); // only compute for a single particle type if (typei != m_type) continue; // loop over all of the neighbors of this particle const unsigned int myHead = h_head_list.data[i]; const unsigned int size = (unsigned int)h_n_neigh.data[i]; for (unsigned int k = 0; k < size; k++) { // access the index of this neighbor (MEM TRANSFER: 1 scalar) unsigned int j = h_nlist.data[myHead + k]; assert(j < m_pdata->getN() + m_pdata->getNGhosts()); // calculate dr_ji (MEM TRANSFER: 3 scalars / FLOPS: 3) Scalar3 pj = make_scalar3(h_pos.data[j].x, h_pos.data[j].y, h_pos.data[j].z); Scalar3 dx = pi - pj; // access the type of the neighbor particle (MEM TRANSFER: 1 scalar) unsigned int typej = __scalar_as_int(h_pos.data[j].w); assert(typej < m_pdata->getNTypes()); if (typej != m_type) continue; // apply periodic boundary conditions dx = box.minImage(dx); // calculate r_ij squared (FLOPS: 5) Scalar rsq = dot(dx, dx); vec3<Scalar> force(0.0,0.0,0.0); if (rsq <= m_rcutsq) { // compute theta, phi std::complex<Scalar> r(sqrt(rsq)); Scalar theta = acos(dx.z/r.real()); Scalar phi = atan2(dx.y, dx.x); vec3<std::complex<Scalar> > e_theta = vec3<std::complex<Scalar> >(cos(theta)*cos(phi),cos(theta)*sin(phi),-sin(theta)); vec3<std::complex<Scalar> > e_phi = vec3<std::complex<Scalar> >(-sin(phi),cos(phi),0.0); bool negative_m = true; // note switching theta and phi due to diffferent convention fsph::evaluate_SPH<Scalar>(&Ylm_pp.front(), m_lmax, &theta, &phi, 1, negative_m); std::complex<Scalar> fprime_divr(fprimeSmooth_divr(m_ronsq,m_rcutsq, rsq)); std::complex<Scalar> f(fSmooth(m_ronsq, m_rcutsq, rsq)); int n = 0; for (int l = 0; l <= (int)m_lmax; ++l) { vec3<Scalar> del_Ql_i(0.0,0.0,0.0); for (int p = 0; p < 2*l+1; ++p) { int m = (p <= l) ? p : (l-p); int phase = (m > 0 && m % 2) ? -1 : 1; // Condon-Shortley phase, for derivative formula std::complex<Scalar> Ylm = std::complex<Scalar>(phase)*Ylm_pp[n]; std::complex<Scalar> dYlm_dtheta = std::complex<Scalar>(m/tan(theta))*Ylm; if (m < l) { unsigned int m_plus_one = (m < 0) ? (m == -1 ? n-p : n-1) : (n+1); int phase_plus_one = (m + 1 > 0 && (m+1) %2 ) ? -1 : 1; dYlm_dtheta += std::complex<Scalar>(phase_plus_one*sqrt((l-m)*(l+m+1)))*std::exp(std::complex<Scalar>(0,-phi))*Ylm_pp[m_plus_one]; } std::complex<Scalar> dYlm_dphi = std::complex<Scalar>(0,m)*Ylm; vec3<std::complex<Scalar> > del_Qlm = vec3<std::complex<Scalar> >(dx)*fprime_divr*Ylm + f/r*e_theta*dYlm_dtheta + f*e_phi/(r*std::complex<Scalar>(sin(theta)))*dYlm_dphi; del_Qlm *= std::conj(m_Qlm[n]); del_Ql_i += Scalar(2.0)*vec3<Scalar>(del_Qlm.x.real(),del_Qlm.y.real(), del_Qlm.z.real()); n++; } del_Ql_i *= Scalar(4.0*M_PI/(2*l+1))/(Nglobal*Nglobal)/(nc*nc); force -= m_bias*del_Ql_i*m_Ql_ref[l]; } } h_force.data[i].x += force.x; h_force.data[i].y += force.y; h_force.data[i].z += force.z; if (third_law && j < N) { h_force.data[j].x -= force.x; h_force.data[j].y -= force.y; h_force.data[j].z -= force.z; } } } if (m_prof) m_prof->pop(); if (m_prof) m_prof->pop(); } void export_SteinhardtQl(py::module& m) { py::class_<SteinhardtQl, std::shared_ptr<SteinhardtQl> > steinhardt(m, "SteinhardtQl", py::base<CollectiveVariable>() ); steinhardt.def(py::init< std::shared_ptr<SystemDefinition>, Scalar, Scalar, unsigned int, std::shared_ptr<NeighborList>, unsigned int, const std::vector<Scalar>&, const std::string& > ()) ; } <file_sep>/*! \file CollectiveVariable.cc \brief Partially implements the CollectiveVariable class */ #include "CollectiveVariable.h" namespace py = pybind11; CollectiveVariable::CollectiveVariable(std::shared_ptr<SystemDefinition> sysdef, const std::string& name) : ForceCompute(sysdef), m_bias(0.0), m_cv_name(name), m_umbrella(no_umbrella), m_cv0(0.0), m_kappa(1.0), m_width_flat(0.0), m_scale(1.0) { } void CollectiveVariable::computeForces(unsigned int timestep) { if (m_umbrella != no_umbrella) { // add to existing bias Scalar val = getCurrentValue(timestep); if ((val < m_cv0 + m_width_flat/Scalar(2.0)) && (val > m_cv0 - m_width_flat/Scalar(2.0))) { // setBiasFactor(0.0); // leave bias as it is } else { Scalar delta(0.0); if (val > m_cv0) delta = val - m_cv0 - m_width_flat/Scalar(2.0); else delta = val - m_cv0 + m_width_flat/Scalar(2.0); if (m_umbrella == linear) { setBiasFactor(m_bias+m_scale*Scalar(1.0)); } else if (m_umbrella == harmonic) { setBiasFactor(m_bias+m_kappa*delta); } else if (m_umbrella == wall) { setBiasFactor(m_bias+m_scale*Scalar(12.0)*pow(delta/m_kappa,Scalar(11.0))/m_kappa); } else if (m_umbrella == gaussian) { setBiasFactor(m_bias-m_scale*(val-m_cv0)*exp(-(val-m_cv0)*(val-m_cv0)/m_kappa/m_kappa/Scalar(2.0))); } } } computeBiasForces(timestep); // reset bias factor setBiasFactor(0.0); } Scalar CollectiveVariable::getUmbrellaPotential(unsigned int timestep) { if (m_umbrella != no_umbrella) { Scalar val = getCurrentValue(timestep); if ((val < m_cv0 + m_width_flat/Scalar(2.0)) && (val > m_cv0 - m_width_flat/Scalar(2.0))) { return Scalar(0.0); } else { Scalar delta(0.0); if (val > m_cv0) delta = val - m_cv0 - m_width_flat/Scalar(2.0); else if (val < m_cv0) delta = val - m_cv0 + m_width_flat/Scalar(2.0); if (m_umbrella == linear) { return m_scale*delta; } else if (m_umbrella == harmonic) { return Scalar(1.0/2.0)*delta*delta*m_kappa; } else if (m_umbrella == wall) { return m_scale*pow(delta/m_kappa,Scalar(12.0)); } else if (m_umbrella == gaussian) { return m_scale*exp(-(val-m_cv0)*(val-m_cv0)/m_kappa/m_kappa/Scalar(2.0))-m_scale; } } } return Scalar(0.0); } void export_CollectiveVariable(py::module& m) { py::class_<CollectiveVariable, std::shared_ptr<CollectiveVariable> > collective_variable(m, "CollectiveVariable", py::base<ForceCompute>() ); collective_variable.def(py::init< std::shared_ptr<SystemDefinition>, const std::string& > ()) .def("getCurrentValue", &CollectiveVariable::getCurrentValue) .def("setUmbrella", &CollectiveVariable::setUmbrella) .def("setKappa", &CollectiveVariable::setKappa) .def("setWidthFlat", &CollectiveVariable::setWidthFlat) .def("setMinimum", &CollectiveVariable::setMinimum) .def("setScale", &CollectiveVariable::setScale) .def("requiresNetForce", &CollectiveVariable::requiresNetForce) ; py::enum_<CollectiveVariable::umbrella_Enum>(collective_variable,"umbrella") .value("no_umbrella", CollectiveVariable::no_umbrella) .value("linear", CollectiveVariable::linear) .value("harmonic", CollectiveVariable::harmonic) .value("wall", CollectiveVariable::wall) .value("gaussian", CollectiveVariable::gaussian) .export_values() ; } <file_sep>/*! \file IntegratorMetaDynamics.cc \brief Implements the IntegratorMetaDynamics class */ #include "IntegratorMetaDynamics.h" #include <stdio.h> #include <iomanip> #include <sstream> #include <sys/stat.h> namespace py = pybind11; #include <hoomd/extern/Eigen/Eigen/Dense> using namespace std; #ifdef ENABLE_CUDA #include "IntegratorMetaDynamics.cuh" #endif //! Constructor IntegratorMetaDynamics::IntegratorMetaDynamics(std::shared_ptr<SystemDefinition> sysdef, Scalar deltaT, Scalar W, Scalar T_shift, Scalar T, unsigned int stride, bool add_bias, const std::string& filename, bool overwrite, const Enum mode) : IntegratorTwoStep(sysdef, deltaT), m_W(W), m_T_shift(T_shift), m_stride(stride), m_num_gaussians(0), m_curr_bias_potential(0.0), m_is_initialized(false), m_filename(filename), m_overwrite(overwrite), m_is_appending(false), m_delimiter("\t"), m_use_grid(false), m_add_bias(add_bias), m_restart_filename(""), m_grid_fname1(""), m_grid_fname2(""), m_grid_period(0), m_cur_file(0), m_sigma_g(1.0), m_adaptive(false), m_temp(T), m_mode(mode), m_multiple_walkers(false), m_curr_reweight(1.0) { assert(m_T_shift>0); assert(m_W > 0); m_log_names.push_back("bias"); m_log_names.push_back("det_sigma"); m_log_names.push_back("weight"); #ifdef ENABLE_MPI // create partition communicator MPI_Comm_split(MPI_COMM_WORLD, (m_exec_conf->getRank() == 0) ? 0 : MPI_UNDEFINED, m_exec_conf->getPartition(), &m_partition_comm); #endif } void IntegratorMetaDynamics::openOutputFile() { struct stat buffer; bool file_exists = stat(m_filename.c_str(), &buffer) == 0; if (file_exists && !m_overwrite) { m_exec_conf->msg->notice(3) << "integrate.mode_metadynamics: Appending log to existing file \"" << m_filename << "\"" << endl; m_file.open(m_filename.c_str(), ios_base::in | ios_base::out | ios_base::ate); m_is_appending = true; } else { m_exec_conf->msg->notice(3) << "integrate.mode_metadynamics: Creating new log in file \"" << m_filename << "\"" << endl; m_file.open(m_filename.c_str(), ios_base::out); m_is_appending = false; } if (!m_file.good()) { m_exec_conf->msg->error() << "integrate.mode_metadynamics: Error opening log file " << m_filename << endl; throw runtime_error("Error initializing IntegratorMetadynamics"); } } void IntegratorMetaDynamics::writeFileHeader() { assert(m_variables.size()); assert(m_file); m_file << "timestep" << m_delimiter << "W" << m_delimiter; std::vector<CollectiveVariableItem>::iterator it,itj; for (it = m_variables.begin(); it != m_variables.end(); ++it) { m_file << it->m_cv->getName(); for (itj = m_variables.begin(); itj != m_variables.end(); ++itj) m_file << m_delimiter << "sigma_" << it->m_cv->getName() << "_" << it -m_variables.begin() << "_" << itj - m_variables.begin(); if (it != m_variables.end()) m_file << m_delimiter; } m_file << endl; } void IntegratorMetaDynamics::prepRun(unsigned int timestep) { #ifdef ENABLE_MPI bool is_root = true; if (m_pdata->getDomainDecomposition()) is_root = m_exec_conf->isRoot(); if (is_root) #endif { // Set up file output if (! m_is_initialized && m_filename != "") { openOutputFile(); if (! m_is_appending) writeFileHeader(); } // Set up colllective variables if (! m_is_initialized) { m_cv_values.resize(m_variables.size()); std::vector< std::vector<Scalar> >::iterator it; for (it = m_cv_values.begin(); it != m_cv_values.end(); ++it) it->clear(); // initialize GPU mirror values for collective variable data GPUArray<Scalar> cv_min(m_variables.size(), m_exec_conf); m_cv_min.swap(cv_min); GPUArray<Scalar> cv_max(m_variables.size(), m_exec_conf); m_cv_max.swap(cv_max); GPUArray<Scalar> current_val(m_variables.size(), m_exec_conf); m_current_val.swap(current_val); GPUArray<unsigned int> lengths(m_variables.size(), m_exec_conf); m_lengths.swap(lengths); GPUArray<Scalar> sigma_inv(m_variables.size()*m_variables.size(), m_exec_conf); m_sigma_inv.swap(sigma_inv); ArrayHandle<Scalar> h_cv_min(m_cv_min, access_location::host, access_mode::overwrite); ArrayHandle<Scalar> h_cv_max(m_cv_max, access_location::host, access_mode::overwrite); ArrayHandle<unsigned int> h_lengths(m_lengths, access_location::host, access_mode::overwrite); ArrayHandle<Scalar> h_sigma_inv(m_sigma_inv, access_location::host, access_mode::overwrite); memset(h_sigma_inv.data, 0, sizeof(Scalar)*m_variables.size()*m_variables.size()); for (unsigned int cv_idx = 0; cv_idx < m_variables.size(); cv_idx++) { h_cv_min.data[cv_idx] = m_variables[cv_idx].m_cv_min; h_cv_max.data[cv_idx] = m_variables[cv_idx].m_cv_max; h_sigma_inv.data[cv_idx*m_variables.size()+cv_idx] = Scalar(1.0)/m_variables[cv_idx].m_sigma; h_lengths.data[cv_idx] = m_variables[cv_idx].m_num_points; } m_bias_potential.clear(); } // Set up grid if necessary if (! m_is_initialized && m_use_grid) { setupGrid(); if (m_restart_filename != "") { // restart from file m_exec_conf->msg->notice(2) << "integrate.mode_metadynamics: Restarting from grid file \"" << m_restart_filename << "\"" << endl; readGrid(m_restart_filename); m_restart_filename = ""; } } } // endif isRoot() m_is_initialized = true; #ifdef ENABLE_MPI if (m_comm) { // perform all necessary communication steps. This ensures // a) that particles have migrated to the correct domains // b) that forces are calculated correctly m_comm->communicate(timestep); } #endif // initial update of the potential updateBiasPotential(timestep); IntegratorTwoStep::prepRun(timestep); } void IntegratorMetaDynamics::update(unsigned int timestep) { // issue a warning if no integration methods are set if (!m_gave_warning && m_methods.size() == 0) { m_exec_conf->msg->warning() << "No integration methods are set, continuing anyways." << endl; m_gave_warning = true; } // ensure that prepRun() has been called assert(this->m_prepared); if (m_prof) m_prof->push("Integrate"); // perform the first step of the integration on all groups std::vector< std::shared_ptr<IntegrationMethodTwoStep> >::iterator method; for (method = m_methods.begin(); method != m_methods.end(); ++method) (*method)->integrateStepOne(timestep); if (m_prof) m_prof->pop(); #ifdef ENABLE_MPI if (m_comm) { // perform all necessary communication steps. This ensures // a) that particles have migrated to the correct domains // b) that forces are calculated correctly, if ghost atom positions are updated every time step // also updates rigid bodies after ghost updating m_comm->communicate(timestep+1); } else #endif { updateRigidBodies(timestep+1); } bool net_force_first = (m_variables.size() == 1 && m_variables[0].m_cv->requiresNetForce()); if (! net_force_first) { // check sanity for (auto it = m_variables.begin(); it != m_variables.end(); ++it) { if (it->m_cv->requiresNetForce()) { throw std::runtime_error("Only one collective variable requiring the potential energy may be defined.\n"); } } } if (net_force_first) { // compute the net force on all particles #ifdef ENABLE_CUDA if (m_exec_conf->exec_mode == ExecutionConfiguration::GPU) computeNetForceGPU(timestep+1); else #endif computeNetForce(timestep+1); } // update bias potential updateBiasPotential(timestep+1); if (! net_force_first) { // compute the net force on all particles #ifdef ENABLE_CUDA if (m_exec_conf->exec_mode == ExecutionConfiguration::GPU) computeNetForceGPU(timestep+1); else #endif computeNetForce(timestep+1); } else { // compute bias forces *after* everything else m_variables[0].m_cv->compute(timestep); } if (m_prof) m_prof->push("Integrate"); // perform the second step of the integration on all groups for (method = m_methods.begin(); method != m_methods.end(); ++method) (*method)->integrateStepTwo(timestep); if (m_prof) m_prof->pop(); } void IntegratorMetaDynamics::updateBiasPotential(unsigned int timestep) { // exit early if there are no collective variables if (m_variables.size() == 0) return; // collect values of collective variables std::vector< Scalar> current_val; std::vector<CollectiveVariableItem>::iterator it; for (it = m_variables.begin(); it != m_variables.end(); ++it) { Scalar val = it->m_cv->getCurrentValue(timestep); current_val.push_back(val); } std::vector<Scalar> bias(m_variables.size(), 0.0); bool is_root = true; if (m_adaptive && (timestep % m_stride == 0)) { // compute derivatives of collective variables for (unsigned int i = 0; i < m_variables.size(); ++i) m_variables[i].m_cv->computeDerivatives(timestep); // compute instantaneous estimate of standard deviation matrix computeSigma(); } if (m_prof) m_prof->push("Metadynamics"); #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition()) is_root = m_exec_conf->isRoot(); if (is_root) #endif { if (! m_use_grid && (timestep % m_stride == 0)) { // record history of CV values every m_stride steps std::vector<CollectiveVariableItem>::iterator it; for (unsigned int i = 0; i < m_variables.size(); ++i) { m_cv_values[i].push_back(current_val[i]); } } if (m_use_grid) { // update histogram updateHistogram(current_val); if (m_add_bias && (timestep % m_stride == 0)) { // update sigma grid updateSigmaGrid(current_val); // scaling factor for well-tempered MetaD Scalar scal = Scalar(1.0); if (m_mode == mode_well_tempered) { Scalar V = interpolateGrid(current_val,false); scal = exp(-V/m_T_shift); } m_exec_conf->msg->notice(3) << "integrate.mode_metadynamics: Updating grid." << std::endl; #ifdef ENABLE_CUDA if (m_exec_conf->isCUDAEnabled()) updateGridGPU(current_val, scal); else updateGrid(current_val, scal); #else updateGrid(current_val, scal); #endif #ifdef ENABLE_MPI if (m_multiple_walkers) { // sum up increments ArrayHandle<Scalar> h_grid_delta(m_grid_delta, access_location::host, access_mode::readwrite); ArrayHandle<Scalar> h_sigma_grid_delta(m_sigma_grid_delta, access_location::host, access_mode::readwrite); ArrayHandle<unsigned int> h_grid_hist_delta(m_grid_hist_delta, access_location::host, access_mode::readwrite); ArrayHandle<unsigned int> h_grid_hist_gauss_delta(m_grid_hist_gauss_delta, access_location::host, access_mode::readwrite); MPI_Allreduce(MPI_IN_PLACE, h_grid_delta.data, m_grid_delta.getNumElements(), MPI_HOOMD_SCALAR, MPI_SUM, m_partition_comm); MPI_Allreduce(MPI_IN_PLACE, h_sigma_grid_delta.data, m_sigma_grid_delta.getNumElements(), MPI_HOOMD_SCALAR, MPI_SUM, m_partition_comm); MPI_Allreduce(MPI_IN_PLACE, h_grid_hist_delta.data,m_grid_hist_delta.getNumElements(), MPI_INT, MPI_SUM, m_partition_comm); MPI_Allreduce(MPI_IN_PLACE, h_grid_hist_gauss_delta.data,m_grid_hist_gauss_delta.getNumElements(), MPI_INT, MPI_SUM, m_partition_comm); } #endif // use deltaV and grid histogram to update estimator of unbiased CV histogram updateReweightedEstimator(current_val); { // add deltas to grid ArrayHandle<Scalar> h_grid(m_grid, access_location::host, access_mode::readwrite); ArrayHandle<Scalar> h_grid_delta(m_grid_delta, access_location::host, access_mode::readwrite); ArrayHandle<Scalar> h_sigma_grid(m_sigma_grid, access_location::host, access_mode::readwrite); ArrayHandle<Scalar> h_sigma_grid_delta(m_sigma_grid_delta, access_location::host, access_mode::readwrite); ArrayHandle<unsigned int> h_grid_hist(m_grid_hist, access_location::host, access_mode::readwrite); ArrayHandle<unsigned int> h_grid_hist_delta(m_grid_hist_delta, access_location::host, access_mode::readwrite); ArrayHandle<unsigned int> h_grid_hist_gauss(m_grid_hist_gauss, access_location::host, access_mode::readwrite); ArrayHandle<unsigned int> h_grid_hist_gauss_delta(m_grid_hist_gauss_delta, access_location::host, access_mode::readwrite); for (unsigned int i = 0; i < m_grid.getNumElements(); ++i) { h_grid.data[i] += h_grid_delta.data[i]; h_sigma_grid.data[i] += h_sigma_grid_delta.data[i]; h_grid_hist.data[i] += h_grid_hist_delta.data[i]; h_grid_hist_gauss.data[i] += h_grid_hist_gauss_delta.data[i]; h_grid_delta.data[i] = Scalar(0.0); h_sigma_grid_delta.data[i] = Scalar(0.0); h_grid_hist_delta.data[i] = 0; h_grid_hist_gauss_delta.data[i] = 0; } } // end ArrayHandle scope m_num_gaussians++; } // end update // calculate partial derivatives numerically for (unsigned int cv_idx = 0; cv_idx < m_variables.size(); ++cv_idx) bias[cv_idx] = biasPotentialDerivative(cv_idx, current_val); // current bias potential m_curr_bias_potential = interpolateGrid(current_val, false); // current reweighting factor m_curr_reweight = interpolateGrid(current_val, true); } else //!m_use_grid { // update biasing weights by summing up partial derivivatives // of Gaussians deposited every m_stride steps m_curr_bias_potential = 0.0; if (m_adaptive) { m_exec_conf->msg->error() << "integrate.mode_metadynamics: Adaptive Gaussians only available in grid mode" << std::endl; throw std::runtime_error("Error in metadynamics integration."); } if (m_variables.size() != m_variables.size()) { m_exec_conf->msg->error() << "integrate.mode_metadynamics: Reweighting supported only in grid mode." << std::endl; throw std::runtime_error("Error in metadynamics integration."); } ArrayHandle<Scalar> h_sigma_inv(m_sigma_inv, access_location::host, access_mode::read); // sum up all Gaussians accumulated until now for (unsigned int gauss_idx = 0; gauss_idx < m_bias_potential.size(); ++gauss_idx) { Scalar gauss_exp = 0.0; // calculate Gaussian contribution from t'=gauss_idx*m_stride for (unsigned int i = 0; i < m_variables.size(); ++i) { Scalar vali = current_val[i]; Scalar delta_i = vali - m_cv_values[i][gauss_idx]; for (unsigned int j = 0; j < m_variables.size(); ++j) { Scalar valj = current_val[j]; Scalar delta_j = valj - m_cv_values[j][gauss_idx]; Scalar sigma_inv_ij = h_sigma_inv.data[i*m_variables.size()+j]; gauss_exp += delta_i*delta_j*Scalar(1.0/2.0)*(sigma_inv_ij*sigma_inv_ij); } } Scalar gauss = exp(-gauss_exp); // calculate partial derivatives // scaling factor for well-tempered MetaD Scalar scal = Scalar(1.0); if (m_mode == mode_well_tempered) scal = exp(-m_bias_potential[gauss_idx]/m_T_shift); for (unsigned int i = 0; i < m_variables.size(); ++i) { Scalar val_i = current_val[i]; for (unsigned int j = 0; j < m_variables.size(); ++j) { Scalar val_j = current_val[j]; Scalar sigma_inv_ij = h_sigma_inv.data[i*m_variables.size()+j]; bias[i] -= Scalar(1.0/2.0)*m_W*scal*(sigma_inv_ij*sigma_inv_ij)*(val_j - m_cv_values[j][gauss_idx])*gauss; bias[j] -= Scalar(1.0/2.0)*m_W*scal*(sigma_inv_ij*sigma_inv_ij)*(val_i - m_cv_values[i][gauss_idx])*gauss; } } m_curr_bias_potential += m_W*scal*gauss; } } // write hills information if (m_is_initialized && (timestep % m_stride == 0) && m_add_bias && m_file.is_open()) { ArrayHandle<Scalar> h_sigma_inv(m_sigma_inv, access_location::host, access_mode::read); Scalar W = m_W*exp(-m_curr_bias_potential/m_T_shift); m_file << setprecision(10) << timestep << m_delimiter; m_file << setprecision(10) << W << m_delimiter; std::vector<Scalar>::iterator cv,cvj; for (cv = current_val.begin(); cv != current_val.end(); ++cv) { unsigned int cv_index = cv - current_val.begin(); m_file << setprecision(10) << *cv << m_delimiter; // Write row of inverse sigma matrix for (cvj = current_val.begin(); cvj != current_val.end(); ++cvj) { unsigned int cv_index_j = cvj - current_val.begin(); Scalar sigma_inv_ij = h_sigma_inv.data[cv_index*m_variables.size()+cv_index_j]; m_file << setprecision(10) << sigma_inv_ij; } if (cv != current_val.end() -1) m_file << m_delimiter; } m_file << endl; } if (m_add_bias && (! m_use_grid) && (timestep % m_stride == 0)) m_bias_potential.push_back(m_curr_bias_potential); // dump grid information if required using alternating scheme if (m_grid_period && (timestep % m_grid_period == 0)) { if (m_grid_fname2 != "") { writeGrid(m_cur_file ? m_grid_fname2 : m_grid_fname1, timestep); m_cur_file = m_cur_file ? 0 : 1; } else writeGrid(m_grid_fname1, timestep); } } // endif root processor #ifdef ENABLE_MPI // broadcast bias factors if (m_pdata->getDomainDecomposition()) MPI_Bcast(&bias.front(), bias.size(), MPI_HOOMD_SCALAR, 0, m_exec_conf->getMPICommunicator()); #endif // update current bias potential derivative for every collective variable std::vector<CollectiveVariableItem>::iterator cv_item; unsigned int cv = 0; for (cv_item = m_variables.begin(); cv_item != m_variables.end(); ++cv_item) { cv_item->m_cv->setBiasFactor(bias[cv]); cv++; } if (m_prof) m_prof->pop(); } void IntegratorMetaDynamics::setupGrid() { assert(! m_is_initialized); assert(m_variables.size()); std::vector< CollectiveVariableItem >::iterator it; std::vector< unsigned int > lengths(m_variables.size()); unsigned int idx = 0; for (it = m_variables.begin(); it != m_variables.end(); ++it) { lengths[idx] = it->m_num_points; idx++; } m_grid_index.setLengths(lengths); GPUArray<Scalar> grid(m_grid_index.getNumElements(),m_exec_conf); m_grid.swap(grid); GPUArray<Scalar> grid_delta(m_grid_index.getNumElements(),m_exec_conf); m_grid_delta.swap(grid_delta); GPUArray<Scalar> grid_reweighted(m_grid_index.getNumElements(),m_exec_conf); m_grid_reweighted.swap(grid_reweighted); GPUArray<Scalar> grid_weight(m_grid_index.getNumElements(),m_exec_conf); m_grid_weight.swap(grid_weight); // reset grid ArrayHandle<Scalar> h_grid(m_grid, access_location::host, access_mode::overwrite); memset(h_grid.data, 0, sizeof(Scalar)*m_grid.getNumElements()); ArrayHandle<Scalar> h_grid_delta(m_grid_delta, access_location::host, access_mode::overwrite); memset(h_grid_delta.data, 0, sizeof(Scalar)*m_grid_delta.getNumElements()); GPUArray<Scalar> sigma_grid(m_grid_index.getNumElements(),m_exec_conf); m_sigma_grid.swap(sigma_grid); GPUArray<Scalar> sigma_grid_delta(m_grid_index.getNumElements(),m_exec_conf); m_sigma_grid_delta.swap(sigma_grid_delta); GPUArray<unsigned int> grid_hist(m_grid_index.getNumElements(),m_exec_conf); m_grid_hist.swap(grid_hist); GPUArray<unsigned int> grid_hist_delta(m_grid_index.getNumElements(),m_exec_conf); m_grid_hist_delta.swap(grid_hist_delta); GPUArray<unsigned int> grid_hist_gauss(m_grid_index.getNumElements(),m_exec_conf); m_grid_hist_gauss.swap(grid_hist_gauss); GPUArray<unsigned int> grid_hist_gauss_delta(m_grid_index.getNumElements(),m_exec_conf); m_grid_hist_gauss_delta.swap(grid_hist_gauss_delta); ArrayHandle<Scalar> h_grid_reweighted(m_grid_reweighted, access_location::host, access_mode::overwrite); memset(h_grid_reweighted.data, 0, sizeof(Scalar)*m_grid.getNumElements()); ArrayHandle<unsigned int> h_grid_hist_gauss(m_grid_hist_gauss, access_location::host, access_mode::overwrite); memset(h_grid_hist_gauss.data,0, sizeof(unsigned int)*m_grid_hist_gauss.getNumElements()); ArrayHandle<unsigned int> h_grid_hist_gauss_delta(m_grid_hist_gauss_delta, access_location::host, access_mode::overwrite); memset(h_grid_hist_gauss_delta.data,0, sizeof(unsigned int)*m_grid_hist_gauss_delta.getNumElements()); // reset to one ArrayHandle<Scalar> h_grid_weight(m_grid_weight, access_location::host, access_mode::overwrite); for (unsigned int i = 0; i < m_grid_weight.getNumElements(); ++i) h_grid_weight.data[i] = Scalar(1.0); resetHistogram(); } Scalar IntegratorMetaDynamics::interpolateGrid(const std::vector<Scalar>& val, bool reweight) { assert(val.size() == m_grid_index.getDimension()); // find closest d-dimensional sub-block std::vector<unsigned int> lower_idx(m_grid_index.getDimension()); std::vector<unsigned int> upper_idx(m_grid_index.getDimension()); std::vector<Scalar> rel_delta(m_grid_index.getDimension()); unsigned int cv = 0; for (unsigned int cv_idx = 0; cv_idx < m_variables.size(); cv_idx++) { Scalar delta = (m_variables[cv_idx].m_cv_max - m_variables[cv_idx].m_cv_min)/(m_variables[cv_idx].m_num_points - 1); if (val[cv] < m_variables[cv_idx].m_cv_min || val[cv] >= m_variables[cv_idx].m_cv_max) { m_exec_conf->msg->warning() << "integrate.mode_metadynamics: Value " << val[cv] << " of collective variable " << m_variables[cv_idx].m_cv->getName() << " out of bounds." << endl << "Assuming bias potential of zero." << endl; return Scalar(0.0); } int lower = (int) ((val[cv] - m_variables[cv_idx].m_cv_min)/delta); int upper = lower+1; // account for round off error if (upper >= (int) m_variables[cv_idx].m_num_points) { lower--; upper--; } Scalar lower_bound = m_variables[cv_idx].m_cv_min + delta * lower; Scalar upper_bound = m_variables[cv_idx].m_cv_min + delta * upper; lower_idx[cv] = lower; upper_idx[cv] = upper; rel_delta[cv] = (val[cv]-lower_bound)/(upper_bound-lower_bound); cv++; } // construct multilinear interpolation unsigned int n_term = 1 << m_grid_index.getDimension(); Scalar res(0.0); ArrayHandle<Scalar> h_grid(m_grid, access_location::host, access_mode::read); ArrayHandle<Scalar> h_grid_weight(m_grid_weight, access_location::host, access_mode::read); for (unsigned int bits = 0; bits < n_term; ++bits) { std::vector<unsigned int> coords(m_grid_index.getDimension()); Scalar term(1.0); for (unsigned int i = 0; i < m_grid_index.getDimension(); i++) { if (bits & (1 << i)) { coords[i] = lower_idx[i]; term *= (Scalar(1.0) - rel_delta[i]); } else { coords[i] = upper_idx[i]; term *= rel_delta[i]; } } unsigned int idx = m_grid_index.getIndex(coords); Scalar val = (reweight ? h_grid_weight.data[idx] : h_grid.data[idx]); term *= val; res += term; } return res; } Scalar IntegratorMetaDynamics::biasPotentialDerivative(unsigned int cv, const std::vector<Scalar>& val) { ArrayHandle<Scalar> h_cv_min(m_cv_min, access_location::host, access_mode::read); ArrayHandle<Scalar> h_cv_max(m_cv_max, access_location::host, access_mode::read); ArrayHandle<unsigned int> h_lengths(m_lengths, access_location::host, access_mode::read); Scalar delta = (h_cv_max.data[cv] - h_cv_min.data[cv])/ (Scalar)(h_lengths.data[cv] - 1); if (val[cv] - delta < m_variables[cv].m_cv_min) { // forward difference std::vector<Scalar> val2 = val; val2[cv] += delta; Scalar y2 = interpolateGrid(val2,false); Scalar y1 = interpolateGrid(val,false); return (y2-y1)/delta; } else if (val[cv] + delta > m_variables[cv].m_cv_max) { // backward difference std::vector<Scalar> val2 = val; val2[cv] -= delta; Scalar y1 = interpolateGrid(val2,false); Scalar y2 = interpolateGrid(val,false); return (y2-y1)/delta; } else { // central difference std::vector<Scalar> val2 = val; std::vector<Scalar> val1 = val; val1[cv] -= delta; val2[cv] += delta; Scalar y1 = interpolateGrid(val1,false); Scalar y2 = interpolateGrid(val2,false); return (y2 - y1)/(Scalar(2.0)*delta); } } void IntegratorMetaDynamics::setGrid(bool use_grid) { #ifdef ENABLE_MPI // Only on root processor if (m_pdata->getDomainDecomposition()) if (! m_exec_conf->isRoot()) return; #endif if (m_is_initialized) { m_exec_conf->msg->error() << "integrate.mode_metadynamics: Cannot change grid mode after initialization." << endl; throw std::runtime_error("Error setting up metadynamics parameters."); } m_use_grid = use_grid; if (use_grid) { // Check for some input errors std::vector<CollectiveVariableItem>::iterator it; for (it = m_variables.begin(); it != m_variables.end(); ++it) { if (it->m_cv_min >= it->m_cv_max) { m_exec_conf->msg->error() << "integrate.mode_metadyanmics: Maximum grid value of collective variable has to be greater than minimum value."; throw std::runtime_error("Error creating collective variable."); } if (it->m_num_points < 2) { m_exec_conf->msg->error() << "integrate.mode_metadynamics: Number of grid points for collective variable has to be at least two."; throw std::runtime_error("Error creating collective variable."); } } } } void IntegratorMetaDynamics::dumpGrid(const std::string& filename1, const std::string& filename2, unsigned int period) { if (period == 0) { // dump grid immediately writeGrid(filename1, 0); return; } m_grid_period = period; m_grid_fname1 = filename1; m_grid_fname2 = filename2; } void IntegratorMetaDynamics::writeGrid(const std::string& filename, unsigned int timestep) { std::ofstream file; #ifdef ENABLE_MPI // Only on root processor if (m_pdata->getDomainDecomposition()) if (! m_exec_conf->isRoot()) return; #endif if (! m_use_grid) { m_exec_conf->msg->error() << "integrate.mode_metadynamics: Grid information can only be dumped if grid is enabled."; throw std::runtime_error("Error dumping grid."); } // open output file file.open((filename+"_"+std::to_string(timestep)).c_str(), ios_base::out); // write file header file << "#n_cv: " << m_grid_index.getDimension() << std::endl; file << "#dim: "; for (unsigned int i= 0; i < m_grid_index.getDimension(); i++) file << " " << m_grid_index.getLength(i); file << std::endl; file << "#num_gaussians: " << m_num_gaussians << std::endl; for (unsigned int i = 0; i < m_variables.size(); i++) { file << m_variables[i].m_cv->getName() << m_delimiter; } file << "grid_value"; file << m_delimiter << "det_sigma"; file << m_delimiter << "num_gaussians"; file << m_delimiter << "hist"; file << m_delimiter << "hist_reweight"; file << m_delimiter << "weight"; file << std::endl; // loop over grid ArrayHandle<Scalar> h_grid(m_grid, access_location::host, access_mode::read); unsigned int len = m_grid_index.getNumElements(); std::vector<unsigned int> coords(m_grid_index.getDimension()); ArrayHandle<Scalar> h_sigma_grid(m_sigma_grid, access_location::host, access_mode::read); ArrayHandle<unsigned int> h_grid_hist(m_grid_hist, access_location::host, access_mode::read); ArrayHandle<unsigned int> h_grid_hist_gauss(m_grid_hist_gauss, access_location::host, access_mode::read); ArrayHandle<Scalar> h_grid_reweighted(m_grid_reweighted, access_location::host, access_mode::read); ArrayHandle<Scalar> h_grid_weight(m_grid_weight, access_location::host, access_mode::read); for (unsigned int grid_idx = 0; grid_idx < len; grid_idx++) { // obtain d-dimensional coordinates m_grid_index.getCoordinates(grid_idx, coords); unsigned int cv = 0; for (unsigned int cv_idx = 0; cv_idx < m_variables.size(); ++cv_idx) { Scalar delta = (m_variables[cv_idx].m_cv_max - m_variables[cv_idx].m_cv_min)/ (m_variables[cv_idx].m_num_points - 1); Scalar val = m_variables[cv_idx].m_cv_min + coords[cv]*delta; file << setprecision(10) << val << m_delimiter; cv++; } file << setprecision(10) << h_grid.data[grid_idx]; // write average of Gaussian volume Scalar val; if (h_grid_hist_gauss.data[grid_idx] > 0) { val = h_sigma_grid.data[grid_idx]/(Scalar)h_grid_hist_gauss.data[grid_idx]; } else val = Scalar(0.0); file << m_delimiter << setprecision(10) << val; file << m_delimiter << h_grid_hist_gauss.data[grid_idx]; file << m_delimiter << h_grid_hist.data[grid_idx]; file << m_delimiter << setprecision(10) << h_grid_reweighted.data[grid_idx]; file << m_delimiter << setprecision(10) << h_grid_weight.data[grid_idx]; file << std::endl; } file.close(); } void IntegratorMetaDynamics::readGrid(const std::string& filename) { #ifdef ENABLE_MPI // Only on root processor if (m_pdata->getDomainDecomposition()) if (! m_exec_conf->isRoot()) return; #endif if (! m_use_grid) { m_exec_conf->msg->error() << "integrate.mode_metadynamics: Grid information can only be read if grid is enabled."; throw std::runtime_error("Error reading grid."); } std::ifstream file; // open grid file file.open(filename.c_str()); std::string line; // Skip first two lines of file header getline(file, line); getline(file, line); // read number of histogram entries getline(file, line); istringstream iss(line); std::string tmp; iss >> tmp >> m_num_gaussians; // Skip last header line getline(file, line); unsigned int len = m_grid_index.getNumElements(); std::vector<unsigned int> coords(m_grid_index.getDimension()); ArrayHandle<Scalar> h_grid(m_grid, access_location::host, access_mode::overwrite); ArrayHandle<Scalar> h_sigma_grid(m_sigma_grid, access_location::host, access_mode::overwrite); ArrayHandle<unsigned int> h_grid_hist(m_grid_hist, access_location::host, access_mode::overwrite); ArrayHandle<unsigned int> h_grid_hist_gauss(m_grid_hist_gauss, access_location::host, access_mode::overwrite); ArrayHandle<Scalar> h_grid_reweighted(m_grid_reweighted, access_location::host, access_mode::overwrite); ArrayHandle<Scalar> h_grid_weight(m_grid_weight, access_location::host, access_mode::overwrite); for (unsigned int grid_idx = 0; grid_idx < len; grid_idx++) { if (! file.good()) { m_exec_conf->msg->error() << "integrate.mode_metadynamics: Premature end of grid file."; throw std::runtime_error("Error reading grid."); } getline(file, line); istringstream iss(line); // skip values of collective variables for (unsigned int i = 0; i < m_variables.size(); i++) iss >> tmp; iss >> h_grid.data[grid_idx]; iss >> h_sigma_grid.data[grid_idx]; iss >> h_grid_hist_gauss.data[grid_idx]; iss >> h_grid_hist.data[grid_idx]; h_sigma_grid.data[grid_idx] *= h_grid_hist_gauss.data[grid_idx]; iss >> h_grid_reweighted.data[grid_idx]; iss >> h_grid_weight.data[grid_idx]; } file.close(); } void IntegratorMetaDynamics::updateGrid(std::vector<Scalar>& current_val, Scalar scal ) { if (m_prof) m_prof->push("update grid"); ArrayHandle<Scalar> h_grid_delta(m_grid_delta, access_location::host, access_mode::overwrite); // loop over grid unsigned int len = m_grid_index.getNumElements(); std::vector<unsigned int> coords(m_grid_index.getDimension()); ArrayHandle<Scalar> h_sigma_inv(m_sigma_inv, access_location::host, access_mode::read); for (unsigned int grid_idx = 0; grid_idx < len; grid_idx++) { // obtain d-dimensional coordinates m_grid_index.getCoordinates(grid_idx, coords); Scalar gauss_exp(0.0); // evaluate Gaussian on grid point for (unsigned int cv_i = 0; cv_i < m_variables.size(); ++cv_i) { Scalar delta_i = (m_variables[cv_i].m_cv_max - m_variables[cv_i].m_cv_min)/ (m_variables[cv_i].m_num_points - 1); Scalar val_i = m_variables[cv_i].m_cv_min + coords[cv_i]*delta_i; double d_i = val_i - current_val[cv_i]; for (unsigned int cv_j = 0; cv_j < m_variables.size(); ++cv_j) { Scalar delta_j = (m_variables[cv_j].m_cv_max - m_variables[cv_j].m_cv_min)/ (m_variables[cv_j].m_num_points - 1); Scalar val_j = m_variables[cv_j].m_cv_min + coords[cv_j]*delta_j; double d_j = val_j - current_val[cv_j]; Scalar sigma_inv_ij = h_sigma_inv.data[cv_i*m_variables.size()+cv_j]; gauss_exp += d_i*d_j*Scalar(1.0/2.0)*(sigma_inv_ij*sigma_inv_ij); } } double gauss = exp(-gauss_exp); // add Gaussian to grid h_grid_delta.data[grid_idx] = m_W*scal*gauss; } if (m_prof) m_prof->pop(); } /*! \param val List of current CV values * * Called every time a Gaussian is deposted */ void IntegratorMetaDynamics::updateReweightedEstimator(std::vector<Scalar>& current_val) { if (m_prof) m_prof->push("update grid"); ArrayHandle<Scalar> h_grid_reweighted(m_grid_reweighted, access_location::host, access_mode::readwrite); ArrayHandle<Scalar> h_grid_weight(m_grid_weight, access_location::host, access_mode::readwrite); ArrayHandle<Scalar> h_grid_delta(m_grid_delta, access_location::host, access_mode::read); ArrayHandle<unsigned int> h_grid_hist_delta(m_grid_hist_delta, access_location::host, access_mode::read); // loop over grid unsigned int len = m_grid_index.getNumElements(); std::vector<unsigned int> coords(m_grid_index.getDimension()); Scalar avg_delta_V(0.0); Scalar norm(0.0); // compute ensemble-averaged temporal bias potential derivative for (unsigned int grid_idx = 0; grid_idx < len; grid_idx++) { h_grid_reweighted.data[grid_idx] += (Scalar) h_grid_hist_delta.data[grid_idx]; avg_delta_V += h_grid_reweighted.data[grid_idx]*h_grid_delta.data[grid_idx]; norm += h_grid_reweighted.data[grid_idx]; } avg_delta_V /= norm; for (unsigned int grid_idx = 0; grid_idx < len; grid_idx++) { double delta_V = h_grid_delta.data[grid_idx]; // evolve estimator and grid of reweighting factors Scalar fac = exp(-(delta_V-avg_delta_V)/m_temp); h_grid_reweighted.data[grid_idx] *= fac; h_grid_weight.data[grid_idx] /= fac; } if (m_prof) m_prof->pop(); } void IntegratorMetaDynamics::updateHistogram(std::vector<Scalar>& current_val) { if (m_prof) m_prof->push("update grid"); ArrayHandle<unsigned int> h_grid_hist_delta(m_grid_hist_delta, access_location::host, access_mode::readwrite); std::vector<unsigned int> grid_coord(m_variables.size()); // increment histogram of CV values bool on_grid = true; for (unsigned int cv_i = 0; cv_i < m_variables.size(); ++cv_i) { Scalar delta = (m_variables[cv_i].m_cv_max - m_variables[cv_i].m_cv_min)/ (m_variables[cv_i].m_num_points - 1); grid_coord[cv_i] = (current_val[cv_i] - m_variables[cv_i].m_cv_min)/delta; if (grid_coord[cv_i] >= m_variables[cv_i].m_num_points) on_grid = false; } // add to histogram if (on_grid) { unsigned int grid_idx = m_grid_index.getIndex(grid_coord); h_grid_hist_delta.data[grid_idx]++; } if (m_prof) m_prof->pop(); } void IntegratorMetaDynamics::updateSigmaGrid(std::vector<Scalar>& current_val) { if (m_prof) m_prof->push("update grid"); ArrayHandle<Scalar> h_sigma_grid_delta(m_sigma_grid_delta, access_location::host, access_mode::readwrite); ArrayHandle<unsigned int> h_grid_hist_gauss_delta(m_grid_hist_gauss_delta, access_location::host, access_mode::readwrite); assert(h_sigma_grid_delta.data); std::vector<unsigned int> grid_coord(m_variables.size()); // add current value of determinant of standard deviation matrix to grid bool on_grid = true; unsigned int cv = 0; for (unsigned int cv_i = 0; cv_i < m_variables.size(); ++cv_i) { Scalar delta = (m_variables[cv_i].m_cv_max - m_variables[cv_i].m_cv_min)/ (m_variables[cv_i].m_num_points - 1); grid_coord[cv] = (current_val[cv] - m_variables[cv_i].m_cv_min)/delta; if (grid_coord[cv] >= m_variables[cv_i].m_num_points) on_grid = false; cv++; } // add Gaussian to grid if (on_grid) { unsigned int grid_idx = m_grid_index.getIndex(grid_coord); h_sigma_grid_delta.data[grid_idx] += sigmaDeterminant(); h_grid_hist_gauss_delta.data[grid_idx]++; } if (m_prof) m_prof->pop(); } #ifdef ENABLE_CUDA void IntegratorMetaDynamics::updateGridGPU(std::vector<Scalar>& current_val, Scalar scal) { if (m_prof) m_prof->push(m_exec_conf, "update grid"); { // copy current CV values into array ArrayHandle<Scalar> h_current_val(m_current_val, access_location::host, access_mode::overwrite); for (unsigned int cv = 0; cv < current_val.size(); cv++) h_current_val.data[cv] = current_val[cv]; } ArrayHandle<Scalar> d_grid_delta(m_grid_delta, access_location::device, access_mode::readwrite); ArrayHandle<unsigned int> d_lengths(m_lengths, access_location::device, access_mode::read); ArrayHandle<Scalar> d_cv_min(m_cv_min, access_location::device, access_mode::read); ArrayHandle<Scalar> d_cv_max(m_cv_max, access_location::device, access_mode::read); ArrayHandle<Scalar> d_sigma_inv(m_sigma_inv, access_location::device, access_mode::read); ArrayHandle<Scalar> d_current_val(m_current_val, access_location::device, access_mode::read); gpu_update_grid(m_grid_index.getNumElements(), d_lengths.data, m_variables.size(), d_current_val.data, d_grid_delta.data, d_cv_min.data, d_cv_max.data, d_sigma_inv.data, scal, m_W, m_temp); if (m_prof) m_prof->pop(m_exec_conf); } #endif void IntegratorMetaDynamics::resetHistogram() { ArrayHandle<unsigned int> h_grid_hist(m_grid_hist, access_location::host, access_mode::overwrite); memset(h_grid_hist.data, 0, sizeof(unsigned int)*m_grid_hist.getNumElements()); ArrayHandle<unsigned int> h_grid_hist_delta(m_grid_hist_delta, access_location::host, access_mode::overwrite); memset(h_grid_hist_delta.data, 0, sizeof(unsigned int)*m_grid_hist_delta.getNumElements()); } void IntegratorMetaDynamics::computeSigma() { if (m_prof) m_prof->push(m_exec_conf,"Derivatives"); std::vector<CollectiveVariableItem>::iterator iti,itj; unsigned int ncv = m_variables.size(); Scalar *sigmasq = new Scalar[ncv*ncv]; bool is_root = m_exec_conf->getRank() == 0; unsigned int i = 0; unsigned int j = 0; std::vector< ArrayHandle<Scalar4>* > handles; for (iti = m_variables.begin(); iti != m_variables.end(); ++iti) handles.push_back(new ArrayHandle<Scalar4>(iti->m_cv->getForceArray(), access_location::host, access_mode::read)); for (iti = m_variables.begin(); iti != m_variables.end(); ++iti) { ArrayHandle<Scalar4>& handle_i = *handles[i]; j = 0; for (itj = m_variables.begin(); itj != m_variables.end(); ++itj) { sigmasq[i*ncv+j] = Scalar(0.0); if (iti->m_cv->canComputeDerivatives() && itj->m_cv->canComputeDerivatives()) { // this releases an array twice, so may create problems in debug mode ArrayHandle<Scalar4>& handle_j = *handles[j]; // sum up products of derviatives for (unsigned int n = 0; n < m_pdata->getN(); ++n) { Scalar4 f_i = handle_i.data[n]; Scalar4 f_j = handle_j.data[n]; Scalar3 force_i = make_scalar3(f_i.x,f_i.y,f_i.z); Scalar3 force_j = make_scalar3(f_j.x,f_j.y,f_j.z); sigmasq[i*ncv+j] += m_sigma_g*m_sigma_g*dot(force_i,force_j); } } else if (i==j && is_root) sigmasq[i*ncv+j] = iti->m_sigma*iti->m_sigma; j++; } i++; } for (unsigned int i = 0; i < handles.size(); ++i) delete handles[i]; #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition()) { MPI_Allreduce(MPI_IN_PLACE, &sigmasq[0], ncv*ncv, MPI_HOOMD_SCALAR, MPI_SUM, m_exec_conf->getMPICommunicator()); } #endif if (is_root) { // invert sigma matrix ArrayHandle<Scalar> h_sigma_inv(m_sigma_inv, access_location::host, access_mode::overwrite); Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> m(ncv,ncv); for (unsigned int i = 0; i < ncv; ++i) for (unsigned int j = 0 ; j < ncv; ++j) m(i,j) = sqrt(sigmasq[i*ncv+j]); Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> inv = m.inverse(); for (unsigned int i = 0; i < ncv; ++i) for (unsigned int j = 0 ; j < ncv; ++j) h_sigma_inv.data[i*ncv+j] = inv(i,j); } delete[] sigmasq; if (m_prof) m_prof->pop(); } Scalar IntegratorMetaDynamics::sigmaDeterminant() { #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition() && m_exec_conf->getRank()) return Scalar(0.0); #endif ArrayHandle<Scalar> h_sigma_inv(m_sigma_inv, access_location::host, access_mode::overwrite); unsigned int ncv = m_variables.size(); Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> m(ncv,ncv); for (unsigned int i = 0; i < ncv; ++i) for (unsigned int j = 0 ; j < ncv; ++j) m(i,j) = h_sigma_inv.data[i*ncv+j]; return m.determinant(); } void export_IntegratorMetaDynamics(py::module& m) { py::class_<IntegratorMetaDynamics, std::shared_ptr<IntegratorMetaDynamics> > integrator_metad(m, "IntegratorMetaDynamics", py::base<IntegratorTwoStep>()); integrator_metad.def(py::init< std::shared_ptr<SystemDefinition>, Scalar, Scalar, Scalar, Scalar, unsigned int, bool, const std::string&, bool, IntegratorMetaDynamics::Enum>()) .def("registerCollectiveVariable", &IntegratorMetaDynamics::registerCollectiveVariable) .def("removeAllVariables", &IntegratorMetaDynamics::removeAllVariables) .def("isInitialized", &IntegratorMetaDynamics::isInitialized) .def("setGrid", &IntegratorMetaDynamics::setGrid) .def("dumpGrid", &IntegratorMetaDynamics::dumpGrid) .def("restartFromGridFile", &IntegratorMetaDynamics::restartFromGridFile) .def("setAddHills", &IntegratorMetaDynamics::setAddHills) .def("setMode", &IntegratorMetaDynamics::setMode) .def("setStride", &IntegratorMetaDynamics::setStride) .def("setAdaptive", &IntegratorMetaDynamics::setAdaptive) .def("setSigmaG", &IntegratorMetaDynamics::setSigmaG) .def("resetHistogram", &IntegratorMetaDynamics::resetHistogram) .def("setMultipleWalkers", &IntegratorMetaDynamics::setMultipleWalkers) ; py::enum_<IntegratorMetaDynamics::Enum>(integrator_metad,"mode") .value("standard", IntegratorMetaDynamics::mode_standard) .value("well_tempered", IntegratorMetaDynamics::mode_well_tempered) .export_values(); ; } <file_sep>/*! \file LamellarOrderParameterGPU.cc * \brief Implements the LamellarOrderParameterGPU class */ #include "LamellarOrderParameterGPU.h" #ifdef ENABLE_CUDA #include "LamellarOrderParameterGPU.cuh" namespace py = pybind11; LamellarOrderParameterGPU::LamellarOrderParameterGPU(std::shared_ptr<SystemDefinition> sysdef, const std::vector<Scalar>& mode, const std::vector<int3>& lattice_vectors, const std::string& suffix) : LamellarOrderParameter(sysdef, mode, lattice_vectors, suffix) { GPUArray<Scalar> gpu_mode(mode.size(), m_exec_conf); m_gpu_mode.swap(gpu_mode); // Load mode information ArrayHandle<Scalar> h_gpu_mode(m_gpu_mode, access_location::host, access_mode::overwrite); for (unsigned int i = 0; i < mode.size(); i++) h_gpu_mode.data[i] = mode[i]; m_block_size = 128; unsigned int max_n_blocks = m_pdata->getMaxN()/m_block_size + 1; GPUArray<Scalar2> fourier_mode_scratch(mode.size()*max_n_blocks, m_exec_conf); m_fourier_mode_scratch.swap(fourier_mode_scratch); } void LamellarOrderParameterGPU::computeCV(unsigned int timestep) { if (m_prof) m_prof->push(m_exec_conf, "Lamellar"); ArrayHandle<Scalar4> d_postype(m_pdata->getPositions(), access_location::device, access_mode::read); unsigned int max_n_blocks = m_pdata->getMaxN()/m_block_size + 1; if (m_fourier_mode_scratch.getNumElements() < max_n_blocks*m_fourier_modes.getNumElements()) { m_fourier_mode_scratch.resize(max_n_blocks*m_fourier_modes.getNumElements()); } { ArrayHandle<int3> d_lattice_vectors(m_lattice_vectors, access_location::device, access_mode::read); ArrayHandle<Scalar2> d_fourier_modes(m_fourier_modes, access_location::device, access_mode::overwrite); ArrayHandle<Scalar> d_gpu_mode(m_gpu_mode, access_location::device, access_mode::read); ArrayHandle<Scalar2> d_fourier_mode_scratch(m_fourier_mode_scratch, access_location::device, access_mode::overwrite); // calculate Fourier modes gpu_calculate_fourier_modes(m_lattice_vectors.getNumElements(), d_lattice_vectors.data, m_pdata->getN(), d_postype.data, d_gpu_mode.data, d_fourier_modes.data, m_block_size, d_fourier_mode_scratch.data, m_pdata->getGlobalBox()); if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); } unsigned int N = m_pdata->getNGlobal(); #ifdef ENABLE_MPI // reduce Fourier modes on all processors if (m_pdata->getDomainDecomposition()) { ArrayHandle<Scalar2> h_fourier_modes(m_fourier_modes, access_location::host, access_mode::readwrite); MPI_Allreduce(MPI_IN_PLACE,h_fourier_modes.data,m_fourier_modes.getNumElements(), MPI_HOOMD_SCALAR, MPI_SUM, m_exec_conf->getMPICommunicator()); } #endif ArrayHandle<Scalar2> h_fourier_modes(m_fourier_modes, access_location::host, access_mode::read); // calculate value of collective variable Scalar sum = 0.0; for (unsigned k = 0; k < m_fourier_modes.getNumElements(); k++) { Scalar2 fmode = h_fourier_modes.data[k]; sum += fmode.x; } sum /= (Scalar) N; m_cv = sum; if (m_prof) m_prof->pop(m_exec_conf); m_cv_last_updated = timestep; } void LamellarOrderParameterGPU::computeBiasForces(unsigned int timestep) { if (m_prof) m_prof->push(m_exec_conf, "Lamellar"); if (m_cv_last_updated < timestep || timestep == 0) computeCV(timestep); ArrayHandle<Scalar4> d_postype(m_pdata->getPositions(), access_location::device, access_mode::read); { ArrayHandle<int3> d_lattice_vectors(m_lattice_vectors, access_location::device, access_mode::read); ArrayHandle<Scalar> d_gpu_mode(m_gpu_mode, access_location::device, access_mode::read); ArrayHandle<Scalar4> d_force(m_force, access_location::device, access_mode::overwrite); // calculate forces gpu_compute_sq_forces(m_pdata->getN(), d_postype.data, d_force.data, m_lattice_vectors.getNumElements(), d_lattice_vectors.data, d_gpu_mode.data, m_pdata->getNGlobal(), m_bias, m_cv, m_pdata->getGlobalBox()); if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); } if (m_prof) m_prof->pop(m_exec_conf); } void export_LamellarOrderParameterGPU(py::module &m) { py::class_<LamellarOrderParameterGPU, std::shared_ptr<LamellarOrderParameterGPU> >(m,"LamellarOrderParameterGPU",py::base<LamellarOrderParameter>()) .def(py::init<std::shared_ptr<SystemDefinition>, const std::vector<Scalar>&, const std::vector<int3>, const std::string&>()); } #endif <file_sep>find_package(Doxygen) if (DOXYGEN_FOUND) set(DOXYGEN_PREDEFINED ${DOXYGEN_PREDEFINED} " \"ENABLE_CUDA=1\" \\ \"NVCC=1\" ") # disable DOT in doxygen if dot is not found if(DOXYGEN_DOT_PATH) set(DOXYGEN_HAVE_DOT "YES") else(DOXYGEN_DOT_PATH) set(DOXYGEN_HAVE_DOT "NO") endif(DOXYGEN_DOT_PATH) # configure the doxygen file configure_file (${CMAKE_CURRENT_SOURCE_DIR}/Doxyfile.in ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile) file(GLOB SOURCE_FILES "${${PROJECT_NAME}_SOURCE_DIR}/cppmodule/*.cu" "${${PROJECT_NAME}_SOURCE_DIR}/cppmodule/*.cuh" "${${PROJECT_NAME}_SOURCE_DIR}/cppmodule/*.cc" "${${PROJECT_NAME}_SOURCE_DIR}/cppmodule/*.h" "${${PROJECT_NAME}_SOURCE_DIR}/pymodule/*.py" "${${PROJECT_NAME}_SOURCE_DIR}/doc/*.doc") add_custom_command (OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}/index.html COMMAND ${DOXYGEN} ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile DEPENDS ${SOURCE_FILES} ${CMAKE_CURRENT_SOURCE_DIR}/Doxyfile.in ${CMAKE_CURRENT_SOURCE_DIR}/DoxygenLayout.xml) add_custom_target (${PROJECT_NAME}_doc ALL DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}/index.html) endif (DOXYGEN_FOUND) <file_sep>"""This module defines collective variables used for metadynamics integration.""" from hoomd.metadynamics import _metadynamics import hoomd from hoomd import _hoomd from hoomd import md from hoomd import group from hoomd.md import nlist as nl from hoomd.md import _md class _collective_variable(md.force._force): """Base class for collective variables. A **collective_variable** in python reflects a CollectiveVariable in C++. It is, in particular, a specialization of a force, since collective variables generate forces acting on the particles during the simulation. :param sigma: Standard deviation of Gaussians added for this collective variable - only relevant for "well-tempered" or "standard" metadynamics. :param name: Name of the collective variable. """ def __init__(self, sigma, name=None): # register as ForceCompute md.force._force.__init__(self, name) self.sigma = sigma # default grid parameters self.cv_min = 0.0 self.cv_max = 0.0 self.num_points = 0 self.grid_set = False self.ftm_min = 0.0 self.ftm_max = 0.0 self.ftm_parameters_set = False self.umbrella = False self.reweight = False ## \var sigma # \internal ## \var cv_min # \internal ## \var cv_max # \internal ## \var num_points # \internal ## \var grid_set # \internal ## \var ftm_min # \internal ## \var ftm_max # \internal ## \var ftm_num_points # \internal def set_grid(self, cv_min, cv_max, num_points): """Sets grid mode for this collective variable. :param cv_min: Minimum of the collective variable (smallest grid value) :param cv_max: Maximum of the collective variable (largest grid value) :param num_points: Dimension of the grid for this collective variable """ hoomd.util.print_status_line() self.cv_min = cv_min self.cv_max = cv_max self.num_points = int(num_points) self.grid_set = True def enable_histograms(self, ftm_min, ftm_max): """Sets parameters for the histogram of flux-tempered metadynamics. :param ftm_min: Minimum of the collective variable (smallest grid value) :param ftm_max: Maximum of the collective variable (largest grid value) :param num_points: Dimension of the grid for this collective variable """ hoomd.util.print_status_line() self.ftm_min = ftm_min self.ftm_max = ftm_max self.ftm_parameters_set = True def set_params(self, sigma=None, kappa=None, cv0=None, umbrella=None, width_flat=None, scale=None, reweight=None): """Set parameters for this collective variable. :param sigma: The standard deviation :param umbrella: The umbrella mode, if this is an umbrella potential :param kappa: Umbrella potential stiffness :param cv0: Umbrella potential minimum position :param umbrella: If True, do not add Gaussians in this collective variable :param width_flat: Width of flat region of umbrella potential :param scale: Prefactor multiplying umbrella potential :param reweight: True if CV should be included in reweighting """ hoomd.util.print_status_line() if sigma is not None: self.sigma = sigma if umbrella is not None: if umbrella == "no_umbrella": cpp_umbrella = self.cpp_force.umbrella.no_umbrella self.reweight = False self.umbrella = False elif umbrella == "linear": cpp_umbrella = self.cpp_force.umbrella.linear self.reweight = True self.umbrella = True elif umbrella == "harmonic": cpp_umbrella = self.cpp_force.umbrella.harmonic self.reweight = True self.umbrella = True elif umbrella == "wall": cpp_umbrella = self.cpp_force.umbrella.wall self.reweight = True self.umbrella = True elif umbrella == "gaussian": cpp_umbrella = self.cpp_force.umbrella.gaussian self.reweight = True self.umbrella = True else: hoomd.context.msg.error("cv: Invalid umbrella mode specified.") raise RuntimeError("Error setting parameters of collective variable.") self.cpp_force.setUmbrella(cpp_umbrella) if kappa is not None: self.cpp_force.setKappa(kappa) if width_flat is not None: self.cpp_force.setWidthFlat(width_flat) if cv0 is not None: self.cpp_force.setMinimum(cv0) if scale is not None: self.cpp_force.setScale(scale) if reweight is not None: self.reweight = reweight class lamellar(_collective_variable): """Lamellar order parameter as a collective variable. This order parameter can be used to study phase transitions in block copolymer systems and is based on the Fourier modes of concentration or composition fluctuations. The value of the collective variable :math:`s` is given by .. math:: s = V^{-1} \sum_{i = 1}^n \sum_{j = 1}^N a(type_j) \cos(\mathbf{q}_i\mathbf{r_j} + \phi_i), where * :math:`n` is the number of modes supplied, * :math:`N` is the number of particles, * :math:`V` is the system volume, * :math:`\mathbf{q}_i = 2 \pi (\frac{n_{i,x}}{L_x}, \frac{n_{i,y}}{L_y}, \frac{n_{i,z}}{L_z})`, is the wave vector associated with mode :math:`i`, * :math:`\phi_i` is its phase shift, * :math:`a(type)` is the mode coefficient for a particle of type :math:`type`. The force on particle i is calculated as :math:`\vec f_i = - \frac{\partial V}{\partial s} \vec\nabla_i s`. ## Example In a diblock copolymer melt constructed from monomers of types A and B, use .. code:: metadynamics.cv.lamellar(sigma=.05,mode=dict(A=1.0, B=-1.0), lattice_vectors=[(0,0,3)],phi=[0.0]) to define the order parameter for a Fourier mode along the (003) direction, with mode coefficients of +1 and -1 for A and B monomers. The width of Gaussians deposited is sigma=0.05. The phase shift is zero. ## Logging The log name of this collective variable used by the command **analyze.log** is **cv_lamellar**. :param sigma: Standard deviation of deposited Gaussians :param mode: Per-type list (dictionary) of mode coefficients :param lattice_vectors: List of reciprocal lattice vectors (Miller indices) for every mode :param name: Name given to this collective variable """ def __init__(self, mode, lattice_vectors, name=None, sigma=1.0): hoomd.util.print_status_line() if name is not None: name = "_" + name suffix = name else: suffix = "" _collective_variable.__init__(self, sigma, name) if len(lattice_vectors) == 0: hoomd.context.msg.error("cv.lamellar: List of supplied latice vectors is empty.\n") raise RuntimeEror('Error creating collective variable.') if type(mode) != type(dict()): hoomd.context.msg.error("cv.lamellar: Mode amplitudes specified incorrectly.\n") raise RuntimeEror('Error creating collective variable.') cpp_mode = _hoomd.std_vector_scalar() for i in range(0, hoomd.context.current.system_definition.getParticleData().getNTypes()): t = hoomd.context.current.system_definition.getParticleData().getNameByType(i) if t not in mode.keys(): hoomd.context.msg.error("cv.lamellar: Missing mode amplitude for particle type " + t + ".\n") raise RuntimeEror('Error creating collective variable.') cpp_mode.append(mode[t]) cpp_lattice_vectors = _metadynamics.std_vector_int3() for l in lattice_vectors: if len(l) != 3: hoomd.context.msg.error("cv.lamellar: List of input lattice vectors not a list of triples.\n") raise RuntimeError('Error creating collective variable.') cpp_lattice_vectors.append(hoomd.make_int3(l[0], l[1], l[2])) if not hoomd.context.exec_conf.isCUDAEnabled(): self.cpp_force = _metadynamics.LamellarOrderParameter( hoomd.context.current.system_definition, cpp_mode, cpp_lattice_vectors, suffix) else: self.cpp_force = _metadynamics.LamellarOrderParameterGPU( hoomd.context.current.system_definition, cpp_mode, cpp_lattice_vectors, suffix) hoomd.context.current.system.addCompute(self.cpp_force, self.force_name) ## \var cpp_force # \internal ## \internal def update_coeffs(self): pass class aspect_ratio(_collective_variable): """Aspect ratio of the tetragonal simulation box as collective variable. The aspect ratio is defined as the ratio between box lengths in direction 1 and 2. :param dir1: Cartesian index of first direction :param dir2: Cartesian index of second direction :param sigma: Standard deviation of deposited Gaussians """ def __init__(self, dir1, dir2, name="", sigma=1.0): hoomd.util.print_status_line() _collective_variable.__init__(self, sigma, name) self.cpp_force = _metadynamics.AspectRatio(hoomd.context.current.system_definition, int(dir1), int(dir2)) # add to System hoomd.context.current.system.addCompute(self.cpp_force, self.force_name) ## \var cpp_force # \internal ## \internal def update_coeffs(self): pass class density(_collective_variable): """Number density Construct a collective variable from the number density of particles. :param group: Group that provides count of number of particles :param sigma: Standard deviation of deposited Gaussians """ def __init__(self, group=None, sigma=1.0): hoomd.util.print_status_line() if group is None: group = hoomd.group.all() name = group.name _collective_variable.__init__(self, sigma, name) self.cpp_force = _metadynamics.Density(hoomd.context.current.system_definition, group.cpp_group, name) # add to System hoomd.context.current.system.addCompute(self.cpp_force, self.force_name) ## \var cpp_force # \internal ## \internal def update_coeffs(self): pass def _table_eval(r, rmin, rmax, V, F, width): dr = (rmax - rmin) / float(width - 1) i = int(round((r - rmin) / dr)) return (V[i], F[i]) def _table_eval(r, rmin, rmax, V, F, width): dr = (rmax - rmin) / float(width - 1) i = int(round((r - rmin) / dr)) return (V[i], F[i]) class mesh(_collective_variable): """Construct a lamellar order parameter. :param sigma: Standard deviation of deposited Gaussians :param mode: Per-type list (dictionary) of mode coefficients :param nx: Number of mesh points along first axis :param ny: Number of mesh points along second axis :param nz: Number of mesh points along third axis :param name: Name given to this collective variable :param zero_modes: Indices of modes that should be zeroed """ def __init__(self, mode, nx, ny=None, nz=None, name=None, sigma=1.0, zero_modes=None): hoomd.util.print_status_line() if name is not None: name = "_" + name suffix = name else: suffix = "" if ny is None: ny = nx if nz is None: nz = nx _collective_variable.__init__(self, sigma, name) if type(mode) != type(dict()): hoomd.context.msg.error("cv.mesh: Mode amplitudes specified incorrectly.\n") raise RuntimeEror('Error creating collective variable.') cpp_mode = _hoomd.std_vector_scalar() for i in range(0, hoomd.context.current.system_definition.getParticleData().getNTypes()): t = hoomd.context.current.system_definition.getParticleData().getNameByType(i) if t not in mode.keys(): hoomd.context.msg.error("cv.mesh: Missing mode amplitude for particle type " + t + ".\n") raise RuntimeEror('Error creating collective variable.') cpp_mode.append(mode[t]) cpp_zero_modes = _metadynamics.std_vector_int3() if zero_modes is not None: for l in zero_modes: if len(l) != 3: hoomd.context.msg.error("cv.lamellar: List of modes to zero not a list of triples.\n") raise RuntimeError('Error creating collective variable.') cpp_zero_modes.append(hoomd.make_int3(l[0], l[1], l[2])) if not hoomd.context.exec_conf.isCUDAEnabled(): self.cpp_force = _metadynamics.OrderParameterMesh( hoomd.context.current.system_definition, nx, ny, nz, cpp_mode, cpp_zero_modes) else: self.cpp_force = _metadynamics.OrderParameterMeshGPU( hoomd.context.current.system_definition, nx, ny, nz, cpp_mode, cpp_zero_modes) hoomd.context.current.system.addCompute(self.cpp_force, self.force_name) ## \var cpp_force # \internal def set_params(self, use_table=None, **args): """Set parameters for the collective variable """ hoomd.util.print_status_line() if use_table is not None: self.cpp_force.setUseTable(use_table) # call base class method hoomd.util.quiet_status() _collective_variable.set_params(self, **args) hoomd.util.quiet_status() def set_kernel(self, func, kmin, kmax, width, coeff=dict()): """Set the table to be used for the convolution kernel. :param func: The function the returns the convolution kernel and its derivative :param kmin: Minimum k :param kmax: Maximum k :param width: Number of interpolation points :param coeff: Additional parameters to the function, as a dict (optional) """ # allocate arrays to store kernel and derivative Ktable = _hoomd.std_vector_scalar() dKtable = _hoomd.std_vector_scalar() # calculate dr dk = (kmax - kmin) / float(width - 1) # evaluate the function for i in range(0, width): k = kmin + dk * i (K, dK) = func(k, kmin, kmax, **coeff) Ktable.append(K) dKtable.append(dK) # pass table to C++ collective variable self.cpp_force.setTable(Ktable, dKtable, kmin, kmax) ## \internal def update_coeffs(self): pass class potential_energy(_collective_variable): """Potential Energy (Well-Tempered Ensemble) Use the potential energy as a collective variable. :param sigma: Standard deviation of deposited Gaussians """ def __init__(self, sigma=1.0): hoomd.util.print_status_line() name = 'cv_potential_energy' _collective_variable.__init__(self, sigma, name) # disable as regular ForceCompute self.enabled = False self.cpp_force = _metadynamics.WellTemperedEnsemble(hoomd.context.current.system_definition, name) hoomd.context.current.system.addCompute(self.cpp_force, name) ## \var cpp_force # \internal ## \internal def update_coeffs(self): pass class wrap(_collective_variable): """Force Wraper Use an arbitrary force as collective variable :param force: The handle to the force we are wrapping :param sigma: Standard deviation of deposited Gaussians """ def __init__(self, force, sigma=1.0): hoomd.util.print_status_line() if not isinstance(force, md.force._force): hoomd.context.msg.error("cv.wrap needs a md._force instance as argument.") name = 'cv_' + force.name _collective_variable.__init__(self, sigma, name) self.cpp_force = _metadynamics.CollectiveWrapper(hoomd.context.current.system_definition, force.cpp_force, name) if force.enabled or force.log: hoomd.context.current.system.addCompute(self.cpp_force, name) self.log = force.log def disable(self, log=False): self.disable(log) force.disable(log) def enable(self): self.enable() force.enable() ## \internal def update_coeffs(self): pass class steinhardt(_collective_variable): """Steinhardt Ql Use a Steinhardt Ql order parameter as collective variable. :param r_cut: Cut-off for neighbor search :param r_on: Onset of smoothing :param lmax: Maximum Ql to compute :param Ql_ref: List of reference Ql values (of length lmax+1) :param nlist: Neighbor list object :param type: Type of particles to compute order parameter for :param name: Name of Ql instance (optional) :param sigma: Standard deviation of deposited Gaussians """ def __init__(self, r_cut, r_on, lmax, Ql_ref, nlist, type, name=None, sigma=1.0): hoomd.util.print_status_line() suffix = "" if name is not None: suffix = "_" + name _collective_variable.__init__(self, sigma, name) self.type = type # subscribe to neighbor list rcut self.nlist = nlist self.r_cut = r_cut self.nlist.subscribe(lambda: self.get_rcut()) self.nlist.update_rcut() if hoomd.context.exec_conf.isCUDAEnabled(): self.nlist.cpp_nlist.setStorageMode(_md.NeighborList.storageMode.full) type_list = [] for i in range(0, hoomd.context.current.system_definition.getParticleData().getNTypes()): type_list.append(hoomd.context.current.system_definition.getParticleData().getNameByType(i)) if type not in type_list: hoomd.context.msg.error("cv.steinhardt: Invalid particle type.") raise RuntimeError('Error creating collective variable.') cpp_Ql_ref = _hoomd.std_vector_scalar() for Ql in list(Ql_ref): cpp_Ql_ref.append(Ql) self.cpp_force = _metadynamics.SteinhardtQl(hoomd.context.current.system_definition, float( r_cut), float(r_on), int(lmax), nlist.cpp_nlist, type_list.index(type), cpp_Ql_ref, suffix) hoomd.context.current.system.addCompute(self.cpp_force, self.force_name) def get_rcut(self): # go through the list of only the active particle types in the sim ntypes = hoomd.context.current.system_definition.getParticleData().getNTypes() type_list = [] for i in range(0, ntypes): type_list.append(hoomd.context.current.system_definition.getParticleData().getNameByType(i)) my_typeid = type_list.index(self.type) # update the rcut by pair type r_cut_dict = nl.rcut() for i in range(0, ntypes): for j in range(i, ntypes): # interaction only for one particle type pair if i == my_typeid and j == my_typeid: # get the r_cut value r_cut_dict.set_pair(type_list[i], type_list[j], self.r_cut) else: r_cut_dict.set_pair(type_list[i], type_list[j], -1.0) return r_cut_dict ## \internal def update_coeffs(self): pass <file_sep># Call with --nrank=1 and multiple MPI ranks # bias.restart_0.dat and bias.dat_2 should be identical up to rounding errors from hoomd import * from hoomd import md import math import numpy as np with context.initialize(): snap = data.make_snapshot(N=1,box=data.boxdim(L=10**(1./3.))) system = init.read_snapshot(snap) # test mesh order parameter from hoomd import metadynamics meta = metadynamics.integrate.mode_metadynamics(dt=0.005, mode='well_tempered', stride=1,deltaT=1,W=1) md.integrate.nve(group=group.all()) density = metadynamics.cv.density(group=group.all(),sigma=0.25) density.set_grid(cv_min=0,cv_max=1,num_points=20) aspect = metadynamics.cv.aspect_ratio(sigma=0.1,dir1=0,dir2=1) aspect.set_grid(cv_min=0,cv_max=2,num_points=30) meta.dump_grid('bias.dat',period=1) meta.set_params(multiple_walkers=True) run(1) system.box = system.box.scale(s=0.125**(1./3.)) run(1) with context.initialize(): snap = data.make_snapshot(N=1,box=data.boxdim(L=10**(1./3.))) system = init.read_snapshot(snap) # test mesh order parameter from hoomd import metadynamics meta = metadynamics.integrate.mode_metadynamics(dt=0.005, mode='well_tempered', stride=1,deltaT=1,W=1) md.integrate.nve(group=group.all()) density = metadynamics.cv.density(group=group.all(),sigma=0.25) density.set_grid(cv_min=0,cv_max=1,num_points=20) aspect = metadynamics.cv.aspect_ratio(sigma=0.1,dir1=0,dir2=1) aspect.set_grid(cv_min=0,cv_max=2,num_points=30) meta.restart_from_grid('bias.dat_1') meta.dump_grid('bias_restart.dat',period=1) meta.set_params(multiple_walkers=True) system.box = system.box.scale(s=0.125**(1./3.)) run(1) <file_sep># -- start license -- # Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition # (HOOMD-blue) Open Source Software License Copyright 2008-2011 Ames Laboratory # Iowa State University and The Regents of the University of Michigan All rights # reserved. # HOOMD-blue may contain modifications ("Contributions") provided, and to which # copyright is held, by various Contributors who have granted The Regents of the # University of Michigan the right to modify and/or distribute such Contributions. # You may redistribute, use, and create derivate works of HOOMD-blue, in source # and binary forms, provided you abide by the following conditions: # * Redistributions of source code must retain the above copyright notice, this # list of conditions, and the following disclaimer both in the code and # prominently in any materials provided with the distribution. # * Redistributions in binary form must reproduce the above copyright notice, this # list of conditions, and the following disclaimer in the documentation and/or # other materials provided with the distribution. # * All publications and presentations based on HOOMD-blue, including any reports # or published results obtained, in whole or in part, with HOOMD-blue, will # acknowledge its use according to the terms posted at the time of submission on: # http://codeblue.umich.edu/hoomd-blue/citations.html # * Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website: # http://codeblue.umich.edu/hoomd-blue/ # * Apart from the above required attributions, neither the name of the copyright # holder nor the names of HOOMD-blue's contributors may be used to endorse or # promote products derived from this software without specific prior written # permission. # Disclaimer # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY # WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # -- end license -- <file_sep>#include "OrderParameterMesh.h" #ifndef __ORDER_PARAMETER_MESH_GPU_H__ #define __ORDER_PARAMETER_MESH_GPU_H__ #ifdef ENABLE_CUDA //#define USE_HOST_DFFT #include <hoomd/GPUFlags.h> #include <hoomd/md/CommunicatorGridGPU.h> #include <cufft.h> #ifdef ENABLE_MPI #ifndef USE_HOST_DFFT #include <hoomd/extern/dfftlib/src/dfft_cuda.h> #else #include <hoomd/extern/dfftlib/src/dfft_host.h> #endif #endif /*! Order parameter evaluated using the particle mesh method */ class OrderParameterMeshGPU : public OrderParameterMesh { public: //! Constructor OrderParameterMeshGPU(std::shared_ptr<SystemDefinition> sysdef, const unsigned int nx, const unsigned int ny, const unsigned int nz, const std::vector<Scalar> mode, const std::vector<int3> zero_modes = std::vector<int3>()); virtual ~OrderParameterMeshGPU(); protected: //! Helper function to setup FFT and allocate the mesh arrays virtual void initializeFFT(); //! Helper function to assign particle coordinates to mesh virtual void assignParticles(); //! Helper function to update the mesh arrays virtual void updateMeshes(); //! Helper function to interpolate the forces virtual void interpolateForces(); //! Helper function to calculate value of collective variable virtual Scalar computeCV(); //! Helper function to compute the virial virtual void computeVirial(); //! Compute maximum q vector virtual void computeQmax(unsigned int timestep); private: cufftHandle m_cufft_plan; //!< The FFT plan bool m_local_fft; //!< True if we are only doing local FFTs (not distributed) #ifdef ENABLE_MPI typedef CommunicatorGridGPU<cufftComplex> CommunicatorGridGPUComplex; std::shared_ptr<CommunicatorGridGPUComplex> m_gpu_grid_comm_forward; //!< Communicate mesh std::shared_ptr<CommunicatorGridGPUComplex> m_gpu_grid_comm_reverse; //!< Communicate fourier mesh dfft_plan m_dfft_plan_forward; //!< Forward distributed FFT dfft_plan m_dfft_plan_inverse; //!< Forward distributed FFT #endif GlobalArray<cufftComplex> m_mesh; //!< The particle density mesh GlobalArray<cufftComplex> m_fourier_mesh; //!< The fourier transformed mesh GlobalArray<cufftComplex> m_fourier_mesh_G; //!< Fourier transformed mesh times the influence function GlobalArray<cufftComplex> m_inv_fourier_mesh; //!< The inverse-fourier transformed force mesh Index2D m_bin_idx; //!< Total number of bins GlobalArray<Scalar4> m_particle_bins; //!< Cell list for particle positions and modes GlobalArray<Scalar> m_mesh_scratch; //!< Mesh with scratch space for density reduction Index2D m_scratch_idx; //!< Indexer for scratch space GlobalArray<unsigned int> m_n_cell; //!< Number of particles per cell unsigned int m_cell_size; //!< Current max. number of particles per cell GPUFlags<unsigned int> m_cell_overflowed; //!< Flag set to 1 if a cell overflows GPUFlags<Scalar> m_sum; //!< Sum over fourier mesh values GlobalArray<Scalar> m_sum_partial; //!< Partial sums over fourier mesh values GlobalArray<Scalar> m_sum_virial_partial; //!< Partial sums over virial mesh values GlobalArray<Scalar> m_sum_virial; //!< Final sum over virial mesh values unsigned int m_block_size; //!< Block size for fourier mesh reduction GPUFlags<Scalar4> m_gpu_q_max; //!< Return value for maximum Fourier mode reduction GlobalArray<Scalar4> m_max_partial; //!< Scratch space for reduction of maximum Fourier amplitude }; //! Define plus operator for complex data type (only need to compile by CommunicatorMesh base class) inline cufftComplex operator + (cufftComplex& lhs, cufftComplex& rhs) { cufftComplex res; res.x = lhs.x + rhs.x; res.y = lhs.y + rhs.y; return res; } //! Define plus operator for Scalar4 data type (only need to compile by CommunicatorMesh base class) inline Scalar4 operator + (Scalar4& lhs, Scalar4& rhs) { Scalar4 res; res.x = lhs.x + rhs.x; res.y = lhs.y + rhs.y; res.z = lhs.z + rhs.z; res.w = lhs.w + rhs.w; return res; } void export_OrderParameterMeshGPU(pybind11::module& m); #endif // ENABLE_CUDA #endif // __ORDER_PARAMETER_MESH_GPU_H__ <file_sep>/*! \file IndexGrid.cc * \brief Implements the IndexGrid class */ #include "IndexGrid.h" #include <assert.h> IndexGrid::IndexGrid() { m_lengths.resize(1); m_factors.resize(1); m_lengths[0] = 0; m_factors[0] = 1; } IndexGrid::IndexGrid(const std::vector<unsigned int>& lengths) { setLengths(lengths); } void IndexGrid::setLengths(const std::vector<unsigned int>& lengths) { m_lengths.resize(lengths.size()); m_factors.resize(lengths.size()); m_lengths = lengths; for (unsigned int i = 0; i < m_lengths.size(); i++) { m_factors[i] = (i == 0) ? 1 : ( m_lengths[i-1] * m_factors[i-1] ); } } unsigned int IndexGrid::getIndex(const std::vector<unsigned int>& coords) { assert(coords.size() == m_lengths.size()); unsigned int idx = 0; for (unsigned int i = 0; i < m_lengths.size(); i++) { idx += coords[i] * m_factors[i]; } return idx; } void IndexGrid::getCoordinates(const unsigned int idx, std::vector<unsigned int>& coords) { assert(coords.size() == m_lengths.size()); unsigned int rest = idx; for (int i = m_lengths.size()-1; i >= 0; i--) { coords[i] = rest/m_factors[i]; rest -= coords[i]*m_factors[i]; } assert(rest == 0); } unsigned int IndexGrid::getNumElements() { unsigned int res = 1; for (unsigned int i = 0; i < m_lengths.size(); i++) res *= m_lengths[i]; return res; } unsigned int IndexGrid::getLength(const unsigned int i) { assert(m_lengths.size() > i); return m_lengths[i]; } unsigned int IndexGrid::getDimension() { return m_lengths.size(); } <file_sep>// Include the defined classes that are to be exported to python #include "IntegratorMetaDynamics.h" #include "CollectiveVariable.h" #include "LamellarOrderParameter.h" #include "AspectRatio.h" #include "OrderParameterMesh.h" #include "WellTemperedEnsemble.h" #include "CollectiveWrapper.h" #include "SteinhardtQl.h" #include "Density.h" #ifdef ENABLE_CUDA #include "LamellarOrderParameterGPU.h" #include "OrderParameterMeshGPU.h" #endif #include <hoomd/extern/pybind/include/pybind11/pybind11.h> #include <hoomd/extern/pybind/include/pybind11/stl_bind.h> // specify the python module. Note that the name must expliclty match the PROJECT() name provided in CMakeLists // (with an underscore in front) PYBIND11_MODULE(_metadynamics, m) { pybind11::bind_vector<std::vector<int3 >>(m, "std_vector_int3"); export_CollectiveVariable(m); export_IntegratorMetaDynamics(m); export_LamellarOrderParameter(m); export_AspectRatio(m); export_OrderParameterMesh(m); export_WellTemperedEnsemble(m); export_CollectiveWrapper(m); export_SteinhardtQl(m); export_Density(m); #ifdef ENABLE_CUDA export_LamellarOrderParameterGPU(m); export_OrderParameterMeshGPU(m); #endif } <file_sep>#ifndef __STEINHARDT_QL_H__ #define __STEINHARDT_QL_H__ /*! \file SteinhardtQl.h \brief Declares the SteinhardtQl abstract class */ #include "CollectiveVariable.h" #include <complex> #include <hoomd/md/NeighborList.h> class SteinhardtQl : public CollectiveVariable { public: SteinhardtQl(std::shared_ptr<SystemDefinition> sysdef, Scalar rcut, Scalar ron, unsigned int lmax, std::shared_ptr<NeighborList> nlist, unsigned int type, const std::vector<Scalar>& Ql_ref, const std::string& log_suffix=""); virtual ~SteinhardtQl() {} /*! Returns the current value of the collective variable * \param timestep The currnt value of the timestep */ virtual Scalar getCurrentValue(unsigned int timestep) { this->computeCV(timestep); return m_value; } /*! Returns the names of provided log quantities. */ virtual std::vector<std::string> getProvidedLogQuantities() { std::vector<std::string> list = CollectiveVariable::getProvidedLogQuantities(); list.push_back("cv_steinhardt"); for (unsigned int l = 1; l <= m_lmax; l++) { list.push_back("steinhardt_Q"+std::to_string(l)); } return list; } /*! Returns the value of a specific log quantity. * \param quantity The name of the quantity to return the value of * \param timestep The current value of the time step */ Scalar getLogValue(const std::string& quantity, unsigned int timestep) { if (quantity == "cv_steinhardt") { this->computeCV(timestep); return m_value; } for (unsigned int l = 1; l <= m_lmax; ++l) { if (quantity == "steinhardt_Q"+std::to_string(l)) { this->computeCV(timestep); return m_Ql[l-1]; } } // nothing found? ask parent class return CollectiveVariable::getLogValue(quantity, timestep); } // compute the collective variable void computeCV(unsigned int teimstep); protected: /*! Compute the biased forces for this collective variable. The force that is written to the force arrays must be multiplied by the bias factor. \param timestep The current value of the time step */ virtual void computeBiasForces(unsigned int timestep); private: Scalar m_rcutsq; //! Cutoff Scalar m_ronsq; //!< Onset of smoothing unsigned int m_lmax; //!< Maxiumum l of spherical harmonics std::shared_ptr<NeighborList> m_nlist; //!< The neighbor list unsigned int m_type; //!< Particle type to compute order parameter for unsigned int m_cv_last_updated; //!< Last updated timestep bool m_have_computed; //!< True if we have computed the CV at least once std::vector<Scalar> m_Ql; //!< List of computed Ql, up to lmax std::vector<std::complex<Scalar> > m_Qlm; //!< List of Qlm, accumulated over all particles std::vector<Scalar> m_Ql_ref; //!< List of reference Ql std::string m_prof_name; //!< Name for profiling Scalar m_value; //!< Value of the collective variable }; //! Export the SteinhardtQl class to python void export_SteinhardtQl(pybind11::module& m); #endif // __STEINHARDT_QL_H__ <file_sep>#include "AspectRatio.h" namespace py = pybind11; AspectRatio::AspectRatio(std::shared_ptr<SystemDefinition> sysdef, const unsigned int dir1, const unsigned int dir2) : CollectiveVariable(sysdef, "cv_aspect_ratio"), m_dir1(dir1), m_dir2(dir2) { if (dir1==dir2 || dir1 >= 3 || dir2 >= 3) { m_exec_conf->msg->error() << "metadynamics.aspect_ratio: Invalid directions given." << std::endl; throw std::runtime_error("Error setting up metadynamics.aspect_ratio"); } // reset force and virial ArrayHandle<Scalar4> h_force(m_force, access_location::host, access_mode::overwrite); ArrayHandle<Scalar> h_virial(m_virial, access_location::host, access_mode::overwrite); memset(h_force.data, 0, sizeof(Scalar4)*m_force.getNumElements()); memset(h_virial.data, 0, sizeof(Scalar)*m_virial.getNumElements()); m_log_name = m_cv_name; } Scalar AspectRatio::getCurrentValue(unsigned int timestep) { Scalar3 L = m_pdata->getGlobalBox().getL(); Scalar length1(0.0), length2(0.0); switch(m_dir1) { case 0: length1 = L.x; break; case 1: length1 = L.y; break; case 2: length1 = L.z; break; } switch(m_dir2) { case 0: length1 = L.x; break; case 1: length2 = L.y; break; case 2: length2 = L.z; break; } return length1/length2; } void AspectRatio::computeBiasForces(unsigned int timestep) { #ifdef ENABLE_MPI // only add contribution to external virial once (on root processor) if (m_exec_conf->getRank()) return; #endif const BoxDim& global_box = m_pdata->getGlobalBox(); Scalar3 L = global_box.getL(); Scalar d_l_x(0.0), d_l_y(0.0), d_l_z(0.0); switch(m_dir1) { case 0: switch(m_dir2) { case 1: d_l_x = Scalar(1.0)/L.y; d_l_y = -L.x/L.y/L.y; d_l_z = Scalar(0.0); break; case 2: d_l_x = Scalar(1.0)/L.z; d_l_y = Scalar(0.0); d_l_z = -L.x/L.z/L.z; break; } break; case 1: switch(m_dir2) { case 0: d_l_x = -L.y/L.x/L.x; d_l_y = Scalar(1.0)/L.x; d_l_z = Scalar(0.0); break; case 2: d_l_x = Scalar(0.0); d_l_y = Scalar(1.0)/L.z; d_l_z = -L.y/L.z/L.z; break; } break; case 2: switch(m_dir2) { case 0: d_l_x = -L.z/L.x/L.x; d_l_y = Scalar(0.0); d_l_z = Scalar(1.0)/L.x; break; case 1: d_l_x = Scalar(0.0); d_l_y = -L.z/L.y/L.y; d_l_z = Scalar(1.0)/L.y; break; } break; } Scalar xy = global_box.getTiltFactorXY(); Scalar xz = global_box.getTiltFactorXZ(); Scalar yz = global_box.getTiltFactorYZ(); m_external_virial[0] = - m_bias*d_l_x * L.x; // xx m_external_virial[1] = - m_bias*d_l_x * (L.y * xy); // xy m_external_virial[2] = - m_bias*d_l_x * (L.z * xz); // xz m_external_virial[3] = - m_bias*d_l_y * L.y; // yy m_external_virial[4] = - m_bias*d_l_y * (L.z * yz); // yz m_external_virial[5] = - m_bias*d_l_z * L.z; // zz } void export_AspectRatio(py::module& m) { py::class_<AspectRatio, std::shared_ptr<AspectRatio> >(m, "AspectRatio", py::base<CollectiveVariable>() ) .def(py::init< std::shared_ptr<SystemDefinition>, const unsigned int, const unsigned int >() ); ; } <file_sep>#ifndef __COLLECTIVE_VARIABLE_H__ #define __COLLECTIVE_VARIABLE_H__ /*! \file CollectiveVariable.h \brief Declares the CollectiveVariable abstract class */ #include <hoomd/ForceCompute.h> #include <hoomd/extern/pybind/include/pybind11/pybind11.h> #include <string.h> /*! Abstract interface for a collective variable All C++ implementations of collective variables inherit from this class. A CollectiveVariable is an extension of a ForceCompute, and can compute forces. The force generated by a collective variable (i.e. its negative derivative with respect to particle positions) must be multiplied by a bias factor (the partial derivative of the biasing potential with respect to the collective variable). The bias factor is set using the method setBiasFactor(). Collective variables should have a potential energy of zero, since they are not directly added to the Hamiltonian (only via the biasing potential). Instead, the value of the collective variable can be queried using getCurrentValue(). */ class CollectiveVariable : public ForceCompute { public: enum umbrella_Enum { no_umbrella = 0, //!< no umbrella potential linear, //!< energy linear in the collective variable harmonic, //!< a harmonic umbrella potential wall, //!< soft wall umbrella potential gaussian //!< Gaussian umbrella potential }; /*! Constructs a collective variable \param sysdef The system definition \param name The name of this collective variable */ CollectiveVariable(std::shared_ptr<SystemDefinition> sysdef, const std::string& name); virtual ~CollectiveVariable() {} /*! Returns the current value of the collective variable * \param timestep The currnt value of the timestep */ virtual Scalar getCurrentValue(unsigned int timestep) { return Scalar(0.0); } /*! Set the current value of the bias factor. This routine has to be called before force evaluation by the integrator. \param bias The value that multiplies the force */ virtual void setBiasFactor(Scalar bias) { m_bias = bias; } /*! Evaluate a harmonic potential function of the collective variable * \param harmonic True if harmonic potential should be active */ void setUmbrella(umbrella_Enum umbrella) { m_umbrella = umbrella; if (umbrella==no_umbrella) m_bias=Scalar(0.0); } /*! Set spring constant for harmonic potential * \param kappa Spring constant (in units of the collective variable) */ void setKappa(Scalar kappa) { m_kappa = kappa; } /*! Set width of flat region of umbrella potential * \param width Width of flat region (in units of collective variable) */ void setWidthFlat(Scalar width) { m_width_flat= width; } /*! Set prefactor of umbrella potential *! \param scale Multiplicative scale factor */ void setScale(Scalar scale) { m_scale = scale; } /*! Set minimum position of harmonic potential * \param cv0 Minimum position (units of c.v.) */ void setMinimum(Scalar cv0) { m_cv0 = cv0; } /*! Returns the name of the collective variable */ std::string getName() { return m_cv_name; } /*! Computes the derivative of the collective variable w.r.t. the particle coordinates * and stores them in the force array. */ void computeDerivatives(unsigned int timestep) { m_bias = Scalar(1.0); computeBiasForces(timestep); } /*! Returns true if the collective variable can compute derivatives * w.r.t. particle coordinates */ virtual bool canComputeDerivatives() { return true; } /*! Returns the value of the harmonic umbrella potential * \param timestep */ Scalar getUmbrellaPotential(unsigned int timestep); /*! Returns true if the evaluation of this variable depends on the evaluation * of the other variables */ virtual bool requiresNetForce() { return false; } /*! Returns the names of provided log quantities. */ virtual std::vector<std::string> getProvidedLogQuantities() { std::vector<std::string> list = ForceCompute::getProvidedLogQuantities(); list.push_back("umbrella_energy_"+m_cv_name); return list; } /*! Returns the value of a specific log quantity. * \param quantity The name of the quantity to return the value of * \param timestep The current value of the time step */ Scalar getLogValue(const std::string& quantity, unsigned int timestep) { if (quantity == "umbrella_energy_"+m_cv_name) { return getUmbrellaPotential(timestep); } // nothing found? m_exec_conf->msg->error() << "cv.*: Invalid log quantity " << quantity << std::endl; throw std::runtime_error("Error querying log quantity"); } protected: /*! \param timestep The current value of the time step */ void computeForces(unsigned int timestep); /*! Compute the biased forces for this collective variable. The force that is written to the force arrays must be multiplied by the bias factor. \param timestep The current value of the time step */ virtual void computeBiasForces(unsigned int timestep) { }; Scalar m_bias; //!< The bias factor multiplying the force std::string m_cv_name; //!< Name of the collective variable private: umbrella_Enum m_umbrella; //!< Type of umbrella potential to evalaute Scalar m_cv0; //!< Minimum position of umbrella tential Scalar m_kappa; //!< Stiffness of umbrella potential Scalar m_width_flat; //!< Region where the umbrella potential is flat Scalar m_scale; //!< Prefactor of umbrella potential }; //! Export the CollectiveVariable class to python void export_CollectiveVariable(pybind11::module& m); #endif // __COLLECTIVE_VARIABLE_H__ <file_sep>#ifndef __INTEGRATOR_METADYNAMICS_H__ #define __INTEGRATOR_METADYNAMICS_H__ #include "CollectiveVariable.h" #include "IndexGrid.h" #include <hoomd/md/IntegratorTwoStep.h> #include <hoomd/extern/pybind/include/pybind11/pybind11.h> /*! \file IntegratorMetaDynamics.h \brief Declares the IntegratorMetaDynamics class */ //! Structure to hold information about a collective variable struct CollectiveVariableItem { std::shared_ptr<CollectiveVariable> m_cv; //!< The collective variable Scalar m_sigma; //!< Width of compensating gaussians for this variable Scalar m_cv_min; //!< Minium value of collective variable (if using grid) Scalar m_cv_max; //!< Maximum value of collective variable (if using grid) unsigned int m_num_points; //!< Number of grid points for this collective variable }; //! Implements a metadynamics update scheme /*! This class implements an integration scheme for metadynamics. For a review of metadynamics, a free-energy measurement technique, see Barducci et al., Metadynamics, Wiley Interdiscipl. Rev.: Comput. Mol. Sci. 5, pp. 826-843 (2011). Some of the features of this class are loosely inspired by the PLUMED plugin for Metadynamics, http://www.plumed-code.org/. The IntegratorMetaDynamics class takes a number of CollectiveVariables, and uses their values during the course of the simulation to update the bias potential, a sum of Gaussians, which disfavors revisiting visited states. The derivative of the bias potential (with respect to the collective coordinate) in turn multiplies the force on the particles as defined by the collective variable. The bias potential is updated every stride steps. Well-tempered metadynamics is supported by default, a value of T_shift defines the temperature shift entering the scaling factor for the bias potential (see above ref. for details). Very large values of T_shift correspond to standard metadynamics, T_shift->0 corresponds to standard molecular dynamics. Two modes of operation are supported: in the first mode, the Gaussians are resummed every time step. With increasing simulation time, this process will take longer, and slow down the simulation. In the second mode, a grid mode, a current grid of values of the collective variables is maintained and updated whenever a new Gaussian is deposited. The value of the bias potential and its derivatives of the potential are calculated by using numerical interpolation. In this mode, the time per step is O(1), so this mode is preferrable for long simulations. It is possible to output the grid after the simulation, and to restart from the grid file. It is also possible to restart from the grid file and turn off the deposition of new Gaussians, e.g. to equilibrate the system in the bias potential landscape and measure the histogram of the collective variable, to correct for errors. */ class IntegratorMetaDynamics : public IntegratorTwoStep { public: enum Enum { mode_standard, mode_well_tempered, }; /*! Constructor \param sysdef System definition \param deltaT Time step \param W Weight of Gaussians (multiplicative factor) \param T_shift Temperature shift for well-tempered metadynamics \param T Temperature for adaptive Gaussian metadynamics \param stride Number of time steps between deposition of Gaussians \param add_bias True if new Gaussians should be added during the simulation \param filename Name of file to output hill information to \param overwrite True f the file should be overwritten when it exists already \param use_grid True if grid should be used \param mode The variant of metadynamics to use */ IntegratorMetaDynamics(std::shared_ptr<SystemDefinition> sysdef, Scalar deltaT, Scalar W, Scalar T_shift, Scalar T, unsigned int stride, bool add_bias = true, const std::string& filename = "", bool overwrite = false, const Enum mode = mode_standard ); virtual ~IntegratorMetaDynamics() {} /*! Sample collective variables, update bias potential and derivatives \param timestep The current value of the timestep */ virtual void update(unsigned int timestep); /*! Prepare for the run \param timestep The current value of the timestep */ virtual void prepRun(unsigned int timestep); /*! Output statistics at end of run (unimplemented as of now) */ virtual void printStats() {}; /*! Register a new collective variable \param cv The collective variable \param sigma The standard deviation of Gaussians for this collective variable \param cv_min Minimum value, if using grid \param cv_max Maximum value, if using grid \param num_points Number of grid points to use for interpolation */ void registerCollectiveVariable(std::shared_ptr<CollectiveVariable> cv, Scalar sigma, Scalar cv_min=Scalar(0.0), Scalar cv_max=Scalar(0.0), int num_points=0) { assert(cv); assert(sigma > 0); CollectiveVariableItem cv_item; cv_item.m_cv = cv; cv_item.m_sigma = sigma; cv_item.m_cv_min = cv_min; cv_item.m_cv_max = cv_max; cv_item.m_num_points = (unsigned int) num_points; m_variables.push_back(cv_item); } /*! Remove all collective variables */ void removeAllVariables() { m_variables.clear(); } /*! Returns the names of log quantitites provided by this integrator */ std::vector< std::string > getProvidedLogQuantities() { std::vector< std::string> ret = m_log_names; std::vector< std::string> q = Integrator::getProvidedLogQuantities(); ret.insert(ret.end(), q.begin(), q.end()); return ret; } /*! Obtain the value of a specific log quantity \param quantity The quantity to obtain the value of \param timestep The current value of the time step */ Scalar getLogValue(const std::string& quantity, unsigned int timestep) { // check if log quantity exists in base class std::vector< std::string> q = Integrator::getProvidedLogQuantities(); std::vector< std::string >::iterator it; for (it = q.begin(); it != q.end(); it++) if (quantity == *it) return Integrator::getLogValue(quantity, timestep); if (quantity == m_log_names[0]) { return m_curr_bias_potential; } else if (quantity == m_log_names[1]) { return sigmaDeterminant(); } else if (quantity == m_log_names[2]) { return m_curr_reweight; } else { // default: throw exception std::cerr << std::endl << "***Error! " << quantity << " is not a valid log quantity for IntegratorMetaDynamics" << std::endl << std::endl; throw std::runtime_error("Error getting log value"); } } /*! Set up grid interpolation \param use_grid True if the grid is to be used */ void setGrid(bool use_grid); /*! Set metadynamics mode \param mode The variant of metadynamics to be used */ void setMode(Enum mode) { m_mode = mode; } /*! Set bias deposition stride \param stride The stride with which the bias potential is updated */ void setStride(unsigned int stride) { m_stride = stride; } /*! Returns true if the integration has been initialized (i.e. the simulation has been run at least once) */ bool isInitialized() { return m_is_initialized; } /*! Output the grid to a file \param filename1 Name of first file to dump grid to \param filename2 Name of second file to dump grid to \param period Number of timesteps between dumps */ void dumpGrid(const std::string& filename1, const std::string& filename2, unsigned int period); /*! Restart from a grid file. Upon running the simulation, the information will be read in. \param filename The name of the file that contains the grid information */ void restartFromGridFile(const std::string &filename) { m_restart_filename = filename; } /*! Set a flag that controls deposition of new Gaussian hills \param add_bias True if hills should be generated during the simulation */ void setAddHills(bool add_bias) { m_add_bias = add_bias; } /*! Enable/disable adaptive Gaussians * \param adpative True if adaptive Gaussians should be enabled */ void setAdaptive(bool adaptive) { m_adaptive = adaptive; } /*! Set the estimate of the MSD of the particle positions (between two update steps) \param sigma_g The particle MSD */ void setSigmaG(Scalar sigma_g) { m_sigma_g = sigma_g; } /*! Set multiple walker mode * \param multiple Multiple walker flag */ void setMultipleWalkers(bool multiple) { m_multiple_walkers = multiple; } //! Reset the histogram void resetHistogram(); private: Scalar m_W; //!< Height of Gaussians Scalar m_T_shift; //!< Temperature shift unsigned int m_stride; //!< Number of timesteps between Gaussian depositions std::vector<CollectiveVariableItem> m_variables; //!< The list of collective variables std::vector<std::vector<Scalar> > m_cv_values; //!< History of CV values unsigned int m_num_update_steps; //!< Number of update steps performed in this run thus far unsigned int m_num_gaussians; //!< Number of Gaussians deposited std::vector<std::string> m_log_names; //!< Names of logging quantities std::string m_suffix; //!< Suffix for unbiased variables Scalar m_curr_bias_potential; //!< The sum of Gaussians std::vector<Scalar> m_bias_potential; //!< List of values of the bias potential bool m_is_initialized; //!< True if history-dependent potential has been initialized bool m_histograms_initialized; //!< True if histograms have been set up const std::string m_filename; //!< Name of output file bool m_overwrite; //!< True if the file should be overwritten bool m_is_appending; //!< True if we are appending to the file std::ofstream m_file; //!< Output log file std::string m_delimiter; //!< Delimiting string bool m_use_grid; //!< True if we are using a grid GPUArray<Scalar> m_grid; //!< d-dimensional grid to store values of bias potential GPUArray<Scalar> m_grid_delta; //!< d-dimensional grid to store increments of bias potential IndexGrid m_grid_index; //!< Indexer for the d-dimensional grid bool m_add_bias; //!< True if hills should be added during the simulation std::string m_restart_filename; //!< Name of file to read restart information from std::string m_grid_fname1; //!< File name for first file of periodic dumping of grid std::string m_grid_fname2; //!< File name for second file of periodic dumping of grid unsigned int m_grid_period; //!< Number of timesteps between dumping of grid data unsigned int m_cur_file; //!< Current index of file we are accessing (0 or 1) GPUArray<unsigned int> m_lengths; //!< Grid dimensions in every direction GPUArray<Scalar> m_cv_min; //!< Minimum grid values per CV GPUArray<Scalar> m_cv_max; //!< Maximum grid values per CV GPUArray<Scalar> m_sigma_inv; //!< Square matrix of Gaussian standard deviations (inverse) GPUArray<Scalar> m_sigma_grid; //!< Gaussian volume as function of the collective ariables GPUArray<Scalar> m_sigma_grid_delta; //!< Gaussian volume as function of the collective ariables, increments GPUArray<unsigned int> m_grid_hist_gauss; //!< Number of Gaussians deposited at every grid point GPUArray<unsigned int> m_grid_hist_gauss_delta; //!< Increments in number of Gaussians GPUArray<unsigned int> m_grid_hist; //!< Number of times a state has been visited GPUArray<unsigned int> m_grid_hist_delta; //!< Deltas of histogram GPUArray<Scalar> m_current_val; //!< Current CV values array Scalar m_sigma_g; //!< Estimated standard deviation of particle displacements bool m_adaptive; //!< True if adaptive Gaussians should be used Scalar m_temp; //!< Temperature for adaptive Gaussians Enum m_mode; //!< The variant of metadynamics being used bool m_multiple_walkers; //!< True if multiple walkers are used Scalar m_curr_reweight; //!< Current weight to reconstruct unbiased Boltzmann distribution #ifdef ENABLE_MPI MPI_Comm m_partition_comm; //!< MPI communicator between partitions #endif GPUArray<Scalar> m_grid_reweighted; //!< Reweighted estimator for the CV distribution GPUArray<Scalar> m_grid_weight; //!< Accumulated reweighting factors //! Internal helper function to update the bias potential void updateBiasPotential(unsigned int timestep); //! Helper function to open output file for logging void openOutputFile(); //! Helper function to write file header void writeFileHeader(); //! Helper function to initialize the grid void setupGrid(); //! Helper function to get value of bias potential by multilinear interpolation /* \param reweight If true, interpolate grid of reweighting factors */ Scalar interpolateGrid(const std::vector<Scalar>& val, bool reweight); //! Helper function to calculate the partial derivative of the bias potential in direction cv Scalar biasPotentialDerivative(unsigned int cv, const std::vector<Scalar>& val); //! Helper function to read in data from grid file void readGrid(const std::string& filename); //! Helper function to write grid data void writeGrid(const std::string& filename, unsigned int timestep); //! Helper function to update the grid values void updateGrid(std::vector<Scalar>& current_val, Scalar scal); #ifdef ENABLE_CUDA void updateGridGPU(std::vector<Scalar>& current_val, Scalar scal); #endif //! Compute sigma matrix void computeSigma(); //! Compute determinant of sigma matrix Scalar sigmaDeterminant(); //! Update the grid of sigma values void updateSigmaGrid(std::vector<Scalar>& current_val); //! Update histogram of collective variable void updateHistogram(std::vector<Scalar>& current_val); //! Update reweighted estimator CV histogram void updateReweightedEstimator(std::vector<Scalar>& current_val); }; //! Export to python void export_IntegratorMetaDynamics(pybind11::module& m); #endif // __INTEGRATOR_METADYNAMICS_H__ <file_sep>#ifndef __ORDER_PARAMETER_MESH_H__ #define __ORDER_PARAMETER_MESH_H__ #include "CollectiveVariable.h" #include <hoomd/md/CommunicatorGrid.h> #ifdef ENABLE_MPI #include <hoomd/extern/dfftlib/src/dfft_host.h> #endif #include <hoomd/extern/kiss_fftnd.h> /*! Order parameter evaluated using the particle mesh method */ class OrderParameterMesh : public CollectiveVariable { public: //! Constructor OrderParameterMesh(std::shared_ptr<SystemDefinition> sysdef, const unsigned int nx, const unsigned int ny, const unsigned int nz, const std::vector<Scalar> mode, const std::vector<int3> zero_modes = std::vector<int3>()); virtual ~OrderParameterMesh(); Scalar getCurrentValue(unsigned int timestep); /*! Returns the names of provided log quantities. */ std::vector<std::string> getProvidedLogQuantities() { std::vector<std::string> list = CollectiveVariable::getProvidedLogQuantities(); for (std::vector<std::string>::iterator it = m_log_names.begin(); it != m_log_names.end(); ++it) { list.push_back(*it); } return list; } /*! Returns the value of a specific log quantity. * \param quantity The name of the quantity to return the value of * \param timestep The current value of the time step */ Scalar getLogValue(const std::string& quantity, unsigned int timestep); /*! Set the convolution kernel table * \param K convolution kernel as function of k * \param d_K derivative of convolution kernel * \param kmin Minimum wave vector for table * \param kmax Maximum wave vector for table */ void setTable(const std::vector<Scalar> &K, const std::vector<Scalar> &d_K, Scalar kmin, Scalar kmax); /*! Set flag whether to use a convolution kernel table */ void setUseTable(bool use_table) { m_use_table = use_table; } protected: /*! Compute the biased forces for this collective variable. The force that is written to the force arrays must be multiplied by the bias factor. \param timestep The current value of the time step */ void computeBiasForces(unsigned int timestep); Scalar3 m_mesh_size; //!< The dimensions of a single cell along every coordinate uint3 m_mesh_points; //!< Number of sub-divisions along one coordinate uint3 m_n_ghost_cells; //!< Number of ghost cells along every axis uint3 m_grid_dim; //!< Grid dimensions (including ghost cells) Scalar3 m_ghost_width; //!< Dimensions of the ghost layer unsigned int m_ghost_offset; //!< Offset in mesh due to ghost cells unsigned int m_n_cells; //!< Total number of inner cells unsigned int m_radius; //!< Stencil radius (in units of mesh size) unsigned int m_n_inner_cells; //!< Number of inner mesh points (without ghost cells) GlobalArray<Scalar> m_mode; //!< Per-type scalar multiplying density ("charges") Scalar m_mode_sq; //!< Sum of squared mode amplitudes GlobalArray<Scalar> m_inf_f; //!< Fourier representation of the influence function (real part) GlobalArray<Scalar> m_interpolation_f; //!< Fourier representation of the interpolation function GlobalArray<Scalar3> m_k; //!< Mesh of k values Scalar m_qstarsq; //!< Short wave length cut-off squared for density harmonics bool m_is_first_step; //!< True if we have not yet computed the influence function unsigned int m_cv_last_updated; //!< Timestep of last update of collective variable bool m_box_changed; //!< True if box has changed since last compute Scalar m_cv; //!< Current value of collective variable GlobalArray<Scalar> m_virial_mesh; //!< k-space mesh of virial tensor values unsigned int m_q_max_last_computed; //!< Last time step at which q max was computed Scalar3 m_q_max; //!< Current wave vector with maximum amplitude Scalar m_sq_max; //!< Maximum structure factor GlobalArray<int3> m_zero_modes; //!< Fourier modes that should be zeroed Scalar m_k_min; //!< Minimum k of tabulated convolution kernel Scalar m_k_max; //!< Maximum k of tabulated convolution kernel Scalar m_delta_k; //!< Spacing between k values GlobalArray<Scalar> m_table; //!< Tabulated kernel GlobalArray<Scalar> m_table_d; //!< Tabulated kernel bool m_use_table; //!< Whether to use the tabulated kernel //! Helper function to be called when box changes void setBoxChange() { m_box_changed = true; } //! Helper function to setup the mesh indices void setupMesh(); //! Helper function to setup FFT and allocate the mesh arrays virtual void initializeFFT(); //! Compute the optimal influence function virtual void computeInfluenceFunction(); //! The TSC (triangular-shaped cloud) charge assignment function Scalar assignTSC(Scalar x); //! Derivative of the TSC (triangular-shaped cloud) charge assignment function Scalar assignTSCderiv(Scalar x); //! Fourier representation of the TSC (triangular-shaped cloud) charge assignment function Scalar assignTSCfourier(Scalar k); //! Helper function to assign particle coordinates to mesh virtual void assignParticles(); //! Helper function to update the mesh arrays virtual void updateMeshes(); //! Helper function to interpolate the forces virtual void interpolateForces(); //! Helper function to calculate value of collective variable virtual Scalar computeCV(); //! Helper function to compute the virial virtual void computeVirial(); //! Helper function to compute q vector with maximum amplitude virtual void computeQmax(unsigned int timestep); private: kiss_fftnd_cfg m_kiss_fft; //!< The FFT configuration kiss_fftnd_cfg m_kiss_ifft; //!< Inverse FFT configuration #ifdef ENABLE_MPI dfft_plan m_dfft_plan_forward; //!< Distributed FFT for forward transform dfft_plan m_dfft_plan_inverse; //!< Distributed FFT for inverse transform std::unique_ptr<CommunicatorGrid<kiss_fft_cpx> > m_grid_comm_forward; //!< Communicator for charge mesh std::unique_ptr<CommunicatorGrid<kiss_fft_cpx> > m_grid_comm_reverse; //!< Communicator for inv fourier mesh #endif bool m_kiss_fft_initialized; //!< True if a local KISS FFT has been set up GlobalArray<kiss_fft_cpx> m_mesh; //!< The particle density mesh GlobalArray<kiss_fft_cpx> m_fourier_mesh; //!< The fourier transformed mesh GlobalArray<kiss_fft_cpx> m_fourier_mesh_G; //!< Fourier transformed mesh times the influence function GlobalArray<kiss_fft_cpx> m_inv_fourier_mesh; //!< The inverse-Fourier transformed mesh std::vector<std::string> m_log_names; //!< Name of the log quantity bool m_dfft_initialized; //! True if host dfft has been initialized //! Compute virial on mesh void computeVirialMesh(); //! Compute number of ghost cellso uint3 computeGhostCellNum(); }; void export_OrderParameterMesh(pybind11::module& m); #endif <file_sep>from hoomd.metadynamics import integrate from hoomd.metadynamics import cv <file_sep>/*! \file LamellarOrderParameterGPU.h * \brief Defines the LamellarOrderParameterGPU class */ #ifndef __LAMELLAR_ORDER_PARAMETER_GPU_H__ #define __LAMELLAR_ORDER_PARAMETER_GPU_H__ #include "LamellarOrderParameter.h" #ifdef ENABLE_CUDA //! Class to calculate the lamellar order parameter on the GPU class LamellarOrderParameterGPU : public LamellarOrderParameter { public: LamellarOrderParameterGPU(std::shared_ptr<SystemDefinition> sysdef, const std::vector<Scalar>& mode, const std::vector<int3>& lattice_vectors, const std::string& suffix = ""); virtual ~LamellarOrderParameterGPU() {} virtual void computeBiasForces(unsigned int timestep); protected: // calculates current CV value virtual void computeCV(unsigned int timestep); private: GPUArray<Scalar> m_gpu_mode; //!< Factors multiplying per-type densities to obtain scalar quantity unsigned int m_block_size; //!< Block size for fourier mode calculation GPUArray<Scalar2> m_fourier_mode_scratch; //!< Scratch memory for fourier mode calculation }; void export_LamellarOrderParameterGPU(pybind11::module& m); #endif #endif // __LAMELLAR_ORDER_PARAMETER_GPU_H__ <file_sep>#ifndef __INDEX_GRID_H__ #define __INDEX_GRID_H__ /*! \file IndexGrid.h \brief Defines the IndexGrid class */ #include <vector> //! Helper Class to cacluate a one-dimensional index for a d-dimensional grid class IndexGrid { public: //! Constructs an index for one-dimensional grid of length 1 IndexGrid(); //! Constructs an index for a d-dimensional grid of given lengths /*! \param lengths List of grid points in every direction */ IndexGrid(const std::vector<unsigned int>& lengths); virtual ~IndexGrid() {} //! Set the dimensions and lengths of the grid /*! \param lengths List of grid points in every direction */ void setLengths(const std::vector<unsigned int>& lengths); //! Get a grid index for given coordinates /*! \param coords Coordinates of the grid point in d dimensions * \returns The grid index */ unsigned int getIndex(const std::vector<unsigned int>& coords); //! Get the coordinates for a given grid index /*! \param idx The grid index * \param coords The grid coordinates (output variable) */ void getCoordinates(const unsigned int idx, std::vector<unsigned int>& coords); //! Returns the total number of grid elements unsigned int getNumElements(); //! Returns the length of the grid in a given direction /*! \param i Index of the direction */ unsigned int getLength(const unsigned int i); //! Returns the dimensionsality of the grid unsigned int getDimension(); private: std::vector<unsigned int> m_lengths; //!< Stores the lengths in every direction std::vector<unsigned int> m_factors; //!< Pre-calculated factors for converting between index and coordinates }; #endif // __INDEX_GRID_H__ <file_sep>/* \file LamellarOrderParameter.cc * \brief Implements the LamellarOrderParameter class */ #include "LamellarOrderParameter.h" namespace py = pybind11; LamellarOrderParameter::LamellarOrderParameter(std::shared_ptr<SystemDefinition> sysdef, const std::vector<Scalar>& mode, const std::vector<int3>& lattice_vectors, const std::string& suffix) : CollectiveVariable(sysdef, "cv_lamellar"), m_mode(mode), m_cv(0.0) { if (mode.size() != m_pdata->getNTypes()) { m_exec_conf->msg->error() << "cv.lamellar: Number of mode parameters has to equal the number of particle types!" << std::endl; throw std::runtime_error("Error initializing cv.lamellar"); } // allocate array of wave vectors GPUArray<int3> lattice_vectors_gpuarray(lattice_vectors.size(), m_exec_conf); m_lattice_vectors.swap(lattice_vectors_gpuarray); GPUArray<Scalar2> fourier_modes(lattice_vectors.size(), m_exec_conf); m_fourier_modes.swap(fourier_modes); m_cv_name += suffix; m_log_name = m_cv_name; // this collective variable does not contribute to the virial ArrayHandle<Scalar> h_virial(m_virial, access_location::host, access_mode::overwrite); memset(h_virial.data, 0, sizeof(Scalar)*6*m_virial.getPitch()); m_cv_last_updated = 0; // copy over lattice vectors ArrayHandle<int3> h_lattice_vectors(m_lattice_vectors, access_location::host, access_mode::overwrite); for (unsigned int k = 0; k < lattice_vectors.size(); k++) h_lattice_vectors.data[k] = lattice_vectors[k]; } void LamellarOrderParameter::computeCV(unsigned int timestep) { if (m_prof) m_prof->push("Lamellar"); calculateFourierModes(); ArrayHandle<Scalar2> h_fourier_modes(m_fourier_modes, access_location::host, access_mode::readwrite); unsigned int N = m_pdata->getNGlobal(); #ifdef ENABLE_MPI // reduce Fourier modes on on all processors if (m_pdata->getDomainDecomposition()) MPI_Allreduce(MPI_IN_PLACE,h_fourier_modes.data,m_fourier_modes.getNumElements(), MPI_HOOMD_SCALAR, MPI_SUM, m_exec_conf->getMPICommunicator()); #endif // Calculate value of collective variable (sum of real parts of fourier modes) Scalar sum = 0.0; for (unsigned k = 0; k < m_fourier_modes.getNumElements(); k++) { Scalar2 fourier_mode = h_fourier_modes.data[k]; sum += fourier_mode.x; } sum /= (Scalar) N; m_cv = sum; if (m_prof) m_prof->pop(); m_cv_last_updated = timestep; } void LamellarOrderParameter::computeBiasForces(unsigned int timestep) { if (m_prof) m_prof->push("Lamellar"); if (m_cv_last_updated < timestep || timestep == 0) computeCV(timestep); ArrayHandle<Scalar4> h_postype(m_pdata->getPositions(), access_location::host, access_mode::read); ArrayHandle<Scalar4> h_force(m_force, access_location::host, access_mode::overwrite); ArrayHandle<int3> h_lattice_vectors(m_lattice_vectors, access_location::host, access_mode::read); unsigned int N = m_pdata->getNGlobal(); Scalar denom = (Scalar)N; // compute reciprocal lattice vectors const BoxDim& global_box = m_pdata->getGlobalBox(); Scalar3 a1 = global_box.getLatticeVector(0); Scalar3 a2 = global_box.getLatticeVector(1); Scalar3 a3 = global_box.getLatticeVector(2); Scalar V_box = global_box.getVolume(); Scalar3 b1 = Scalar(2.0*M_PI)*make_scalar3(a2.y*a3.z-a2.z*a3.y, a2.z*a3.x-a2.x*a3.z, a2.x*a3.y-a2.y*a3.x)/V_box; Scalar3 b2 = Scalar(2.0*M_PI)*make_scalar3(a3.y*a1.z-a3.z*a1.y, a3.z*a1.x-a3.x*a1.z, a3.x*a1.y-a3.y*a1.x)/V_box; Scalar3 b3 = Scalar(2.0*M_PI)*make_scalar3(a1.y*a2.z-a1.z*a2.y, a1.z*a2.x-a1.x*a2.z, a1.x*a2.y-a1.y*a2.x)/V_box; for (unsigned int idx = 0; idx < m_pdata->getN(); idx++) { Scalar4 postype = h_postype.data[idx]; Scalar3 pos = make_scalar3(postype.x, postype.y, postype.z); unsigned int type = __scalar_as_int(postype.w); Scalar mode = m_mode[type]; Scalar4 force_energy = make_scalar4(0,0,0,0); for (unsigned int k = 0; k < m_lattice_vectors.getNumElements(); k++) { Scalar3 q = b1*(Scalar)h_lattice_vectors.data[k].x + b2*(Scalar)h_lattice_vectors.data[k].y + b3*(Scalar)h_lattice_vectors.data[k].z; Scalar dotproduct = dot(pos,q); Scalar f; f = Scalar(2.0)*mode*sin(dotproduct); force_energy.x += q.x*f; force_energy.y += q.y*f; force_energy.z += q.z*f; } force_energy.x *= m_bias; force_energy.y *= m_bias; force_energy.z *= m_bias; force_energy.x /= denom; force_energy.y /= denom; force_energy.z /= denom; h_force.data[idx] = force_energy; } if (m_prof) m_prof->pop(); } //! Returns a list of fourier modes (for all wave vectors) void LamellarOrderParameter::calculateFourierModes() { ArrayHandle<Scalar2> h_fourier_modes(m_fourier_modes, access_location::host, access_mode::overwrite); ArrayHandle<int3> h_lattice_vectors(m_lattice_vectors, access_location::host, access_mode::read); ArrayHandle<Scalar4> h_postype(m_pdata->getPositions(), access_location::host, access_mode::read); // compute reciprocal lattice vectors const BoxDim& global_box = m_pdata->getGlobalBox(); Scalar3 a1 = global_box.getLatticeVector(0); Scalar3 a2 = global_box.getLatticeVector(1); Scalar3 a3 = global_box.getLatticeVector(2); Scalar V_box = global_box.getVolume(); Scalar3 b1 = Scalar(2.0*M_PI)*make_scalar3(a2.y*a3.z-a2.z*a3.y, a2.z*a3.x-a2.x*a3.z, a2.x*a3.y-a2.y*a3.x)/V_box; Scalar3 b2 = Scalar(2.0*M_PI)*make_scalar3(a3.y*a1.z-a3.z*a1.y, a3.z*a1.x-a3.x*a1.z, a3.x*a1.y-a3.y*a1.x)/V_box; Scalar3 b3 = Scalar(2.0*M_PI)*make_scalar3(a1.y*a2.z-a1.z*a2.y, a1.z*a2.x-a1.x*a2.z, a1.x*a2.y-a1.y*a2.x)/V_box; for (unsigned int k = 0; k < m_lattice_vectors.getNumElements(); k++) { h_fourier_modes.data[k] = make_scalar2(0.0,0.0); Scalar3 q = b1*(Scalar)h_lattice_vectors.data[k].x + b2*(Scalar)h_lattice_vectors.data[k].y + b3*(Scalar)h_lattice_vectors.data[k].z; for (unsigned int idx = 0; idx < m_pdata->getN(); idx++) { Scalar4 postype = h_postype.data[idx]; Scalar3 pos = make_scalar3(postype.x, postype.y, postype.z); unsigned int type = __scalar_as_int(postype.w); Scalar mode = m_mode[type]; Scalar dotproduct = dot(q,pos); h_fourier_modes.data[k].x += mode * cos(dotproduct); h_fourier_modes.data[k].y += mode * sin(dotproduct); } } } Scalar LamellarOrderParameter::getLogValue(const std::string& quantity, unsigned int timestep) { if (quantity == m_log_name) { computeCV(timestep); return m_cv; } // nothing found, turn to base class return CollectiveVariable::getLogValue(quantity, timestep); } void export_LamellarOrderParameter(py::module& m) { py::class_<LamellarOrderParameter, std::shared_ptr<LamellarOrderParameter> >(m,"LamellarOrderParameter",py::base<CollectiveVariable>()) .def(py::init<std::shared_ptr<SystemDefinition>, const std::vector<Scalar>&, const std::vector<int3>, const std::string&>()); } <file_sep>#include "OrderParameterMesh.h" namespace py = pybind11; bool is_pow2(unsigned int n) { while (n && n%2 == 0) { n/=2; } return (n == 1); }; /*! \param sysdef The system definition \param nx Number of cells along first axis \param ny Number of cells along second axis \param nz Number of cells along third axis \param mode Per-type modes to multiply density */ OrderParameterMesh::OrderParameterMesh(std::shared_ptr<SystemDefinition> sysdef, const unsigned int nx, const unsigned int ny, const unsigned int nz, std::vector<Scalar> mode, std::vector<int3> zero_modes) : CollectiveVariable(sysdef, "mesh"), m_n_ghost_cells(make_uint3(0,0,0)), m_grid_dim(make_uint3(0,0,0)), m_ghost_width(make_scalar3(0,0,0)), m_n_cells(0), m_radius(1), m_n_inner_cells(0), m_is_first_step(true), m_cv_last_updated(0), m_box_changed(false), m_cv(Scalar(0.0)), m_q_max_last_computed(0), m_k_min(0.0), m_k_max(0.0), m_delta_k(0.0), m_use_table(false), m_kiss_fft_initialized(false), m_dfft_initialized(false) { if (mode.size() != m_pdata->getNTypes()) { m_exec_conf->msg->error() << "Number of modes unequal number of particle types." << std::endl << std::endl; throw std::runtime_error("Error setting up cv.mesh"); } GlobalArray<Scalar> mode_array(m_pdata->getNTypes(), m_exec_conf); m_mode.swap(mode_array); m_mode_sq = 0.0; ArrayHandle<Scalar> h_mode(m_mode, access_location::host, access_mode::overwrite); std::copy(mode.begin(), mode.end(), h_mode.data); GlobalArray<int3> zero_modes_array(zero_modes.size(), m_exec_conf); m_zero_modes.swap(zero_modes_array); ArrayHandle<int3> h_zero_modes(m_zero_modes, access_location::host, access_mode::overwrite); std::copy(zero_modes.begin(), zero_modes.end(), h_zero_modes.data); m_pdata->getBoxChangeSignal().connect<OrderParameterMesh, &OrderParameterMesh::setBoxChange>(this); m_mesh_points = make_uint3(nx, ny, nz); #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition()) { const Index3D& didx = m_pdata->getDomainDecomposition()->getDomainIndexer(); if (!is_pow2(m_mesh_points.x) || !is_pow2(m_mesh_points.y) || !is_pow2(m_mesh_points.z)) { m_exec_conf->msg->error() << "The number of mesh points along the every direction must be a power of two!" << std::endl; throw std::runtime_error("Error initializing cv.mesh"); } if (nx % didx.getW()) { m_exec_conf->msg->error() << "The number of mesh points along the x-direction ("<< nx <<") is not" << std::endl << "a multiple of the width (" << didx.getW() << ") of the processsor grid!" << std::endl << std::endl; throw std::runtime_error("Error initializing cv.mesh"); } if (ny % didx.getH()) { m_exec_conf->msg->error() << "The number of mesh points along the y-direction ("<< ny <<") is not" << std::endl << "a multiple of the height (" << didx.getH() << ") of the processsor grid!" << std::endl << std::endl; throw std::runtime_error("Error initializing cv.mesh"); } if (nz % didx.getD()) { m_exec_conf->msg->error() << "The number of mesh points along the z-direction ("<< nz <<") is not" << std::endl << "a multiple of the depth (" << didx.getD() << ") of the processsor grid!" << std::endl << std::endl; throw std::runtime_error("Error initializing cv.mesh"); } m_mesh_points.x /= didx.getW(); m_mesh_points.y /= didx.getH(); m_mesh_points.z /= didx.getD(); } m_ghost_offset = 0; #endif // ENABLE_MPI // reset virial ArrayHandle<Scalar> h_virial(m_virial, access_location::host, access_mode::overwrite); memset(h_virial.data, 0, sizeof(Scalar)*m_virial.getNumElements()); m_log_names.push_back("cv_mesh"); m_log_names.push_back("qx_max"); m_log_names.push_back("qy_max"); m_log_names.push_back("qz_max"); m_log_names.push_back("sq_max"); } OrderParameterMesh::~OrderParameterMesh() { if (m_kiss_fft_initialized) { free(m_kiss_fft); free(m_kiss_ifft); kiss_fft_cleanup(); } #ifdef ENABLE_MPI if (m_dfft_initialized) { dfft_destroy_plan(m_dfft_plan_forward); dfft_destroy_plan(m_dfft_plan_inverse); } #endif m_pdata->getBoxChangeSignal().disconnect<OrderParameterMesh, &OrderParameterMesh::setBoxChange>(this); } /*! \param K Table for the convolution kernel \param kmin Minimum k in the potential \param kmax Maximum k in the potential */ void OrderParameterMesh::setTable(const std::vector<Scalar> &K, const std::vector<Scalar> &d_K, Scalar kmin, Scalar kmax) { // range check on the parameters if (kmin < 0 || kmax < 0 || kmax <= kmin) { m_exec_conf->msg->error() << "cv.mesh kmin, kmax (" << kmin << "," << kmax << ") is invalid" << std::endl; throw std::runtime_error("Error setting up OrderParameterMesh"); } if (K.size() != d_K.size()) { m_exec_conf->msg->error() << "Convolution kernel and derivative have tables of unequal length " << K.size() << " != " << d_K.size() << std::endl; throw std::runtime_error("Error setting up OrderParameterMesh"); } m_k_min = kmin; m_k_max = kmax; m_delta_k = (kmax - kmin) / Scalar(K.size() - 1); // allocate the arrays GlobalArray<Scalar> table(K.size(), m_exec_conf); m_table.swap(table); GlobalArray<Scalar> table_d(d_K.size(), m_exec_conf); m_table_d.swap(table_d); // access the array ArrayHandle<Scalar> h_table(m_table, access_location::host, access_mode::readwrite); ArrayHandle<Scalar> h_table_d(m_table_d, access_location::host, access_mode::readwrite); // fill out the table for (unsigned int i = 0; i < m_table.getNumElements(); i++) { h_table.data[i] = K[i]; h_table_d.data[i] = d_K[i]; } } void OrderParameterMesh::setupMesh() { // update number of ghost cells m_n_ghost_cells = computeGhostCellNum(); // extra ghost cells are as wide as the inner cells const BoxDim& box = m_pdata->getBox(); Scalar3 cell_width = box.getNearestPlaneDistance() / make_scalar3(m_mesh_points.x, m_mesh_points.y, m_mesh_points.z); m_ghost_width = cell_width*make_scalar3( m_n_ghost_cells.x, m_n_ghost_cells.y, m_n_ghost_cells.z); m_exec_conf->msg->notice(6) << "cv.mesh: (Re-)allocating ghost layer (" << m_n_ghost_cells.x << "," << m_n_ghost_cells.y << "," << m_n_ghost_cells.z << ")" << std::endl; m_grid_dim = make_uint3(m_mesh_points.x+2*m_n_ghost_cells.x, m_mesh_points.y+2*m_n_ghost_cells.y, m_mesh_points.z+2*m_n_ghost_cells.z); m_n_cells = m_grid_dim.x*m_grid_dim.y*m_grid_dim.z; m_n_inner_cells = m_mesh_points.x * m_mesh_points.y * m_mesh_points.z; // allocate memory for influence function and k values GlobalArray<Scalar> inf_f(m_n_inner_cells, m_exec_conf); m_inf_f.swap(inf_f); // allocate memory for interpolationluence function and k values GlobalArray<Scalar> interpolation_f(m_n_inner_cells, m_exec_conf); m_interpolation_f.swap(interpolation_f); GlobalArray<Scalar3> k(m_n_inner_cells, m_exec_conf); m_k.swap(k); GlobalArray<Scalar> virial_mesh(6*m_n_inner_cells, m_exec_conf); m_virial_mesh.swap(virial_mesh); initializeFFT(); } uint3 OrderParameterMesh::computeGhostCellNum() { // ghost cells uint3 n_ghost_cells = make_uint3(0,0,0); #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition()) { Index3D di = m_pdata->getDomainDecomposition()->getDomainIndexer(); n_ghost_cells.x = (di.getW() > 1) ? m_radius : 0; n_ghost_cells.y = (di.getH() > 1) ? m_radius : 0; n_ghost_cells.z = (di.getD() > 1) ? m_radius : 0; } #endif // extra ghost cells to accomodate skin layer (max 1/2 ghost layer width) #ifdef ENABLE_MPI if (m_comm) { Scalar r_buff = m_comm->getGhostLayerMaxWidth(); const BoxDim& box = m_pdata->getBox(); Scalar3 cell_width = box.getNearestPlaneDistance() / make_scalar3(m_mesh_points.x, m_mesh_points.y, m_mesh_points.z); if (n_ghost_cells.x) n_ghost_cells.x += r_buff/cell_width.x + 1; if (n_ghost_cells.y) n_ghost_cells.y += r_buff/cell_width.y + 1; if (n_ghost_cells.z) n_ghost_cells.z += r_buff/cell_width.z + 1; } #endif return n_ghost_cells; } void OrderParameterMesh::initializeFFT() { bool local_fft = true; #ifdef ENABLE_MPI local_fft = !m_pdata->getDomainDecomposition(); if (! local_fft) { // ghost cell communicator for charge interpolation m_grid_comm_forward = std::unique_ptr<CommunicatorGrid<kiss_fft_cpx> >( new CommunicatorGrid<kiss_fft_cpx>(m_sysdef, make_uint3(m_mesh_points.x, m_mesh_points.y, m_mesh_points.z), make_uint3(m_grid_dim.x, m_grid_dim.y, m_grid_dim.z), m_n_ghost_cells, true)); // ghost cell communicator for force mesh m_grid_comm_reverse = std::unique_ptr<CommunicatorGrid<kiss_fft_cpx> >( new CommunicatorGrid<kiss_fft_cpx>(m_sysdef, make_uint3(m_mesh_points.x, m_mesh_points.y, m_mesh_points.z), make_uint3(m_grid_dim.x, m_grid_dim.y, m_grid_dim.z), m_n_ghost_cells, false)); // set up distributed FFTs int gdim[3]; int pdim[3]; Index3D decomp_idx = m_pdata->getDomainDecomposition()->getDomainIndexer(); pdim[0] = decomp_idx.getD(); pdim[1] = decomp_idx.getH(); pdim[2] = decomp_idx.getW(); gdim[0] = m_mesh_points.z*pdim[0]; gdim[1] = m_mesh_points.y*pdim[1]; gdim[2] = m_mesh_points.x*pdim[2]; int embed[3]; embed[0] = m_mesh_points.z+2*m_n_ghost_cells.z; embed[1] = m_mesh_points.y+2*m_n_ghost_cells.y; embed[2] = m_mesh_points.x+2*m_n_ghost_cells.x; m_ghost_offset = (m_n_ghost_cells.z*embed[1]+m_n_ghost_cells.y)*embed[2]+m_n_ghost_cells.x; uint3 pcoord = m_pdata->getDomainDecomposition()->getGridPos(); int pidx[3]; pidx[0] = pcoord.z; pidx[1] = pcoord.y; pidx[2] = pcoord.x; int row_m = 0; /* both local grid and proc grid are row major, no transposition necessary */ ArrayHandle<unsigned int> h_cart_ranks(m_pdata->getDomainDecomposition()->getCartRanks(), access_location::host, access_mode::read); dfft_create_plan(&m_dfft_plan_forward, 3, gdim, embed, NULL, pdim, pidx, row_m, 0, 1, m_exec_conf->getMPICommunicator(), (int *)h_cart_ranks.data); dfft_create_plan(&m_dfft_plan_inverse, 3, gdim, NULL, embed, pdim, pidx, row_m, 0, 1, m_exec_conf->getMPICommunicator(), (int *)h_cart_ranks.data); m_dfft_initialized = true; } #endif // ENABLE_MPI if (local_fft) { int dims[3]; dims[0] = m_mesh_points.z; dims[1] = m_mesh_points.y; dims[2] = m_mesh_points.x; m_kiss_fft = kiss_fftnd_alloc(dims, 3, 0, NULL, NULL); m_kiss_ifft = kiss_fftnd_alloc(dims, 3, 1, NULL, NULL); m_kiss_fft_initialized = true; } // allocate mesh and transformed mesh GlobalArray<kiss_fft_cpx> mesh(m_n_cells,m_exec_conf); m_mesh.swap(mesh); GlobalArray<kiss_fft_cpx> fourier_mesh(m_n_inner_cells, m_exec_conf); m_fourier_mesh.swap(fourier_mesh); GlobalArray<kiss_fft_cpx> fourier_mesh_G(m_n_inner_cells, m_exec_conf); m_fourier_mesh_G.swap(fourier_mesh_G); GlobalArray<kiss_fft_cpx> inv_fourier_mesh(m_n_cells, m_exec_conf); m_inv_fourier_mesh.swap(inv_fourier_mesh); } void OrderParameterMesh::computeInfluenceFunction() { if (m_prof) m_prof->push("influence function"); ArrayHandle<Scalar> h_inf_f(m_inf_f,access_location::host, access_mode::overwrite); ArrayHandle<Scalar> h_interpolation_f(m_interpolation_f,access_location::host, access_mode::overwrite); ArrayHandle<Scalar3> h_k(m_k,access_location::host, access_mode::overwrite); ArrayHandle<Scalar> h_table(m_table, access_location::host, access_mode::read); // reset arrays memset(h_inf_f.data, 0, sizeof(Scalar)*m_inf_f.getNumElements()); memset(h_interpolation_f.data, 0, sizeof(Scalar)*m_interpolation_f.getNumElements()); memset(h_k.data, 0, sizeof(Scalar3)*m_k.getNumElements()); const BoxDim& global_box = m_pdata->getGlobalBox(); // compute reciprocal lattice vectors Scalar3 a1 = global_box.getLatticeVector(0); Scalar3 a2 = global_box.getLatticeVector(1); Scalar3 a3 = global_box.getLatticeVector(2); Scalar V_box = global_box.getVolume(); Scalar3 b1 = Scalar(2.0*M_PI)*make_scalar3(a2.y*a3.z-a2.z*a3.y, a2.z*a3.x-a2.x*a3.z, a2.x*a3.y-a2.y*a3.x)/V_box; Scalar3 b2 = Scalar(2.0*M_PI)*make_scalar3(a3.y*a1.z-a3.z*a1.y, a3.z*a1.x-a3.x*a1.z, a3.x*a1.y-a3.y*a1.x)/V_box; Scalar3 b3 = Scalar(2.0*M_PI)*make_scalar3(a1.y*a2.z-a1.z*a2.y, a1.z*a2.x-a1.x*a2.z, a1.x*a2.y-a1.y*a2.x)/V_box; bool local_fft = m_kiss_fft_initialized; uint3 global_dim = m_mesh_points; #ifdef ENABLE_MPI uint3 pdim=make_uint3(0,0,0); uint3 pidx=make_uint3(0,0,0); if (m_pdata->getDomainDecomposition()) { const Index3D &didx = m_pdata->getDomainDecomposition()->getDomainIndexer(); global_dim.x *= didx.getW(); global_dim.y *= didx.getH(); global_dim.z *= didx.getD(); pidx = m_pdata->getDomainDecomposition()->getGridPos(); pdim = make_uint3(didx.getW(), didx.getH(), didx.getD()); } #endif for (unsigned int cell_idx = 0; cell_idx < m_n_inner_cells; ++cell_idx) { uint3 wave_idx; #ifdef ENABLE_MPI if (! local_fft) { // local layout: row major int ny = m_mesh_points.y; int nx = m_mesh_points.x; int n_local = cell_idx/ny/nx; int m_local = (cell_idx-n_local*ny*nx)/nx; int l_local = cell_idx % nx; // cyclic distribution wave_idx.x = l_local*pdim.x + pidx.x; wave_idx.y = m_local*pdim.y + pidx.y; wave_idx.z = n_local*pdim.z + pidx.z; } else #endif { // kiss FFT expects data in row major format wave_idx.z = cell_idx / (m_mesh_points.y * m_mesh_points.x); wave_idx.y = (cell_idx - wave_idx.z * m_mesh_points.x * m_mesh_points.y)/ m_mesh_points.x; wave_idx.x = cell_idx % m_mesh_points.x; } int3 n = make_int3(wave_idx.x,wave_idx.y,wave_idx.z); // compute Miller indices if (n.x >= (int)(global_dim.x/2 + global_dim.x%2)) n.x -= (int) global_dim.x; if (n.y >= (int)(global_dim.y/2 + global_dim.y%2)) n.y -= (int) global_dim.y; if (n.z >= (int)(global_dim.z/2 + global_dim.z%2)) n.z -= (int) global_dim.z; Scalar3 k = (Scalar)n.x*b1+(Scalar)n.y*b2+(Scalar)n.z*b3; Scalar ksq = dot(k,k); Scalar knorm = fast::sqrt(ksq); Scalar val(1.0); if (m_use_table && knorm >= m_k_min && knorm < m_k_max) { Scalar value_f = (knorm - m_k_min) / m_delta_k; unsigned int value_i = (unsigned int) value_f; Scalar K0 = h_table.data[value_i]; Scalar K1 = h_table.data[value_i+1]; // interpolate Scalar f = value_f - Scalar(value_i); val = K0 + f * (K1-K0); } h_inf_f.data[cell_idx] = val; h_k.data[cell_idx] = k; Scalar3 kH = Scalar(M_PI*2.0)*make_scalar3(n.x/global_dim.x, n.y/global_dim.y, n.z/global_dim.z); h_interpolation_f.data[cell_idx] = assignTSCfourier(kH.x)*assignTSCfourier(kH.y)*assignTSCfourier(kH.z); } if (m_prof) m_prof->pop(); } /*! \param x Distance on mesh in units of the mesh size */ Scalar OrderParameterMesh::assignTSC(Scalar x) { Scalar xsq = x*x; Scalar xabs = sqrt(xsq); if (xsq <= Scalar(1.0/4.0)) return Scalar(3.0/4.0) - xsq; else if (xsq <= Scalar(9.0/4.0)) return Scalar(1.0/2.0)*(Scalar(3.0/2.0)-xabs)*(Scalar(3.0/2.0)-xabs); else return Scalar(0.0); } Scalar OrderParameterMesh::assignTSCderiv(Scalar x) { Scalar xsq = x*x; Scalar xabs = copysignf(x,Scalar(1.0)); Scalar fac =(Scalar(3.0/2.0)-xabs); Scalar ret(0.0); if (xsq <= Scalar(1.0/4.0)) ret = -Scalar(2.0)*x; else if (xsq <= Scalar(9.0/4.0)) ret = -fac*x/xabs; return ret; } /*! \param k Wave number, times mesh size */ Scalar OrderParameterMesh::assignTSCfourier(Scalar x) { //! Coefficients of a power expansion of sin(x)/x const Scalar cpu_sinc_coeff[] = {Scalar(1.0), Scalar(-1.0/6.0), Scalar(1.0/120.0), Scalar(-1.0/5040.0),Scalar(1.0/362880.0), Scalar(-1.0/39916800.0)}; Scalar sinc = 0; if (x*x <= Scalar(1.0)) { Scalar term = Scalar(1.0); for (unsigned int i = 0; i < 6; ++i) { sinc += cpu_sinc_coeff[i] * term; term *= x*x; } } else { sinc = sin(x)/x; } // third order assigment function return sinc*sinc*sinc; } //! Assignment of particles to mesh using three-point scheme (triangular shaped cloud) /*! This is a second order accurate scheme with continuous value and continuous derivative */ void OrderParameterMesh::assignParticles() { if (m_prof) m_prof->push("assign"); ArrayHandle<Scalar4> h_postype(m_pdata->getPositions(), access_location::host, access_mode::read); ArrayHandle<kiss_fft_cpx> h_mesh(m_mesh, access_location::host, access_mode::overwrite); ArrayHandle<Scalar> h_mode(m_mode, access_location::host, access_mode::read); const BoxDim& box = m_pdata->getBox(); // set mesh to zero memset(h_mesh.data, 0, sizeof(kiss_fft_cpx)*m_mesh.getNumElements()); unsigned int nparticles = m_pdata->getN(); m_mode_sq = 0.0; // loop over local particles for (unsigned int idx = 0; idx < nparticles; ++idx) { Scalar4 postype = h_postype.data[idx]; Scalar3 pos = make_scalar3(postype.x, postype.y, postype.z); unsigned int type = __scalar_as_int(postype.w); // compute coordinates in units of the mesh size Scalar3 f = box.makeFraction(pos); Scalar3 reduced_pos = make_scalar3(f.x * (Scalar) m_mesh_points.x, f.y * (Scalar) m_mesh_points.y, f.z * (Scalar) m_mesh_points.z); reduced_pos += make_scalar3(m_n_ghost_cells.x, m_n_ghost_cells.y, m_n_ghost_cells.z); // find cell the particle is in (rounding downwards) int ix = reduced_pos.x; int iy = reduced_pos.y; int iz = reduced_pos.z; // handle particles on the boundary if (ix == (int)m_grid_dim.x && !m_n_ghost_cells.x) ix = 0; if (iy == (int)m_grid_dim.y && !m_n_ghost_cells.y) iy = 0; if (iz == (int)m_grid_dim.z && !m_n_ghost_cells.z) iz = 0; // compute distance between particle and cell center // in fractional coordinates Scalar3 cell_center = make_scalar3((Scalar)(ix-(int)m_n_ghost_cells.x)+Scalar(0.5), (Scalar)(iy-(int)m_n_ghost_cells.y)+Scalar(0.5), (Scalar)(iz-(int)m_n_ghost_cells.z)+Scalar(0.5)); // compute minimum image separation to center Scalar3 c_cart = box.makeCoordinates(cell_center/make_scalar3(m_mesh_points.x,m_mesh_points.y,m_mesh_points.z)); Scalar3 shift_cart = box.minImage(pos-c_cart); Scalar3 shift_f = box.makeFraction(shift_cart+box.getLo()); Scalar3 shift = shift_f*make_scalar3(m_mesh_points.x,m_mesh_points.y,m_mesh_points.z); // assign particle to cell and next neighbors for (int i = -1; i <= 1 ; ++i) for (int j = -1; j <= 1; ++j) for (int k = -1; k <= 1; ++k) { int neighi = (int)ix + i; int neighj = (int)iy + j; int neighk = (int)iz + k; if (! m_n_ghost_cells.x) { if (neighi == (int) m_grid_dim.x) neighi = 0; else if (neighi < 0) neighi += m_grid_dim.x; } assert(neighi >= 0 && neighi < (int) m_grid_dim.x); if (! m_n_ghost_cells.y) { if (neighj == (int) m_grid_dim.y) neighj = 0; else if (neighj < 0) neighj += m_grid_dim.y; } assert(neighj >= 0 && neighj < (int) m_grid_dim.y); if (! m_n_ghost_cells.z) { if (neighk == (int) m_grid_dim.z) neighk = 0; else if (neighk < 0) neighk += m_grid_dim.z; } assert(neighk >= 0 && neighk < (int) m_grid_dim.z); Scalar3 dx_frac = shift - make_scalar3(i,j,k); // compute fraction of particle density assigned to cell Scalar density_fraction = assignTSC(dx_frac.x)*assignTSC(dx_frac.y)*assignTSC(dx_frac.z); unsigned int neigh_idx; // store in row major order neigh_idx = neighi + m_grid_dim.x * (neighj + m_grid_dim.y*neighk); h_mesh.data[neigh_idx].r += h_mode.data[type]*density_fraction; } m_mode_sq += h_mode.data[type]*h_mode.data[type]; } // end of loop over particles #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition()) { // reduce sum MPI_Allreduce(MPI_IN_PLACE, &m_mode_sq, 1, MPI_HOOMD_SCALAR, MPI_SUM, m_exec_conf->getMPICommunicator()); } #endif if (m_prof) m_prof->pop(); } void OrderParameterMesh::updateMeshes() { ArrayHandle<Scalar> h_inf_f(m_inf_f, access_location::host, access_mode::read); ArrayHandle<Scalar3> h_k(m_k, access_location::host, access_mode::read); if (m_kiss_fft_initialized) { if (m_prof) m_prof->push("FFT"); // transform the particle mesh locally (forward transform) ArrayHandle<kiss_fft_cpx> h_mesh(m_mesh, access_location::host, access_mode::read); ArrayHandle<kiss_fft_cpx> h_fourier_mesh(m_fourier_mesh, access_location::host, access_mode::overwrite); kiss_fftnd(m_kiss_fft, h_mesh.data, h_fourier_mesh.data); if (m_prof) m_prof->pop(); } #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition()) { // update inner cells of particle mesh if (m_prof) m_prof->push("ghost cell update"); m_exec_conf->msg->notice(8) << "cv.mesh: Ghost cell update" << std::endl; m_grid_comm_forward->communicate(m_mesh); if (m_prof) m_prof->pop(); // perform a distributed FFT m_exec_conf->msg->notice(8) << "cv.mesh: Distributed FFT mesh" << std::endl; if (m_prof) m_prof->push("FFT"); ArrayHandle<kiss_fft_cpx> h_mesh(m_mesh, access_location::host, access_mode::read); ArrayHandle<kiss_fft_cpx> h_fourier_mesh(m_fourier_mesh, access_location::host, access_mode::overwrite); dfft_execute((cpx_t *)(h_mesh.data+m_ghost_offset), (cpx_t *)h_fourier_mesh.data, 0,m_dfft_plan_forward); if (m_prof) m_prof->pop(); } #endif ArrayHandle<kiss_fft_cpx> h_fourier_mesh(m_fourier_mesh, access_location::host, access_mode::readwrite); unsigned int N_global = m_pdata->getNGlobal(); { ArrayHandle<kiss_fft_cpx> h_fourier_mesh_G(m_fourier_mesh_G, access_location::host, access_mode::overwrite); ArrayHandle<Scalar> h_interpolation_f(m_interpolation_f, access_location::host, access_mode::read); // multiply with influence function for (unsigned int k = 0; k < m_n_inner_cells; ++k) { kiss_fft_cpx f = h_fourier_mesh.data[k]; // normalization f.r /= (Scalar) N_global; f.i /= (Scalar) N_global; Scalar val = f.r*f.r+f.i*f.i; h_fourier_mesh_G.data[k].r = f.r * val; h_fourier_mesh_G.data[k].i = f.i * val; Scalar diagonal_term = Scalar(0.5)*h_interpolation_f.data[k]*h_interpolation_f.data[k]*m_mode_sq/(Scalar)N_global/(Scalar)N_global; h_fourier_mesh_G.data[k].r -= f.r * diagonal_term; h_fourier_mesh_G.data[k].i -= f.i * diagonal_term; h_fourier_mesh.data[k] = f; } } if (m_prof) m_prof->pop(); if (m_kiss_fft_initialized) { if (m_prof) m_prof->push("FFT"); // do a local inverse transform of the force mesh ArrayHandle<kiss_fft_cpx> h_inv_fourier_mesh(m_inv_fourier_mesh, access_location::host, access_mode::overwrite); ArrayHandle<kiss_fft_cpx> h_fourier_mesh_G(m_fourier_mesh_G, access_location::host, access_mode::read); kiss_fftnd(m_kiss_ifft, h_fourier_mesh_G.data, h_inv_fourier_mesh.data); if (m_prof) m_prof->pop(); } #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition()) { if (m_prof) m_prof->push("FFT"); // Distributed inverse transform force on mesh points m_exec_conf->msg->notice(8) << "cv.mesh: Distributed iFFT" << std::endl; ArrayHandle<kiss_fft_cpx> h_fourier_mesh_G(m_fourier_mesh_G, access_location::host, access_mode::read); ArrayHandle<kiss_fft_cpx> h_inv_fourier_mesh(m_inv_fourier_mesh, access_location::host, access_mode::overwrite); dfft_execute((cpx_t *)h_fourier_mesh_G.data, (cpx_t *)(h_inv_fourier_mesh.data+m_ghost_offset), 1,m_dfft_plan_inverse); if (m_prof) m_prof->pop(); } #endif #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition()) { // update outer cells of force mesh using ghost cells from neighboring processors if (m_prof) m_prof->push("ghost cell update"); m_exec_conf->msg->notice(8) << "cv.mesh: Ghost cell update" << std::endl; m_grid_comm_reverse->communicate(m_inv_fourier_mesh); if (m_prof) m_prof->pop(); } #endif } void OrderParameterMesh::interpolateForces() { if (m_prof) m_prof->push("interpolate"); ArrayHandle<Scalar4> h_postype(m_pdata->getPositions(), access_location::host, access_mode::read); ArrayHandle<kiss_fft_cpx> h_inv_fourier_mesh(m_inv_fourier_mesh, access_location::host, access_mode::read); ArrayHandle<Scalar> h_mode(m_mode, access_location::host, access_mode::read); ArrayHandle<Scalar4> h_force(m_force, access_location::host, access_mode::overwrite); const BoxDim& box = m_pdata->getBox(); Scalar3 a1 = box.getLatticeVector(0); Scalar3 a2 = box.getLatticeVector(1); Scalar3 a3 = box.getLatticeVector(2); // reciprocal lattice vectors Scalar V_box = box.getVolume(); Scalar3 b1 = make_scalar3(a2.y*a3.z-a2.z*a3.y, a2.z*a3.x-a2.x*a3.z, a2.x*a3.y-a2.y*a3.x)/V_box; Scalar3 b2 = make_scalar3(a3.y*a1.z-a3.z*a1.y, a3.z*a1.x-a3.x*a1.z, a3.x*a1.y-a3.y*a1.x)/V_box; Scalar3 b3 = make_scalar3(a1.y*a2.z-a1.z*a2.y, a1.z*a2.x-a1.x*a2.z, a1.x*a2.y-a1.y*a2.x)/V_box; // particle number unsigned int n_global = m_pdata->getNGlobal(); for (unsigned int idx = 0; idx < m_pdata->getN(); ++idx) { Scalar4 postype = h_postype.data[idx]; Scalar3 pos = make_scalar3(postype.x, postype.y, postype.z); unsigned int type = __scalar_as_int(postype.w); Scalar mode = h_mode.data[type]; // compute coordinates in units of the mesh size Scalar3 f = box.makeFraction(pos); Scalar3 reduced_pos = make_scalar3(f.x * (Scalar) m_mesh_points.x, f.y * (Scalar) m_mesh_points.y, f.z * (Scalar) m_mesh_points.z); // find cell of the force mesh the particle is in unsigned int ix = (reduced_pos.x + (Scalar)m_n_ghost_cells.x); unsigned int iy = (reduced_pos.y + (Scalar)m_n_ghost_cells.y); unsigned int iz = (reduced_pos.z + (Scalar)m_n_ghost_cells.z); // handle particles on the boundary if (ix == m_grid_dim.x && !m_n_ghost_cells.x) ix = 0; if (iy == m_grid_dim.y && !m_n_ghost_cells.y) iy = 0; if (iz == m_grid_dim.z && !m_n_ghost_cells.z) iz = 0; // center of cell (in units of the mesh size) Scalar3 cell_center = make_scalar3((Scalar)ix - (Scalar)(m_n_ghost_cells.x) + Scalar(0.5), (Scalar)iy - (Scalar)(m_n_ghost_cells.y) + Scalar(0.5), (Scalar)iz - (Scalar)(m_n_ghost_cells.z) + Scalar(0.5)); // compute minimum image separation to center Scalar3 c_cart = box.makeCoordinates(cell_center/make_scalar3(m_mesh_points.x,m_mesh_points.y,m_mesh_points.z)); Scalar3 shift_cart = box.minImage(pos-c_cart); Scalar3 shift_f = box.makeFraction(shift_cart+box.getLo()); Scalar3 shift = shift_f*make_scalar3(m_mesh_points.x,m_mesh_points.y,m_mesh_points.z); Scalar3 force = make_scalar3(0.0,0.0,0.0); for (int i = -1; i <= 1 ; ++i) for (int j = -1; j <= 1; ++j) for (int k = -1; k <= 1; ++k) { int neighi = (int)ix + i; int neighj = (int)iy + j; int neighk = (int)iz + k; if (! m_n_ghost_cells.x) { if (neighi == (int)m_grid_dim.x) neighi = 0; else if (neighi < 0) neighi += m_grid_dim.x; } if (! m_n_ghost_cells.y) { if (neighj == (int)m_grid_dim.y) neighj = 0; else if (neighj < 0) neighj += m_grid_dim.y; } if (! m_n_ghost_cells.z) { if (neighk == (int)m_grid_dim.z) neighk = 0; else if (neighk < 0) neighk += m_grid_dim.z; } Scalar3 dx_frac = shift - make_scalar3(i,j,k); unsigned int neigh_idx; neigh_idx = neighi + m_grid_dim.x * (neighj + m_grid_dim.y*neighk); kiss_fft_cpx inv_mesh = h_inv_fourier_mesh.data[neigh_idx]; force += -(Scalar)m_mesh_points.x*b1*mode*assignTSCderiv(dx_frac.x)*assignTSC(dx_frac.y)*assignTSC(dx_frac.z)*inv_mesh.r; force += -(Scalar)m_mesh_points.y*b2*mode*assignTSC(dx_frac.x)*assignTSCderiv(dx_frac.y)*assignTSC(dx_frac.z)*inv_mesh.r; force += -(Scalar)m_mesh_points.z*b3*mode*assignTSC(dx_frac.x)*assignTSC(dx_frac.y)*assignTSCderiv(dx_frac.z)*inv_mesh.r; } // Multiply with bias potential derivative force *= Scalar(2.0)/(Scalar)n_global*m_bias; h_force.data[idx] = make_scalar4(force.x,force.y,force.z,0.0); } // end of loop over particles if (m_prof) m_prof->pop(); } Scalar OrderParameterMesh::computeCV() { if (m_prof) m_prof->push("sum"); ArrayHandle<kiss_fft_cpx> h_fourier_mesh(m_fourier_mesh, access_location::host, access_mode::read); ArrayHandle<kiss_fft_cpx> h_fourier_mesh_G(m_fourier_mesh_G, access_location::host, access_mode::read); ArrayHandle<Scalar> h_interpolation_f(m_interpolation_f, access_location::host, access_mode::read); Scalar sum(0.0); bool exclude_dc = true; #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition()) { uint3 my_pos = m_pdata->getDomainDecomposition()->getGridPos(); exclude_dc = !my_pos.x && !my_pos.y && !my_pos.z; } #endif unsigned int N_global = m_pdata->getNGlobal(); for (unsigned int k = 0; k < m_n_inner_cells; ++k) { bool exclude = false; if (exclude_dc) // exclude DC bin exclude = (k == 0); if (! exclude) { sum += h_fourier_mesh_G.data[k].r * h_fourier_mesh.data[k].r + h_fourier_mesh_G.data[k].i * h_fourier_mesh.data[k].i; Scalar norm2 = h_fourier_mesh.data[k].r*h_fourier_mesh.data[k].r + h_fourier_mesh.data[k].i*h_fourier_mesh.data[k].i; Scalar diagonal_term = Scalar(0.5)*norm2*h_interpolation_f.data[k]*h_interpolation_f.data[k]*m_mode_sq/(Scalar)N_global/(Scalar)N_global; sum -= diagonal_term; } } sum *= Scalar(1.0/2.0); #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition()) { // reduce sum MPI_Allreduce(MPI_IN_PLACE, &sum, 1, MPI_HOOMD_SCALAR, MPI_SUM, m_exec_conf->getMPICommunicator()); } #endif if (m_prof) m_prof->pop(); return sum; } Scalar OrderParameterMesh::getCurrentValue(unsigned int timestep) { if (m_cv_last_updated == timestep && !m_is_first_step) return m_cv; if (m_prof) m_prof->push("Mesh"); if (m_is_first_step) { // allocate memory and initialize arrays setupMesh(); computeInfluenceFunction(); m_is_first_step = false; } bool ghost_cell_num_changed = false; uint3 n_ghost_cells = computeGhostCellNum(); // do we need to reallocate? if (m_n_ghost_cells.x != n_ghost_cells.x || m_n_ghost_cells.y != n_ghost_cells.y || m_n_ghost_cells.z != n_ghost_cells.z) ghost_cell_num_changed = true; if (ghost_cell_num_changed) { if (ghost_cell_num_changed) setupMesh(); computeInfluenceFunction(); m_box_changed = false; } assignParticles(); updateMeshes(); m_cv = computeCV(); m_cv_last_updated = timestep; if (m_prof) m_prof->pop(); return m_cv; } void OrderParameterMesh::computeVirial() { if (m_prof) m_prof->push("virial"); ArrayHandle<kiss_fft_cpx> h_fourier_mesh(m_fourier_mesh, access_location::host, access_mode::overwrite); ArrayHandle<kiss_fft_cpx> h_fourier_mesh_G(m_fourier_mesh_G, access_location::host, access_mode::overwrite); ArrayHandle<Scalar> h_inf_f(m_inf_f, access_location::host, access_mode::read); ArrayHandle<Scalar3> h_k(m_k, access_location::host, access_mode::read); ArrayHandle<Scalar> h_table_d(m_table_d, access_location::host, access_mode::read); Scalar virial[6]; for (unsigned int i = 0; i < 6; ++i) virial[i] = Scalar(0.0); bool exclude_dc = true; #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition()) { uint3 my_pos = m_pdata->getDomainDecomposition()->getGridPos(); exclude_dc = !my_pos.x && !my_pos.y && !my_pos.z; } #endif unsigned int Nglobal = m_pdata->getNGlobal(); for (unsigned int kidx = 0; kidx < m_n_inner_cells; ++kidx) { bool exclude = false; if (exclude_dc) // exclude DC bin exclude = (kidx == 0); if (! exclude) { // non-zero wave vector kiss_fft_cpx fourier = h_fourier_mesh.data[kidx]; Scalar3 k = h_k.data[kidx]; Scalar ksq = dot(k,k); Scalar knorm = sqrt(ksq); Scalar kfac = Scalar(1.0)/Scalar(2.0)/knorm; // derivative of convolution kernel Scalar val_D(0.0); if (m_use_table && knorm >= m_k_min && knorm < m_k_max) { Scalar value_f = (knorm - m_k_min) / m_delta_k; unsigned int value_i = (unsigned int) value_f; Scalar dK0 = h_table_d.data[value_i]; Scalar dK1 = h_table_d.data[value_i+1]; // interpolate Scalar f = value_f - Scalar(value_i); val_D = dK0 + f * (dK1-dK0); } kfac *= val_D; Scalar val = (fourier.r*fourier.r+fourier.i*fourier.i)/(Scalar)Nglobal; Scalar rhog = (fourier.r * fourier.r + fourier.i * fourier.i)*val/(Scalar)Nglobal; virial[0] += rhog*kfac*k.x*k.x; // xx virial[1] += rhog*kfac*k.x*k.y; // xy virial[2] += rhog*kfac*k.x*k.z; // xz virial[3] += rhog*kfac*k.y*k.y; // yy virial[4] += rhog*kfac*k.y*k.z; // yz virial[5] += rhog*kfac*k.z*k.z; // zz } } for (unsigned int i = 0; i < 6; ++i) m_external_virial[i] = m_bias*virial[i]; if (m_prof) m_prof->pop(); } void OrderParameterMesh::computeBiasForces(unsigned int timestep) { if (m_is_first_step || m_cv_last_updated != timestep) getCurrentValue(timestep); if (m_prof) m_prof->push("Mesh"); interpolateForces(); PDataFlags flags = m_pdata->getFlags(); if (flags[pdata_flag::pressure_tensor] || flags[pdata_flag::isotropic_virial]) { computeVirial(); } else { for (unsigned int i = 0; i < 6; ++i) m_external_virial[i] = Scalar(0.0); } if (m_prof) m_prof->pop(); } Scalar OrderParameterMesh::getLogValue(const std::string& quantity, unsigned int timestep) { if (quantity == m_log_names[0]) { return getCurrentValue(timestep); } else if (quantity == m_log_names[1]) { computeQmax(timestep); return m_q_max.x; } else if (quantity == m_log_names[2]) { computeQmax(timestep); return m_q_max.y; } else if (quantity == m_log_names[3]) { computeQmax(timestep); return m_q_max.z; } else if (quantity == m_log_names[4]) { computeQmax(timestep); return m_sq_max; } // nothing found? return base class value return CollectiveVariable::getLogValue(quantity, timestep); } void OrderParameterMesh::computeQmax(unsigned int timestep) { // compute Fourier grid getCurrentValue(timestep); if (timestep && m_q_max_last_computed == timestep) return; m_q_max_last_computed = timestep; if (m_prof) m_prof->push("max q"); ArrayHandle<kiss_fft_cpx> h_fourier_mesh(m_fourier_mesh, access_location::host, access_mode::read); ArrayHandle<Scalar3> h_k(m_k, access_location::host, access_mode::read); Scalar max_amplitude(0.0); Scalar3 q_max(make_scalar3(0.0,0.0,0.0)); for (unsigned int kidx = 0; kidx < m_n_inner_cells; ++kidx) { Scalar a = h_fourier_mesh.data[kidx].r*h_fourier_mesh.data[kidx].r + h_fourier_mesh.data[kidx].i*h_fourier_mesh.data[kidx].i; if (a > max_amplitude) { q_max = h_k.data[kidx]; max_amplitude = a; } } #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition()) { // all processes send their results to all other processes // and then they determine the maximum wave vector Scalar *all_amplitudes = new Scalar[m_exec_conf->getNRanks()]; Scalar3 *all_q_max = new Scalar3[m_exec_conf->getNRanks()]; MPI_Allgather(&max_amplitude, 1, MPI_HOOMD_SCALAR, all_amplitudes, 1, MPI_HOOMD_SCALAR, m_exec_conf->getMPICommunicator()); MPI_Allgather(&q_max, sizeof(Scalar3), MPI_BYTE, all_q_max, sizeof(Scalar3), MPI_BYTE, m_exec_conf->getMPICommunicator()); for (unsigned int i = 0; i < m_exec_conf->getNRanks();++i) { if (all_amplitudes[i] > max_amplitude) { max_amplitude = all_amplitudes[i]; q_max = all_q_max[i]; } } delete [] all_amplitudes; delete [] all_q_max; } #endif if (m_prof) m_prof->pop(); m_q_max = q_max; m_sq_max = max_amplitude; // normalize with 1/V unsigned int n_global = m_pdata->getNGlobal(); m_sq_max *= (Scalar)n_global; } void export_OrderParameterMesh(py::module& m) { py::class_<OrderParameterMesh, std::shared_ptr<OrderParameterMesh> >(m,"OrderParameterMesh", py::base<CollectiveVariable> ()) .def(py::init<std::shared_ptr<SystemDefinition>, const unsigned int, const unsigned int, const unsigned int, const std::vector<Scalar>, const std::vector<int3> >()) .def("setTable", &OrderParameterMesh::setTable) .def("setUseTable", &OrderParameterMesh::setUseTable); } <file_sep>/*! \file WellTemperedEnsemble.cc \brief Implements the potential energy as a collective variable (well-tempered ensemble) */ #include "WellTemperedEnsemble.h" #ifdef ENABLE_CUDA #include "WellTemperedEnsemble.cuh" #endif namespace py = pybind11; WellTemperedEnsemble::WellTemperedEnsemble(std::shared_ptr<SystemDefinition> sysdef, const std::string& name) : CollectiveVariable(sysdef, name), m_pe(0.0), m_log_name("cv_potential_energy") { #ifdef ENABLE_CUDA if (m_exec_conf->exec_mode == ExecutionConfiguration::GPU) { GlobalArray<Scalar> sum(1,m_exec_conf); m_sum.swap(sum); TAG_ALLOCATION(m_sum); } cudaDeviceProp dev_prop = m_exec_conf->dev_prop; m_tuner_reduce.reset(new Autotuner(dev_prop.warpSize, dev_prop.maxThreadsPerBlock, dev_prop.warpSize, 5, 100000, "wte_reduce", this->m_exec_conf)); m_tuner_scale.reset(new Autotuner(dev_prop.warpSize, dev_prop.maxThreadsPerBlock, dev_prop.warpSize, 5, 100000, "wte_scale", this->m_exec_conf)); #endif } void WellTemperedEnsemble::computeCV(unsigned int timestep) { if (m_prof) m_prof->push(m_exec_conf,"Well-Tempered Ensemble"); #ifdef ENABLE_CUDA if (m_exec_conf->exec_mode == ExecutionConfiguration::GPU) { computeCVGPU(timestep); } else #endif { ArrayHandle<Scalar4> h_net_force(m_pdata->getNetForce(), access_location::host, access_mode::read); unsigned int N = m_pdata->getN(); m_pe = Scalar(0.0); // Sum up potential energy for (unsigned int i = 0; i < N; ++i) { m_pe += h_net_force.data[i].w; } } m_pe += m_pdata->getExternalEnergy(); #ifdef ENABLE_MPI // reduce Fourier modes on on all processors if (m_pdata->getDomainDecomposition()) { MPI_Allreduce(MPI_IN_PLACE, &m_pe, 1, MPI_HOOMD_SCALAR, MPI_SUM, m_exec_conf->getMPICommunicator()); } #endif if (m_prof) m_prof->pop(); } #ifdef ENABLE_CUDA void WellTemperedEnsemble::computeCVGPU(unsigned int timestep) { ArrayHandle<Scalar4> d_net_force(m_pdata->getNetForce(), access_location::device, access_mode::read); // maximum size, per GPU, for a block_size of one unsigned int scratch_size = (m_pdata->getN()+1); ScopedAllocation<Scalar> d_scratch(m_exec_conf->getCachedAllocatorManaged(), scratch_size*m_exec_conf->getNumActiveGPUs()); { ArrayHandle<Scalar> d_sum(m_sum, access_location::device, access_mode::overwrite); // reset sum cudaMemsetAsync(d_sum.data, 0, sizeof(Scalar)); m_exec_conf->beginMultiGPU(); m_tuner_reduce->begin(); gpu_reduce_potential_energy(d_scratch.data, d_net_force.data, m_pdata->getGPUPartition(), 0, // nghost scratch_size, d_sum.data, false, m_tuner_reduce->getParam()); if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); m_tuner_reduce->end(); m_exec_conf->endMultiGPU(); } ArrayHandle<Scalar> h_sum(m_sum, access_location::host, access_mode::read); m_pe = *h_sum.data; } void WellTemperedEnsemble::computeBiasForcesGPU(unsigned int timestep) { ArrayHandle<Scalar4> d_net_force(m_pdata->getNetForce(), access_location::device, access_mode::readwrite); ArrayHandle<Scalar4> d_net_torque(m_pdata->getNetTorqueArray(), access_location::device, access_mode::readwrite); ArrayHandle<Scalar> d_net_virial(m_pdata->getNetVirial(), access_location::device, access_mode::readwrite); unsigned int pitch = m_pdata->getNetVirial().getPitch(); Scalar fac = Scalar(1.0)+m_bias; m_exec_conf->beginMultiGPU(); m_tuner_scale->begin(); gpu_scale_netforce(d_net_force.data, d_net_torque.data, d_net_virial.data, pitch, fac, m_pdata->getGPUPartition(), 0, // nghost m_tuner_scale->getParam()); if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); m_tuner_scale->end(); m_exec_conf->endMultiGPU(); } #endif void WellTemperedEnsemble::computeBiasForces(unsigned int timestep) { if (m_prof) m_prof->push("Well-Tempered Ensemble"); Scalar fac = Scalar(1.0)+m_bias; #ifdef ENABLE_CUDA if (m_exec_conf->exec_mode == ExecutionConfiguration::GPU) { computeBiasForcesGPU(timestep); } else #endif { // Note: this Compute operates directly on the net force, therefore it needs to be called // after every other force ArrayHandle<Scalar4> h_net_force(m_pdata->getNetForce(), access_location::host, access_mode::readwrite); ArrayHandle<Scalar4> h_net_torque(m_pdata->getNetTorqueArray(), access_location::host, access_mode::readwrite); ArrayHandle<Scalar> h_net_virial(m_pdata->getNetVirial(), access_location::host, access_mode::readwrite); unsigned int N = m_pdata->getN(); unsigned int pitch = m_pdata->getNetVirial().getPitch(); // apply bias factor for (unsigned int i = 0; i < N; ++i) { h_net_force.data[i].x *= fac; h_net_force.data[i].y *= fac; h_net_force.data[i].z *= fac; h_net_torque.data[i].x *= fac; h_net_torque.data[i].y *= fac; h_net_torque.data[i].z *= fac; h_net_torque.data[i].w *= fac; h_net_virial.data[i + 0*pitch] *= fac; h_net_virial.data[i + 1*pitch] *= fac; h_net_virial.data[i + 2*pitch] *= fac; h_net_virial.data[i + 3*pitch] *= fac; h_net_virial.data[i + 4*pitch] *= fac; h_net_virial.data[i + 5*pitch] *= fac; } } for (unsigned int i = 0; i < 6; ++i) { Scalar v = m_pdata->getExternalVirial(i); m_pdata->setExternalVirial(i,fac*v); } if (m_prof) m_prof->pop(); } void export_WellTemperedEnsemble(py::module& m) { py::class_<WellTemperedEnsemble, std::shared_ptr<WellTemperedEnsemble> > (m, "WellTemperedEnsemble", py::base<CollectiveVariable>() ) .def(py::init< std::shared_ptr<SystemDefinition>, const std::string& > ()) ; } <file_sep>#include "Density.h" namespace py = pybind11; Density::Density(std::shared_ptr<SystemDefinition> sysdef, std::shared_ptr<ParticleGroup> group, const std::string& suffix) : CollectiveVariable(sysdef, "cv_density"+(suffix != "" ? "_"+suffix : "")), m_group(group) { // reset force and virial ArrayHandle<Scalar4> h_force(m_force, access_location::host, access_mode::overwrite); ArrayHandle<Scalar> h_virial(m_virial, access_location::host, access_mode::overwrite); memset(h_force.data, 0, sizeof(Scalar4)*m_force.getNumElements()); memset(h_virial.data, 0, sizeof(Scalar)*m_virial.getNumElements()); m_log_name = m_cv_name; } Scalar Density::getCurrentValue(unsigned int timestep) { Scalar V = m_pdata->getGlobalBox().getVolume(m_sysdef->getNDimensions()==2); unsigned int N = m_group->getNumMembersGlobal(); Scalar rho = (Scalar)N/V; return rho; } void Density::computeBiasForces(unsigned int timestep) { #ifdef ENABLE_MPI // only add contribution to external virial once (on rank zero) if (m_exec_conf->getRank()) return; #endif const BoxDim& global_box = m_pdata->getGlobalBox(); Scalar V = global_box.getVolume(m_sysdef->getNDimensions()==2); unsigned int N = m_group->getNumMembersGlobal(); Scalar Lx = global_box.getL().x; Scalar Ly = global_box.getL().y; Scalar Lz = global_box.getL().z; // derivative of rho w.r.t. V Scalar fac = -(Scalar)N/(V*V); // from <NAME> 1994 Eq. (2.20) m_external_virial[0] = -m_bias*fac*Lx*Ly*Lz; // xx m_external_virial[1] = 0; m_external_virial[2] = 0; m_external_virial[3] = -m_bias*fac*Lx*Ly*Lz; // yy m_external_virial[4] = 0; m_external_virial[5] = -m_bias*fac*Lx*Ly*Lz; // zz } void export_Density(py::module& m) { py::class_<Density, std::shared_ptr<Density> >(m, "Density", py::base<CollectiveVariable>() ) .def(py::init< std::shared_ptr<SystemDefinition>, std::shared_ptr<ParticleGroup>, const std::string& >() ); ; } <file_sep>#ifndef __WELL_TEMPERED_ENSEMBLE_H__ #define __WELL_TEMPERED_ENSEMBLE_H__ /*! \file CollectiveVariable.h \brief Declares the CollectiveVariable abstract class */ #include "CollectiveVariable.h" #include <hoomd/GlobalArray.h> #ifdef ENABLE_CUDA #include "hoomd/Autotuner.h" #endif #include <memory> /*! Class to implement the potential energy as a collective variable (Well-tempered Ensemble) see Bonomi, Parrinello PRL 104:190601 (2010) */ class WellTemperedEnsemble : public CollectiveVariable { public: /*! Constructs the collective variable \param sysdef The system definition \param name The name of this collective variable */ WellTemperedEnsemble(std::shared_ptr<SystemDefinition> sysdef, const std::string& name); virtual ~WellTemperedEnsemble() {} /*! Requires the evaluation of other variables first */ virtual bool requiresNetForce() { return true; } /*! Returns the names of provided log quantities. */ virtual std::vector<std::string> getProvidedLogQuantities() { std::vector<std::string> list = CollectiveVariable::getProvidedLogQuantities(); list.push_back(m_log_name); return list; } /*! Returns the current value of the collective variable * \param timestep The currnt value of the timestep */ virtual Scalar getCurrentValue(unsigned int timestep) { computeCV(timestep); return m_pe; } /*! Returns the value of a specific log quantity. * \param quantity The name of the quantity to return the value of * \param timestep The current value of the time step */ Scalar getLogValue(const std::string& quantity, unsigned int timestep) { if (quantity == m_log_name) { computeCV(timestep); return m_pe; } // nothing found, turn to base class return CollectiveVariable::getLogValue(quantity, timestep); } //! Set autotuner parameters /*! \param enable Enable/disable autotuning \param period period (approximate) in time steps when returning occurs */ virtual void setAutotunerParams(bool enable, unsigned int period) { CollectiveVariable::setAutotunerParams(enable, period); m_tuner_reduce->setPeriod(period); m_tuner_reduce->setEnabled(enable); m_tuner_scale->setPeriod(period); m_tuner_scale->setEnabled(enable); } protected: Scalar m_pe; //!< The potential energy std::string m_log_name; //!< Name of log quantity #ifdef ENABLE_CUDA GlobalArray<Scalar> m_sum; //!< for reading back potential energy from GPU std::unique_ptr<Autotuner> m_tuner_scale; //!< Autotuner for scaling forces std::unique_ptr<Autotuner> m_tuner_reduce; //!< Autotuner for collective variable reduction #endif virtual void computeCV(unsigned int timestep); /*! Compute the biased forces for this collective variable. The force that is written to the force arrays must be multiplied by the bias factor. \param timestep The current value of the time step */ virtual void computeBiasForces(unsigned int timestep); //! Compute bias force on GPU void computeBiasForcesGPU(unsigned int timestep); //! Compute collective variable on GPU void computeCVGPU(unsigned int timestep); }; //! Export the CollectiveVariable class to python void export_WellTemperedEnsemble(pybind11::module& m); #endif // __WELL_TEMPERED_ENSEMBLE_H__ <file_sep>/*! \file CollectiveWrapper.cc \brief Wraps a CollectiveVariable around a regular ForceCompute */ #include "CollectiveWrapper.h" #ifdef ENABLE_CUDA #include "WellTemperedEnsemble.cuh" #endif namespace py = pybind11; CollectiveWrapper::CollectiveWrapper(std::shared_ptr<SystemDefinition> sysdef, std::shared_ptr<ForceCompute> fc, const std::string& name) : CollectiveVariable(sysdef, name), m_fc(fc), m_energy(0.0) { #ifdef ENABLE_CUDA if (m_exec_conf->exec_mode == ExecutionConfiguration::GPU) { GlobalArray<Scalar> sum(1,m_exec_conf); m_sum.swap(sum); TAG_ALLOCATION(m_sum); } cudaDeviceProp dev_prop = m_exec_conf->dev_prop; m_tuner_reduce.reset(new Autotuner(dev_prop.warpSize, dev_prop.maxThreadsPerBlock, dev_prop.warpSize, 5, 100000, name+"_reduce", this->m_exec_conf)); m_tuner_scale.reset(new Autotuner(dev_prop.warpSize, dev_prop.maxThreadsPerBlock, dev_prop.warpSize, 5, 100000, name+"_scale", this->m_exec_conf)); #endif } void CollectiveWrapper::computeCV(unsigned int timestep) { // compute the force (note this only computes once per time step) m_fc->compute(timestep); if (m_prof) m_prof->push(m_exec_conf,"Collective wrap"); #ifdef ENABLE_CUDA if (m_exec_conf->exec_mode == ExecutionConfiguration::GPU) { computeCVGPU(timestep); } else #endif { ArrayHandle<Scalar4> h_force(m_fc->getForceArray(), access_location::host, access_mode::readwrite); unsigned int N = m_pdata->getN(); m_energy = Scalar(0.0); // Sum up potential energy for (unsigned int i = 0; i < N; ++i) { m_energy += h_force.data[i].w; } } Scalar external_energy = m_fc->getExternalEnergy(); m_energy += external_energy; #ifdef ENABLE_MPI // reduce Fourier modes on on all processors if (m_pdata->getDomainDecomposition()) { MPI_Allreduce(MPI_IN_PLACE, &m_energy, 1, MPI_HOOMD_SCALAR, MPI_SUM, m_exec_conf->getMPICommunicator()); } #endif if (m_prof) m_prof->pop(); } #ifdef ENABLE_CUDA void CollectiveWrapper::computeCVGPU(unsigned int timestep) { ArrayHandle<Scalar4> d_force(m_fc->getForceArray(), access_location::device, access_mode::read); // maximum size, per GPU, for a block_size of one unsigned int scratch_size = (m_pdata->getN()+m_pdata->getNGhosts()+1); ScopedAllocation<Scalar> d_scratch(m_exec_conf->getCachedAllocatorManaged(), scratch_size*m_exec_conf->getNumActiveGPUs()); { ArrayHandle<Scalar> d_sum(m_sum, access_location::device, access_mode::overwrite); // reset sum cudaMemsetAsync(d_sum.data, 0, sizeof(Scalar)); m_exec_conf->beginMultiGPU(); m_tuner_reduce->begin(); gpu_reduce_potential_energy(d_scratch.data, d_force.data, m_pdata->getGPUPartition(), m_pdata->getNGhosts(), scratch_size, d_sum.data, false, m_tuner_reduce->getParam()); if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); m_tuner_reduce->end(); m_exec_conf->endMultiGPU(); } ArrayHandle<Scalar> h_sum(m_sum, access_location::host, access_mode::read); m_energy = *h_sum.data; } void CollectiveWrapper::computeBiasForcesGPU(unsigned int timestep) { ArrayHandle<Scalar4> d_force(m_fc->getForceArray(), access_location::device, access_mode::readwrite); ArrayHandle<Scalar4> d_torque(m_fc->getTorqueArray(), access_location::device, access_mode::readwrite); ArrayHandle<Scalar> d_virial(m_fc->getVirialArray(), access_location::device, access_mode::readwrite); unsigned int pitch = m_fc->getVirialArray().getPitch(); Scalar fac = m_bias; m_exec_conf->beginMultiGPU(); m_tuner_scale->begin(); gpu_scale_netforce(d_force.data, d_torque.data, d_virial.data, pitch, fac, m_pdata->getGPUPartition(), m_pdata->getNGhosts(), m_tuner_scale->getParam()); if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); m_tuner_scale->end(); m_exec_conf->endMultiGPU(); } #endif void CollectiveWrapper::computeBiasForces(unsigned int timestep) { // compute the force (note this only computes once per time step) m_fc->compute(timestep); if (m_prof) m_prof->push("Collective wrap"); Scalar fac = m_bias; #ifdef ENABLE_CUDA if (m_exec_conf->exec_mode == ExecutionConfiguration::GPU) { computeBiasForcesGPU(timestep); } else #endif { ArrayHandle<Scalar4> h_force(m_fc->getForceArray(), access_location::host, access_mode::readwrite); ArrayHandle<Scalar4> h_torque(m_fc->getTorqueArray(), access_location::host, access_mode::readwrite); ArrayHandle<Scalar> h_virial(m_fc->getVirialArray(), access_location::host, access_mode::readwrite); unsigned int N = m_pdata->getN()+m_pdata->getNGhosts(); unsigned int pitch = m_fc->getVirialArray().getPitch(); // apply bias factor for (unsigned int i = 0; i < N; ++i) { h_force.data[i].x *= fac; h_force.data[i].y *= fac; h_force.data[i].z *= fac; h_torque.data[i].x *= fac; h_torque.data[i].y *= fac; h_torque.data[i].z *= fac; h_torque.data[i].w *= fac; h_virial.data[i + 0*pitch] *= fac; h_virial.data[i + 1*pitch] *= fac; h_virial.data[i + 2*pitch] *= fac; h_virial.data[i + 3*pitch] *= fac; h_virial.data[i + 4*pitch] *= fac; h_virial.data[i + 5*pitch] *= fac; } } if (m_prof) m_prof->pop(); } void export_CollectiveWrapper(py::module& m) { py::class_<CollectiveWrapper, std::shared_ptr<CollectiveWrapper> > (m, "CollectiveWrapper", py::base<CollectiveVariable>() ) .def(py::init< std::shared_ptr<SystemDefinition>, std::shared_ptr<ForceCompute>, const std::string& > ()) ; } <file_sep>#include "CollectiveVariable.h" #include <hoomd/ParticleGroup.h> class Density : public CollectiveVariable { public: Density(std::shared_ptr<SystemDefinition> sysdef, std::shared_ptr<ParticleGroup> group, const std::string& suffix); virtual ~Density() {} virtual Scalar getCurrentValue(unsigned int timestep); /*! Returns the names of provided log quantities. */ std::vector<std::string> getProvidedLogQuantities() { std::vector<std::string> list = CollectiveVariable::getProvidedLogQuantities(); list.push_back(m_log_name); return list; } /*! Returns the value of a specific log quantity. * \param quantity The name of the quantity to return the value of * \param timestep The current value of the time step */ Scalar getLogValue(const std::string& quantity, unsigned int timestep) { if (quantity == m_log_name) return getCurrentValue(timestep); return CollectiveVariable::getLogValue(quantity, timestep); } /*! Returns true if the collective variable can compute derivatives * w.r.t. particle coordinates */ virtual bool canComputeDerivatives() { return false; } private: /*! Compute the biased forces for this collective variable. The force that is written to the force arrays must be multiplied by the bias factor. \param timestep The current value of the time step */ virtual void computeBiasForces(unsigned int timestep); std::string m_log_name; //!< The name of the collective variable std::shared_ptr<ParticleGroup> m_group; //!< The group to count the number of particles }; //! Export Density to Python void export_Density(pybind11::module& m); <file_sep>from hoomd import * from hoomd import md import math import numpy as np context.initialize() init.create_lattice(unitcell=lattice.sc(a=1.0), n=[10,10,10]); nl = md.nlist.cell() wca = md.pair.lj(r_cut=2**(1./6.),nlist=nl) wca.pair_coeff.set('A','A',sigma=1,epsilon=1) wca.set_params(mode='shift') md.integrate.mode_standard(dt=0.001) # thermalize bd = md.integrate.brownian(group = group.all(),kT=1.0,seed=123) bd.set_gamma('A',100) run(1e4) bd.disable() nve = md.integrate.nve(group = group.all()) # test mesh order parameter from hoomd import metadynamics mesh = metadynamics.cv.mesh(nx=32,mode={'A': 1}) cv0 = 0.025 mesh.set_params(umbrella='harmonic',cv0=cv0,kappa=10000/cv0**2) # energy (= kinetic energy + potential energy + umbrella energy) should be conserved with 4-5 sigfigs in single precision # & cv_mesh should be close to target value (cv0) log = analyze.log(quantities=['kinetic_energy','potential_energy','umbrella_energy_mesh','cv_mesh'],filename='test.log',period=100,overwrite=True) run(1e5) <file_sep>#ifndef __COLLECTIVE_WRAPPER_H__ #define __COLLECTIVE_WRAPPER_H__ #include "CollectiveVariable.h" #include <hoomd/GlobalArray.h> /*! Wrapper to convert a regular ForceCompute into a CollectiveVariable */ class CollectiveWrapper : public CollectiveVariable { public: /*! Constructs the collective variable \param sysdef The system definition \param name The name of this collective variable */ CollectiveWrapper(std::shared_ptr<SystemDefinition> sysdef, std::shared_ptr<ForceCompute> fc, const std::string& name); virtual ~CollectiveWrapper() {} /*! Returns the current value of the collective variable * \param timestep The currnt value of the timestep */ virtual Scalar getCurrentValue(unsigned int timestep) { computeCV(timestep); return m_energy; } //! Set autotuner parameters /*! \param enable Enable/disable autotuning \param period period (approximate) in time steps when returning occurs */ virtual void setAutotunerParams(bool enable, unsigned int period) { CollectiveVariable::setAutotunerParams(enable, period); m_tuner_reduce->setPeriod(period); m_tuner_reduce->setEnabled(enable); m_tuner_scale->setPeriod(period); m_tuner_scale->setEnabled(enable); } protected: std::shared_ptr<ForceCompute> m_fc; //!< The parent force compute Scalar m_energy; //!< The potential energy #ifdef ENABLE_CUDA GlobalArray<Scalar> m_sum; //!< for reading back potential energy from GPU std::unique_ptr<Autotuner> m_tuner_scale; //!< Autotuner for scaling forces std::unique_ptr<Autotuner> m_tuner_reduce; //!< Autotuner for collective variable reduction #endif virtual void computeCV(unsigned int timestep); /*! Compute the biased forces for this collective variable. The force that is written to the force arrays must be multiplied by the bias factor. \param timestep The current value of the time step */ virtual void computeBiasForces(unsigned int timestep); //! Compute bias force on GPU void computeBiasForcesGPU(unsigned int timestep); //! Compute collective variable on GPU void computeCVGPU(unsigned int timestep); }; //! Export the CollectiveVariable class to python void export_CollectiveWrapper(pybind11::module& m); #endif // __COLLECTIVE_WRAPPER_H__ <file_sep>"""Commands to integrate the equation of motion using metadynamics. This package implements a metadynamics integration mode using an adaptive bias potential. Metadynamics integration (integrate.mode_metadynamics) can be combined with any standard integration methods, such as NVT, NVE etc. supported by HOOMD-Blue. In addition to integration methods, metadynamics also requires at least one :mod:`collective variable <metadynamics.cv>` to be defined, the values of which will be sampled to update the bias potential. The forces generated from the bias potential are added to the particles during the simulation. This package supports well-tempered metadynamics with multiple collective variables, on- and off-grid bias potentials, and saving of and restarting from grid information. It is also possible to simply equilibrate the system in the presence of a previously generated bias potential, without updating the latter, to sample a histogram of values of the collective variable (i.e. for error control). """ from hoomd.metadynamics import _metadynamics from hoomd.metadynamics import cv import hoomd from hoomd import md class mode_metadynamics(md.integrate._integrator): """Enables integration using metadynamics, a free energy technique. The command **integrate.mode_metadynamics** sets up MD integration with an arbitrary integration method (such as NVT), to continuously sample the collective variables and use their values to update the bias potential, from which forces are calculated. Some features of this package are loosely inspired by the PLUMED plugin for Metadynamics, http://www.plumed-code.org/. The metadynamics algorithm is reviewed in detail in [Barducci et al., Metadynamics, Wiley Interdiscipl. Rev.: Comput. Mol. Sci. 5, pp. 826-843 (2011)](http://dx.doi.org/10.1002/wcms.31) Explictly, the metadynamics biasing potential :math:`V(s,t)` at time :math:`t` takes the form .. math:: V(\mathbf{s}, t) = \sum\limits_{t'=0, t_G, 2 t_G,\dots}^{t'<t} W e^{-\frac{V[\mathbf{s}(\mathbf{r}(t')]}{\Delta T}} \exp\left\{-\sum\limits_{i=1}^d \frac{[s_i(\mathbf{r}) - s_i(\mathbf{r}(t'))]^2}{2\sigma_i^2}\right\}, where * :math:`s` is the vector of collective variables, * :math:`t_G` is the stride (in time units); it should be chosen on the order of several :math:`\tau` , where :math:`\tau` is a typical internal relaxation time of the system, * :math:`W` is the height of Gaussians added during the simulation (in energy units), * :math:`\sigma_i` is the standard deviation of Gaussian added for collective variable :math:`i`. Before a metadynamics run, the collective variables need to be defined and the integration methods need to specified. While metadynamics in principle works independently of the integration method, it has thus far been tested with :class:`integrate.nvt` only. During a metadynamics run, the potential is updated every :math:`t_G/\Delta t` steps and forces derived from the potential are applied to the particles every step. The result of a metadynamics run is either a hills file (which contains the positions and heights of Gaussians that are added together to form the bias potential), or a bias potential evaluated on a grid. The negative of the bias potential can be used to calculate the free energy surface (FES). By default, **integrate.mode_metadynamics** uses the *well-tempered* variant of metadynamics, where a shift temperature :math:`\Delta T` is defined, which converges to a well-defined bias potential after a typical time for convergence that depends entirely on the system simulated and on the value of :math:`\Delta T`. The latter quantity should be chosen such that :math:`(\Delta T + T) k_B T` equals the typical height of free energy barriers in the system. By contrast, *standard* metadynamics does not converge to a limiting potential, and thus the free energy landscape is 'overfilled'. Standard metadynamics corresponds to :math:`\Delta T = \infty`. If the goal is to approximate standard metadynamics, large values (e.g. :math:`\Delta T = 100`) of the temperature shift can therefore be used. .. note:: The collective variables need to be defined before the first call to **run()**. They cannot be changed after that (i.e. after **run()** has been called at least once), since the integrator maintains a history of the collective variables also in between multiple calls to the **run()** command. The only way to reset metadynamics integration is to use another **integrate.mode_metadynamics** instance instead of the original one. Two modes of operation are supported: 1. Resummation of Gaussians every time step 2. Evaluation of the bias potential on a grid In the first mode, the integration will slow down with increasing simulation time, as the number of Gaussians increases with time. In the second mode, a current grid of values of the collective variables is maintained and updated whenever a new Gaussian is deposited. This avoids the slowing down, and this mode is thus preferrable for long simulations. However, a reasonable set of grid points has to be chosen for accuracy (typically on the order of 200-500, depending on the collective variable and the system under study). It is possible to output the grid after the simulation, and to restart from the grid file. It is also possible to restart from the grid file and turn off the deposition of new Gaussians, e.g., to equilibrate the system in the bias potential landscape and measure the histogram of the collective variable, to correct for errors. .. note:: Grid mode is automatically enabled when it is specified for all collective variables simultaneously. Otherwise, it has to be disabled for all collective variables at the same time. In the following, we give an example for using metadynamics in a diblock copolymer system. This sets up metadynamics with Gaussians of height :math:`W =1` (in energy units), which are deposited every :math:`t_G/\Delta t=5000` steps :math:`\Delta t = 0.005` in time units), with a well-tempered metadynamics temperature shift :math:`\Delta T = 7` (in temperature units). The collective variable is a lamellar order parameter. At the end of the simulation, the bias potential is saved into a file. .. code:: all = group.all meta = metadynamics.integrate.mode_metadynamics dt=0.005, mode="well_tempered", W=1,stride=5000, deltaT=dT) # Use the NVT integration method integrate.nvt(group=all, T=1, tau=0.5) # set up a collective variable on a grid lamellar = metadynamics.cv.lamellar( sigma=0.05, mode=dict(A=1.0, B=-1.0), lattice_vectors=[(0,0,3)], phi=[0.0]) lamellar.enable_grid(cv_min=-2.0, cv_max=2.0, num_points=400) # Run the metadynamics simulation for 10^5 time steps run(1e5) # dump bias potential meta.dump_grid("grid.dat") If the saved bias potential should be used to continue the simulation from, this can be accomplished by the following piece of code: .. code:: meta = metadynamics.integrate.mode_metadynamics(dt=0.005, W=1) integrate.nvt(group=all, T=1, tau=0.5) # set up a collective variable on a grid lamellar = metadynamics.cv.lamellar( sigma=0.05, mode=dict(A=1.0, B=-1.0), lattice_vectors=[(0,0,3)], phi=[0.0]) lamellar.enable_grid(cv_min=-2.0, cv_max=2.0, num_points=400) # restart from saved bias potential meta.restart_from_grid("grid.dat") run(1e5) :param dt: Each time step of the simulation run() will advance the real time of the system forward by \a dt (in time units) :param stride: Interval (number of time steps) between depositions of Gaussians :param mode: Metadynamics mode - "standard" (default) or "well_tempered" :param W: *(only in mode="standard" or "well_tempered")* Height of Gaussians (in energy units) deposited :param deltaT: *(only in mode="well_tempered")* Temperature shift (in temperature units) for well-tempered metadynamics :param T: *(only for adaptive Gaussians)* Temperature :param filename: *(optional)* Name of the log file to write hills information to :param overwrite: *(optional)* True if the hills file should be overwritten :param add_hills: *(optional)* True if Gaussians should be deposited during the simulation """ def __init__(self, dt, stride, mode="standard", W=1.0, deltaT=1.0, T=1.0, filename="", overwrite=False, add_hills=True): hoomd.util.print_status_line() # initialize base class md.integrate._integrator.__init__(self) if (mode == "standard"): cpp_mode = _metadynamics.IntegratorMetaDynamics.mode.standard elif (mode == "well_tempered"): cpp_mode = _metadynamics.IntegratorMetaDynamics.mode.well_tempered else: hoomd.context.msg.error("integrate.mode_metadynamics: Unsupported metadynamics mode.\n") raise RuntimeError('Error setting up Metadynamics.') # initialize the reflected c++ class self.cpp_integrator = _metadynamics.IntegratorMetaDynamics( hoomd.context.current.system_definition, dt, W, deltaT, T, stride, add_hills, filename, overwrite, cpp_mode) self.supports_methods = True hoomd.context.current.system.setIntegrator(self.cpp_integrator) self.cv_names = [] def update_forces(self): """Registers the collective variables with the C++ integration class""" if self.cpp_integrator.isInitialized(): notfound = False num_cv = 0 for f in hoomd.context.current.forces: if isinstance(f, cv._collective_variable) and f.grid_set: if f.name != self.cv_names[num_cv]: notfound = True num_cv += 1 if (len(self.cv_names) != num_cv) or notfound: hoomd.context.msg.error( "integrate.mode_metadynamics: Set of collective variables has changed since last run. This is unsupported.\n") raise RuntimeError('Error setting up Metadynamics.') # (re-) register collective variables with integrator self.cv_names = [] self.cpp_integrator.removeAllVariables() for f in hoomd.context.current.forces: if isinstance(f, cv._collective_variable): # enable histograms if required if f.grid_set is True: self.cpp_integrator.registerCollectiveVariable( f.cpp_force, f.sigma, f.cv_min, f.cv_max, f.num_points) self.cv_names.append(f.name) else: if not f.umbrella: hoomd.context.msg.warning( "integrate.mode_metadynamics: Grid parameters not set. Ignoring CV " + f.name) if len(self.cv_names) == 0: hoomd.context.msg.warning( "integrate.mode_metadynamics: No collective variables defined. Continuing with simulation anyway.\n") if not self.cpp_integrator.isInitialized(): self.cpp_integrator.setGrid(True) md.integrate._integrator.update_forces(self) def dump_grid(self, filename1, filename2="", period=0): """Dump information about the bias potential. If a grid has been previously defined for the collective variables, this method dumps the values of the bias potential evaluated on the grid points to a file, for later restart or analysis. This method can be used to dump the grid during the simulation or at any time before or after the simulation. :param filename1: First file to dump the grid to :param filename2: Second file to dump the grid to, if a period has been set. If this parameter is given, files are dumped in an alternating fashion. :param period: Number of timesteps between periodic dumps. If zero (default), file is written when the command is called. """ hoomd.util.print_status_line() self.cpp_integrator.dumpGrid(filename1, filename2, int(period)) def restart_from_grid(self, filename): """Restart from a previously saved grid file. This command may be used before starting the simulation with the run() command. Upon start of the simulation, the supplied grid file is then read in and used to initialize the bias potential. :param filename: The file to read, which has been previously generated by dump_grid """ hoomd.util.print_status_line() self.cpp_integrator.restartFromGridFile(filename) def reset_histogram(self): """Reset the histogram. This command resets the histogram of values of the collective variable visited. """ hoomd.util.print_status_line() self.cpp_integrator.resetHistogram() def set_params(self, add_hills=None, mode=None, stride=None, adaptive=None, sigma_g=None, multiple_walkers=None): """Set parameters of the integration. :param mode: The variant of metadynamics to be used :param add_hills: True if new Gaussians should be added during the simulation :param stride: The stride for bias potential updates :param adaptive: True if adaptive Gaussians should be used :param sigma_g: Estimated RMSD of particle positions for adapative Gaussian mode """ hoomd.util.print_status_line() if add_hills is not None: self.cpp_integrator.setAddHills(add_hills) if mode is not None: if (mode == "standard"): cpp_mode = _metadynamics.IntegratorMetaDynamics.mode.standard elif (mode == "well_tempered"): cpp_mode = _metadynamics.IntegratorMetaDynamics.mode.well_tempered else: hoomd.context.msg.error("integrate.mode_metadynamics: Unsupported metadynamics mode.\n") raise RuntimeError('Error setting up Metadynamics.') self.cpp_integrator.setMode(cpp_mode) if stride is not None: self.cpp_integrator.setStride(int(stride)) if adaptive is not None: self.cpp_integrator.setAdaptive(adaptive) if sigma_g is not None: self.cpp_integrator.setSigmaG(sigma_g) if multiple_walkers is not None: self.cpp_integrator.setMultipleWalkers(multiple_walkers)
563037ba2fa57940bc4e4a3d06dee726630a63b8
[ "Python", "CMake", "C++" ]
33
CMake
jglaser/metadynamics-plugin
387217474c9f5563eae94e0f26e15390049029de
4e4f78af672c70adcc9d307eae290d2c24caba91
refs/heads/main
<repo_name>zhaoyun168/swoole<file_sep>/go_test2.php <?php Co\run(function () { $wg = new \Swoole\Coroutine\WaitGroup(); $outChan = new Swoole\Coroutine\Channel(1); $requestUrl = "https://cn.bing.com/search?q=urldecode"; $urlArr = parse_url($requestUrl); $host = $urlArr['host']; $port = isset($urlArr['port']) ? $urlArr['port'] : 80; $uri = sprintf("%s?%s", $urlArr['path'], $urlArr['query']); for ($i = 1; $i <= 10;$i++) { $wg->add(); go(function () use ($outChan, $i, $host, $port, $uri) { $cli = new Swoole\Coroutine\Http\Client($host, $port); $cli->set( array( 'timeout' => 3 ) ); $cli->setHeaders( array( 'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36', ) ); $uri = sprintf("%s&page=%d", $uri, $i); $cli->get($uri); $html = $cli->statusCode; $cli->close(); if(strlen($html) > 0){ $outChan->push(array($i, $html)) ; } //出让协程执行 co::sleep(0.05); }); $wg->done(); } $wg->add(); go(function () use ($wg, $outChan) { while (true) { Co::sleep(1); var_dump($outChan->pop()); } $wg->done(); }); $wg->wait(); }); <file_sep>/swoole_timer_after.php <?php class Test { private $str = "Say Hello"; public function onAfter() { echo $this->str; // 输出”Say Hello“ } } $test = new Test(); swoole_timer_after(1000, array($test, "onAfter")); // 成员变量 swoole_timer_after(2000, function() use($test){ // 闭包 $test->onAfter(); // 输出”Say Hello“ }); <file_sep>/GoTestCommand.php <?php /** * swoole协程 */ namespace app\schedule\controller; use platform\common\LoggerClient; use think\console\Command; use think\console\Input; use think\console\Output; use think\console\input\Argument; use think\console\input\Option; use think\Db; class GoTestCommand extends Command { /** @var config */ private $config; /** @var db config */ private $dbConfig; //monolog object private $_instance; //monolog instance private $logger; //db object private $db; //处理重试次数 private $handle_num = 0; //最大处理重试次数 private $max_handle_num = 3; /** * 配置命令 */ protected function configure() { $this->setName('go:test:run') ->setDescription('update invalid status command'); } /** * swoole协程 * @param Input $input 输入 * @param Output $output 输出 * @return */ protected function execute(Input $input, Output $output) { //日志配置 if (!($this->_instance instanceof LoggerClient)) { $this->_instance = new LoggerClient(); } $this->logger = $this->_instance->getMonolog('update', BASE_ROOT . 'log/schedule/go_'.date('Y-m-d').'.log', 0); /** mysql数据库的配置 */ $this->dbConfig = require BASE_ROOT . '/config/database.php'; //数据库配置 $this->db = $this->getDbConnection($this->dbConfig); //更新状态 $this->updateInvalidStatus(); return 0; } /** * 连接数据库(重连机制) * @return object */ private function getDbConnection($dbConfig) { $try_times = 0; //重连次数 $conn = null; while (true) { ++$try_times; try { $conn = Db::connect($dbConfig); break; } catch (\Exception $e) { $this->logger->error(sprintf('[%s]第[%s]次连接数据库失败,错误为[%s]', $this->_instance->uniqid, $try_times, $e->getMessage())); sleep(2); continue; } } return $conn; } /** * 更新状态 * @return */ private function updateInvalidStatus() { $this->logger->info(sprintf('[%s]开始更新特慢病申报状态...', $this->_instance->uniqid)); $handle_start_time = date('Y-m-d H:i:s'); $execute_start_time = microtime(true); try { startHandle: $current_time = time(); $url = [ 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', 'https://www.jianshu.com/p/3ca61b47149a', ]; foreach ($url as $key => $value) { $result_info = $this->httpGet($value, []); $insert_data = [ 'result' => $result_info, 'time' => time(), ]; try { $this->db->name('http_result')->insert($insert_data); } catch (\Exception $e) { $this->logger->error(sprintf('[%s]操作数据库异常[%s]', $this->_instance->uniqid, $e->getMessage())); } } $this->handle_num = 0; $handle_end_time = date('Y-m-d H:i:s'); $execute_end_time = microtime(true); $execute_time = $execute_end_time - $execute_start_time; $this->logger->info(sprintf('[%s]更新特慢病申报状态结束...', $this->_instance->uniqid)); echo 'success|start_time:'.$handle_start_time.'|end_time:'.$handle_end_time.'|execute_time:'.$execute_time. "\r\n"; } catch (\Exception $e) { $this->handle_num++; //发生异常时,重试更新状态 if ($this->handle_num <= $this->max_handle_num) { $this->logger->error(sprintf('[%s]第[%s]次更新状态异常,异常信息为[%s],[%s]秒后继续重试...', $this->_instance->uniqid, $this->handle_num, $e->getMessage(), $this->handle_num * 5)); sleep($this->handle_num * 5); goto startHandle; } else { $this->logger->error(sprintf('[%s]第[%s]次更新状态异常,异常信息为[%s],不再重试', $this->_instance->uniqid, $this->handle_num, $e->getMessage())); } $handle_end_time = date('Y-m-d H:i:s'); $execute_end_time = microtime(true); $execute_time = $execute_end_time - $execute_start_time; echo 'error|start_time:'.$handle_start_time.'|end_time:'.$handle_end_time.'|execute_time:'.$execute_time. "\r\n"; } } protected function httpGet($url, $data) { if ($data) { $url .= '?' . http_build_query($data); } $curlObj = curl_init(); //初始化curl, curl_setopt($curlObj, CURLOPT_URL, $url); //设置网址 curl_setopt($curlObj, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($curlObj, CURLOPT_TIMEOUT, 5); curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1); //将curl_exec的结果返回 curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curlObj, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($curlObj, CURLOPT_HEADER, 0); //是否输出返回头信息 $response = curl_exec($curlObj); //执行 if (curl_errno($curlObj)) { echo sprintf('curl请求异常[%s]', curl_error($curlObj)); } curl_close($curlObj); //关闭会话 return $response; } } <file_sep>/swoole_timer_clear.php <?php $timerid = swoole_timer_tick(1000,function(){ echo time()."\n"; }); swoole_timer_tick(1000,function() use($timerid) { swoole_timer_clear($timerid); }); <file_sep>/process_test.php <?php $start_time = microtime(TRUE); $cmds = [ "uname", "date", "whoami" ]; foreach ($cmds as $cmd) { $process = new swoole_process( "my_process", true); $process->start(); $process->write($cmd); //通过管道发数据到子进程。管道是单向的:发出的数据必须由另一端读取。不能读取自己发出去的 //echo $rec = $process->read();//同步阻塞读取管道数据 //使用swoole_event_add将管道加入到事件循环中,变为异步模式 swoole_event_add($process->pipe, function($pipe) use($process) { echo $rec = $process->read(); swoole_event_del($process->pipe);//socket处理完成后,从epoll事件中移除管道 }); } //子进程创建成功后要执行的函数 function my_process(swoole_process $worker){ sleep(1);//暂停1s $cmd = $worker->read(); // $return = exec($cmd);//exec只会输出命令执行结果的最后一行内容,且需要显式打印输出 ob_start(); passthru($cmd);//执行外部程序并且显示未经处理的、原始输出,会直接打印输出。 $return = ob_get_clean(); if(!$return) $return = 'null'; $worker->write($return);//写入数据到管道 } //子进程结束必须要执行wait进行回收,否则子进程会变成僵尸进程 while($ret = swoole_process::wait()){// $ret 是个数组 code是进程退出状态码, $pid = $ret['pid']; echo PHP_EOL."Worker Exit, PID=" . $pid . PHP_EOL; } $end_time = microtime(TRUE); echo sprintf("use time:%.3f s\n", $end_time - $start_time); <file_sep>/process_start.php <?php $process = new swoole_process('callback_function', true); //子进程执行的逻辑 function callback_function(swoole_process $worker) { echo '子进程创建成功'; } $ret = $process->start(); echo '子进程进程号为'.$process->pid . "\r\n"; echo '管道的文件描述符为'.$process->pipe . "\r\n"; <file_sep>/spl_queue.php <?php $queue = new SplQueue; $data = ['name' => 'tianyu', 'age' => 21]; //入队 $queue->push($data); //出队 $data = $queue->shift(); //查询队列中的排队数量 echo $n = count($queue); <file_sep>/go1.php <?php //sleep(100); go(function () { echo "hello go1 \n"; }); echo "hello main \n"; go(function () { echo "hello go2 \n"; }); <file_sep>/swoole_go_mysql.php <?php class AysMysql{ public $dbSource = ""; public $dbConfig = []; public function __construct() { $this->dbSource = new Swoole\Coroutine\MySQL(); $this->dbConfig = [ 'host' => '127.0.0.1', 'port' => '3306', 'user' => 'root', 'password' => '<PASSWORD>', 'database' => 'test', 'charset' => 'utf8' ]; } /** * @Notes:mysql执行 * @Interface execute * @param $id * @param $username * @return bool * @Time: 2020/4/3 下午5:48 */ public function execute($id,$username){ go(function () use($id){ //connect $this->dbSource->connect($this->dbConfig); $sql = "select * from yb_users where id = ".$id; $res = $this->dbSource->query($sql); if($res === false){ var_dump("error"); } var_dump($res); $this->dbSource->close(); }); } } $obj = new AysMysql(); $obj->execute(1,'张三'); <file_sep>/swoole_go_mysql1.php <?php $swoole_mysql = new Swoole\Coroutine\MySQL(); go(function() use($swoole_mysql) { $swoole_mysql->connect([ 'host' => '127.0.0.1', 'port' => '3306', 'user' => 'root', 'password' => '<PASSWORD>', 'database' => 'test', 'charset' => 'utf8' ]); $res = $swoole_mysql->query('select * from yb_users'); print_r($res); }); <file_sep>/pc.php <?php $s_time = time(); echo '开始时间:'.date('H:i:s',$s_time).PHP_EOL; //进程数 $work_number=6; // $worker=[]; //模拟地址 $curl=[ 'https://blog.csdn.net/feiwutudou', 'https://wiki.swoole.com/wiki/page/215.html', 'http://fanyi.baidu.com/?aldtype=16047#en/zh/manager', 'http://wanguo.net/Salecar/index.html', 'http://o.ngking.com/themes/mskin/login/login.jsp', 'https://blog.csdn.net/marksinoberg/article/details/77816991' ]; //单线程模式 // foreach ($curl as $v) { // echo curldeta($v); // } //创建进程 for ($i=0; $i < $work_number; $i++) { //创建多线程 $pro=new swoole_process(function(swoole_process $work) use($i,$curl){ //获取html文件 $content=curldeta($curl[$i]); //写入管道 $work->write($content.PHP_EOL); },true); $pro_id=$pro->start(); $worker[$pro_id]=$pro; } //读取管道内容 foreach ($worker as $v) { echo $v->read().PHP_EOL; } //模拟爬虫 function curldeta($curl_arr) {//file_get_contents echo $curl_arr.PHP_EOL; file_get_contents($curl_arr); } //进程回收 swoole_process::wait(); $e_time = time(); echo '结束时间:'.date('H:i:s',$e_time).PHP_EOL; echo '所用时间:'.($e_time-$s_time).'秒'.PHP_EOL; ?> <file_sep>/swoole_timer_ds.php <?php swoole_timer_tick(1000, function(){ echo "timeout\n"; }); <file_sep>/swoole_timer1.php <?php $str = "Say "; $timer_id = swoole_timer_tick( 1000 , function($timer_id , $params) use ($str) { echo $timer_id . $str . $params; // 输出“Say Hello” } , "Hello" ); <file_sep>/swoole_go.php <?php $client = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP); $client->connect("127.0.0.1", 8888, 0.5); //调用connect将触发协程切换 $client->send("hello world from swoole"); //调用recv将触发协程切换 $ret = $client->recv(); $client->close(); echo $ret; <file_sep>/process_name.php <?php $process = new swoole_process('callback_function', true); //子进程执行的逻辑 function callback_function(swoole_process $worker) { $worker->name('child process'); swoole_timer_tick(2000,function(){ echo time(); }); } $pid = $process->start(); swoole_set_process_name('parent process'); swoole_timer_tick(2000,function(){ echo time(); }); <file_sep>/process_queue.php <?php //获取多个网页信息 $urls = [ 'https://www.baidu.com', 'http://www.52fhy.com', 'http://www.52fhy.com/1', 'https://www.52fhy.com', ]; $process = new swoole_process(function(swoole_process $worker) use($urls) { foreach ($urls as $url) { $code = getHttpCode($url); $worker->push($url.': '.$code); } $worker->push('exit'); }, false, false); //不创建管道 $process->useQueue(1, 2); //使用消息队列。消息队列通信方式与管道不可共用。消息队列不支持EventLoop,使用消息队列后只能使用同步阻塞模式非阻塞 $process->start(); while(1){ $ret = $process->pop(); if($ret == 'exit') break; echo sprintf("%s\n", $ret); } echo "ok.\n"; while($ret = swoole_process::wait()){ echo PHP_EOL."Worker Exit, PID=" . $ret['pid'] . PHP_EOL; } /** * 获取网页http code */ function getHttpCode($url){ //省略 } <file_sep>/process.php <?php $process = new swoole_process('callback_function', true); $pid = $process->start(); function callback_function(swoole_process $worker) { $worker->exec('/usr/bin/php', array(__DIR__.'/swoole_server.php')); } <file_sep>/go_xc.php <?php $start_time = time(); for ($i = 0; $i <= 500; $i++) { go(function ()use($i,$start_time){ $cli = new Swoole\Coroutine\Http\Client('www.baidu.com'); $cli->setHeaders([ 'Host' => "www.baidu.com", "User-Agent" => 'Chrome/49.0.2587.3', 'Accept' => 'text/html,application/xhtml+xml,application/xml', 'Accept-Encoding' => 'gzip', ]); $cli->set([ 'timeout' => 0.11]); $cli->get('/'); $cli->close(); echo "协程{$i}已完成,耗时".(time()-$start_time).PHP_EOL; }); } /* $start_time = time(); for ($i = 0; $i <= 500; $i++) { $url = 'https://www.baidu.com/'; $content = file_get_contents($url); echo "普通{$i}已完成\n"; } */ echo "非携程完成时间:" . (time() - $start_time); <file_sep>/process_duo_1.php <?php echo PHP_EOL . time() ; $worker_num =3;//创建的进程数 for($i=0;$i<$worker_num ; $i++){ $process = new swoole_process('callback_function_we_write'); $pid = $process->start(); } function callback_function_we_write(swoole_process $worker){ for($i=0;$i<100000000;$i++){} echo PHP_EOL . time() ; } <file_sep>/swoole_table.php <?php $table = new swoole_table(1024); $table->column('id', swoole_table::TYPE_INT, 4); //1,2,4,8 $table->column('name', swoole_table::TYPE_STRING, 64); $table->column('num', swoole_table::TYPE_FLOAT); $table->create(); $table->set('<EMAIL>', array('id' => 145, 'name' => 'rango', 'num' => 3.1415)); $table->set('<EMAIL>', array('id' => 358, 'name' => "Rango1234", 'num' => 3.1415)); $table->set('<EMAIL>', array('id' => 189, 'name' => 'rango3', 'num' => 3.1415)); $data = $table->get('<EMAIL>'); $table->del('<EMAIL>'); $lock = new Swoole\Lock(SWOOLE_MUTEX); $lock->lock(); /** 事务性处理。 **/ $lock->unlock(); echo count($table); // 获得有多少条记录。 foreach($table as $value){ print_r($value); } <file_sep>/swoole_go_client1.php <?php use Swoole\Coroutine as co; co::create(function () { $cli = new co\Http2\Client('127.0.0.1', 9518); $cli->set([ 'timeout' => 1]); $cli->connect(); $req = new co\Http2\Request; $req->path = "/index.html"; $req->headers = [ 'host' => "localhost", "user-agent" => 'Chrome/49.0.2587.3', 'accept' => 'text/html,application/xhtml+xml,application/xml', 'accept-encoding' => 'gzip', ]; $req->cookies = ['name' => 'rango', 'email' => '<EMAIL>']; var_dump($cli->send($req)); $resp = $cli->recv(); var_dump($resp); }); <file_sep>/TaskCommand.php <?php /** * swoole异步任务 */ namespace app\schedule\controller; use platform\common\LoggerClient; use think\console\Command; use think\console\Input; use think\console\Output; use think\console\input\Argument; use think\console\input\Option; use think\Db; class TaskCommand extends Command { /** @var config */ private $config; /** @var db config */ private $dbConfig; //monolog object private $_instance; //monolog instance private $logger; //db object private $db; //处理重试次数 private $handle_num = 0; //最大处理重试次数 private $max_handle_num = 3; private $serv; /** * 配置命令 */ protected function configure() { $this->setName('task:run') ->setDescription('asynchronous task command'); } /** * swoole协程 * @param Input $input 输入 * @param Output $output 输出 * @return */ protected function execute(Input $input, Output $output) { //日志配置 if (!($this->_instance instanceof LoggerClient)) { $this->_instance = new LoggerClient(); } $this->logger = $this->_instance->getMonolog('update', BASE_ROOT . 'log/schedule/task_'.date('Y-m-d').'.log', 0); /** mysql数据库的配置 */ $this->dbConfig = require BASE_ROOT . '/config/database.php'; //数据库配置 $this->db = $this->getDbConnection($this->dbConfig); //开启异步任务服务 $this->start(); return 0; } /** * 连接数据库(重连机制) * @return object */ private function getDbConnection($dbConfig) { $try_times = 0; //重连次数 $conn = null; while (true) { ++$try_times; try { $conn = Db::connect($dbConfig); break; } catch (\Exception $e) { $this->logger->error(sprintf('[%s]第[%s]次连接数据库失败,错误为[%s]', $this->_instance->uniqid, $try_times, $e->getMessage())); sleep(2); continue; } } return $conn; } /** * 开启异步任务服务 * @return */ private function start() { $this->logger->info(sprintf('[%s]开启异步任务服务...', $this->_instance->uniqid)); $this->serv = new \swoole_server("0.0.0.0", 9501); $this->serv->set(array( 'worker_num' => 1, //一般设置为服务器CPU数的1-4倍 'daemonize' => 0, //以守护进程执行 'max_request' => 10000, 'dispatch_mode' => 2, 'task_worker_num' => 8, //task进程的数量 "task_ipc_mode " => 3, //使用消息队列通信,并设置为争抢模式 "log_file" => "/var/www/html/swoole_test/task_test.log" ,//日志 )); $this->serv->on('Receive', array($this, 'onReceive')); // bind callback $this->serv->on('Task', array($this, 'onTask')); $this->serv->on('Finish', array($this, 'onFinish')); $this->serv->start(); } public function onReceive(\swoole_server $serv, $fd, $from_id, $data) { $this->logger->info(sprintf('[%s]Get Message From Client %s:%s', $this->_instance->uniqid, $fd, $data)); // send a task to task worker. $serv->task($data); } public function onTask($serv, $task_id, $from_id, $data) { $array = json_decode($data, true); if ($array['url']) { return $this->httpGet($array['url'], $array['param']); } } public function onFinish($serv, $task_id, $data) { $this->logger->info(sprintf('[%s]Task %s finish', $this->_instance->uniqid, $task_id)); $this->logger->info(sprintf('[%s]Result: %s', $this->_instance->uniqid, $data)); $insert_data = [ 'result' => $data, 'time' => time(), ]; try { $this->db->name('http_result')->insert($insert_data); } catch (\Exception $e) { $this->logger->error(sprintf('[%s]操作数据库异常[%s]', $this->_instance->uniqid, $e->getMessage())); } } protected function httpGet($url, $data) { if ($data) { $url .= '?' . http_build_query($data); } $curlObj = curl_init(); //初始化curl, curl_setopt($curlObj, CURLOPT_URL, $url); //设置网址 curl_setopt($curlObj, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($curlObj, CURLOPT_TIMEOUT, 5); curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1); //将curl_exec的结果返回 curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curlObj, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($curlObj, CURLOPT_HEADER, 0); //是否输出返回头信息 $response = curl_exec($curlObj); //执行 if (curl_errno($curlObj)) { echo sprintf('curl请求异常[%s]', curl_error($curlObj)); } curl_close($curlObj); //关闭会话 return $response; } } <file_sep>/IndexController.php <?php class index { public function test($request, $response) { $response->header("Content-Type", "text/html; charset=utf-8"); $response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>"); } } <file_sep>/swoole_readfile.php <?php swoole_async_readfile( __DIR__."/Test.txt", function($filename, $content) { echo "$filename: $content"; }); <file_sep>/mysql_clinet.php <?php $client = new \swoole_client(SWOOLE_SOCK_TCP); $num=rand(111111,999999); $rts=$client->connect('127.0.0.1', 9508, 10) or die("连接失败");//链接mysql客户端 $sql =("select * from yb_users"); $client->send($sql); $resdata = $client->recv(); $resda=json_decode($resdata,true); $client->close(); echo json_encode($resda); <file_sep>/mysql_pool_server.php <?php /** * swoole 数据库连接池 BY 凌晨 'worker_num' => 20, //worker进程数量 'task_worker_num' => 10, //task进程数量 即为维持的MySQL连接的数量 'daemonize'=> 1, //设置守护进程 'max_request' => 10000, //最大请求数,超过了进程重启 'dispatch_mode' => 2,/ */ class server_db_pool { //swoole set params protected $task_worker_num; protected $work_num; protected $max_request; protected $dispatch_mode; protected $daemonize; protected $server_port; protected $log_file; //db params protected $db_host; protected $db_user; protected $db_pwd; protected $db_name; protected $db_port; public function __construct() { $this->host = "127.0.0.1"; // server监听的端口 $this->server_port = 9508; // server监听的端口 $this->worker_num = 5; $this->task_worker_num = 2; $this->dispatch_mode = 2; $this->daemonize = 0; $this->max_request = 10000; $filename=date("Y-m-d",time()); $this->log_file = "/var/www/html/swoole_test/swoole.log"; $this->serv = new swoole_server("127.0.0.1", $this->server_port); $this->serv->set( array( 'worker_num'=>$this->worker_num, 'task_worker_num' => $this->task_worker_num, 'max_request' => $this->max_request, 'daemonize' => $this->daemonize, 'log_file' => $this->log_file, 'dispatch_mode' => $this->dispatch_mode, )); } public function run(){ $this->serv->on('Receive', array($this, 'onReceive')); // Task 回调的2个必须函数 $this->serv->on('Task', array($this, 'onTask')); $this->serv->on('Finish', array($this, 'onFinish')); $this->serv->start(); } public function onReceive($serv, $fd, $from_id, $data){ $result = $this->serv->taskwait($data); if ($result !== false) { $result=json_decode($result,true); if ($result['status'] == 'OK') { $this->serv->send($fd, json_encode($result['data']) . "\n"); } else { $this->serv->send($fd, $result); } return; } else { $this->serv->send($fd, "Error. Task timeout\n"); } } public function onTask($serv, $task_id, $from_id, $sql){ static $link = null; HELL: if ($link == null) { $link = @mysqli_connect("127.0.0.1", "root", "<PASSWORD>", "test"); if (!$link) { $link = null; $this->serv->finish("ER:" . mysqli_error($link)); return; } } $result = $link->query($sql); if (!$result) { //如果查询失败了 if(in_array(mysqli_errno($link), [2013, 2006])){//错误码为2013,或者2006,则重连数据库,重新执行sql $link = null; goto HELL; }else{ $this->serv->finish("ER:" . mysqli_error($link)); return; } } if(preg_match("/^select/i", $sql)){//如果是select操作,就返回关联数组 $data = array(); while ($fetchResult = mysqli_fetch_assoc($result) ){ $data['data'][]=$fetchResult; } }else{//否则直接返回结果 $data['data'] = $result; } $data['status']="OK"; $this->serv->finish(json_encode($data)); } public function onFinish($serv, $task_id, $data){ echo "任务完成";//taskwait 不触发这个函数。。 } } $serv=new server_db_pool(); $serv->run(); <file_sep>/swoole_timer_after1.php <?php swoole_timer_after(1000, function(){ echo "timeout\n"; }); <file_sep>/go_redis.php <?php // 同步版, redis使用时会有 IO 阻塞 $cnt = 2000; for ($i = 0; $i < $cnt; $i++) { $redis = new \Redis(); $redis->connect('127.0.0.1',6379); $redis->auth('ab<PASSWORD>'); echo $key = $redis->get('name'); } /* // 单协程版: 只有一个协程, 并没有使用到协程调度减少 IO 阻塞 go(function () use ($cnt) { for ($i = 0; $i < $cnt; $i++) { $redis = new Co\Redis(); $redis->connect('127.0.0.1', 6379); $redis->auth('ab<PASSWORD>'); echo $redis->get('name'); } }); */ /* // 多协程版, 真正使用到协程调度带来的 IO 阻塞时的调度 for ($i = 0; $i < $cnt; $i++) { go(function () { $redis = new \Co\Redis(); $redis->connect('127.0.0.1', 6379); $redis->auth('ab<PASSWORD>'); echo $redis->get('name'); }); } */ <file_sep>/process_curl.php <?php //获取多个网页信息 $urls = [ 'https://www.baidu.com', 'http://www.52fhy.com', 'http://www.52fhy.com/1', 'https://www.52fhy.com', ]; foreach ($urls as $key => $url) { $process = new swoole_process(function(swoole_process $worker) use ($url){ $code = getHttpCode($url); $worker->write($code); }, true); $process->start(); swoole_event_add($process->pipe, function($pipe) use($process, $url) { echo sprintf("%s code: %s\n", $url, $process->read()); swoole_event_del($pipe); }); } echo "ok.\n"; while($ret = swoole_process::wait()){ // echo PHP_EOL."Worker Exit, PID=" . $ret['pid'] . PHP_EOL; } /** * 获取网页http code */ function getHttpCode($url){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); // curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "HEAD"); curl_setopt($ch, CURLOPT_NOBODY, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不验证证书 curl_setopt ($ch, CURLOPT_TIMEOUT_MS, 1000);//超时时间 curl_exec($ch); $info = curl_getinfo($ch); curl_close($ch); return (string)$info['http_code']; } <file_sep>/swoole_server.php <?php file_put_contents('test.log', 'Hello World'); <file_sep>/process_duo_2.php <?php echo PHP_EOL . time() ; for($i=0;$i<100000000;$i++){} for($i=0;$i<100000000;$i++){} for($i=0;$i<100000000;$i++){} echo PHP_EOL . time() ; <file_sep>/process_construct.php <?php $process = new swoole_process('callback_function'); //子进程执行的逻辑 function callback_function(swoole_process $worker) { swoole_timer_tick(2000,function(){ echo time(); }); } $pid = $process->start(); //父进程执行的逻辑 //监听子进程退出信号 swoole_process::signal(SIGCHLD, function($sig) { //必须为false,非阻塞模式 while($ret = swoole_process::wait(false)) { echo 'process end'; //执行回收后的处理逻辑,比如拉起一个新的进程 } }); <file_sep>/spl_queue_test.php <?php $splq = new SplQueue; for($i = 0; $i < 1000000; $i++) { $data = "hello $i\n"; $splq->push($data); if ($i % 100 == 99 and count($splq) > 100) { $popN = rand(10, 99); for ($j = 0; $j < $popN; $j++) { $splq->shift(); } } } $popN = count($splq); for ($j = 0; $j < $popN; $j++) { $splq->pop(); } <file_sep>/swoole_go_create.php <?php go(function () { $db = new Co\MySQL(); $server = array( 'host' => '127.0.0.1', 'user' => 'root', 'password' => '<PASSWORD>', 'database' => 'test', ); $db->connect($server); $result = $db->query('SELECT * FROM yb_users WHERE id = 3'); var_dump($result); });
ff3af4fe2dbee69a262dc10b12b6cafb12e0b9ba
[ "PHP" ]
34
PHP
zhaoyun168/swoole
10a7eeb6feb1ae97d4ee7c459a15cf07c9b84d21
21ecad16e07f4d318db28564c8b94a1d71c736a3
refs/heads/master
<repo_name>abramov1982/AlkoBot<file_sep>/bot/alkobot.py import telebot import parcer.parcer as parcer import json import time with open('token.json', 'r') as f: token = json.load(f)['token'] bot = telebot.TeleBot(token) time_list = [] chats_ids = [-1001206122362, -1001409669768] keyboard1 = telebot.types.ReplyKeyboardMarkup(True, True) keyboard1.row('/bash', '/ibash') keyboard1.row('/tost', '/anekdot') def timer(chat_id): time_list.append(chat_id) time.sleep(5) time_list.remove(chat_id) @bot.message_handler(commands=['start']) def start_message(message): bot.send_message(message.chat.id, 'Выбери', reply_markup=keyboard1) @bot.message_handler(commands=['tost']) def start_message(message): if message.chat.id not in time_list: bot.send_message(message.chat.id, parcer.rzhunemogu_api(6)) timer(message.chat.id) @bot.message_handler(commands=['anekdot']) def start_message(message): if message.chat.id not in time_list: bot.send_message(message.chat.id, parcer.rzhunemogu_api(11)) timer(message.chat.id) @bot.message_handler(commands=['bash']) def start_message(message): if message.chat.id not in time_list: bot.send_message(message.chat.id, parcer.bash_api()) timer(message.chat.id) @bot.message_handler(commands=['ibash']) def start_message(message): if message.chat.id not in time_list: bot.send_message(message.chat.id, parcer.ibash_api()) timer(message.chat.id) @bot.message_handler(regexp='^[т][о]*[л][я]*?[н]?[и]?[к]?[, ]?[ ]?[ст][ко][алс][жкт][ину]?[ий]?\s?[т]?[о]?[с]?[т]?$') def handle_message(message): if message.chat.id in chats_ids: bot.send_message(message.chat.id, parcer.rzhunemogu_api(6)) timer(message.chat.id) bot.polling() <file_sep>/bot/parcer/parcer.py import requests from bs4 import BeautifulSoup def rzhunemogu_api(slug): const_url = 'http://rzhunemogu.ru/Rand.aspx?CType=' try: r = requests.get(const_url + str(slug)) soup = BeautifulSoup(r.text, features="lxml") data = soup.find('content').text if r.status_code != 200: data = 'API недоступно' raise Exception(data) except Exception: return 'API недоступно' return data def ibash_api(): url = 'http://ibash.org.ru/random.php' try: r = requests.get(url) soup = BeautifulSoup(r.text, features="lxml") data = soup.find('div', {'class': 'quotbody'}) data = str(data).replace('<br/>', '\n')[22:].split('</div>')[0] if r.status_code != 200: data = 'API недоступно' raise Exception(data) except Exception: return 'API недоступно' return data def bash_api(): url = 'https://bash.im/random' try: r = requests.get(url) soup = BeautifulSoup(r.text, features="lxml") data = soup.find('div', {'class': 'quote__body'}) data = str(data).replace('<br/>', '\n')[32:].split('</div>')[0] if r.status_code != 200: data = 'API недоступно' raise Exception(data) except Exception: return 'API недоступно' return data ''' url = 'http://tostov.net/?m=theme&r=16&p=' pages = [i for i in range(1,17)] tost_list = [] def tost_parcing(): for i in pages: temp_url = url + str(i) r = requests.get(temp_url) soup = BeautifulSoup(r.text) tosts = soup.find_all('div', {'id': 'tostt'}) for tost in tosts: print(tost) tost_list.append(tost.text) '''<file_sep>/Dockerfile FROM python:3.7.6 ENV PORT 8081 COPY ./requirements.txt /bot/requirements.txt WORKDIR /bot RUN pip install -r requirements.txt COPY ./bot /bot ENTRYPOINT ["python"] CMD ["alkobot.py"] <file_sep>/README.md [![Travis][build-badge]][build] [build-badge]: https://img.shields.io/travis/abramov1982/AlkoBot/master.png?style=flat-square [build]: https://travis-ci.org/github/abramov1982/AlkoBot # AlkoBot Bot for fun Tosts, stories, anekdots Token needed
21dc40ae336d1753e4140b4c75cd944c2cc5f725
[ "Markdown", "Python", "Dockerfile" ]
4
Python
abramov1982/AlkoBot
d22a3891b74233170a337ed1abeec9436aeee338
e320d89b9a579d9cc2d6ce554a752b566b831d9e
refs/heads/master
<file_sep>EGCB ATIS Retriever =================== A simple Flask app to retrieve ATIS information from egcbatis.co.uk, extract pertinent data via regex and output in a format which can be read aloud by voice assistants (Siri, Alexa, etc). <file_sep>import flask import urllib3 import re app = flask.Flask(__name__) ALPHANUMERICS = { "A": "Alpha", "B": "Bravo", "C": "Charlie", "D": "Delta", "E": "Echo", "F": "Foxtrot", "G": "Golf", "H": "Hotel", "I": "India", "J": "Juliet", "K": "Kilo", "L": "Lima", "M": "Mike", "N": "November", "O": "Oscar", "P": "Papa", "Q": "Quebec", "R": "Romeo", "S": "Sierra", "T": "Tango", "U": "Uniform", "V": "Victor", "W": "Whisky", "X": "X-Ray", "Y": "Yankee", "Z": "Zulu" } def expand_alphanumeric(letter): return ALPHANUMERICS[letter] def expand_LR(lr): if lr.upper() == 'L': return "left" elif lr.upper() == 'R': return "right" raise RuntimeError("Unhandled runway assignment.") def talkify_runway(runway_code): t = runway_code[0] + " " + runway_code[1] if len(runway_code) == 3: t += " " + expand_LR(runway_code[2]) return t def talkify_circuit(cct): if cct.upper() == "LH": return "left hand" elif cct.upper() == "RH": return "right hand" raise RuntimeError("Unhandled circuit direction.") def talkify_pressure(pressure): t = "" for char in pressure: t += char + " " if int(pressure) <= 999: t += "hectopascals" return t def get_atis(): http = urllib3.PoolManager() r = http.request('GET', 'https://www.egcbatis.co.uk/main/index.php') if (r.status != 200): return None html = str(r.data) data = {} # Time timerx = re.compile("<span class=\"style_green_data_text\">\s?([0-9]{4})\s?<\/span>\s?<span class=\"style_headings\">\s?z") m = re.search(timerx, html) if m: data["time"] = str(m.group(1)[0:2]) + " " + str(m.group(1)[2:4]) + " zulu" # Information inforx = re.compile("INFO:\s?<\/span>\s?<span class=\"style_green_data_text\">\s?([A-Z]{1})\s?<\/span>") m = re.search(inforx, html) if m: data["information"] = expand_alphanumeric(m.group(1)) # Runway rwyrx = re.compile("RWY:\s?<\/span>\s?<span class=\"style_green_data_text\">\s?([0-9LR]{2,3})\s?<\/span>") m = re.search(rwyrx, html) if m: data["runway"] = talkify_runway(m.group(1)) # Circuit cctrx = re.compile("CCT:\s?<\/span>\s?<span class=\"style_green_data_text\">(RH|LH)<\/span>") m = re.search(cctrx, html) if m: data["circuit"] = talkify_circuit(m.group(1)) # MCR QNH qnhrx = re.compile("M\/CR QNH:\s?<\/span>\s?<span class=\"style_green_data_text\">([0-9]+)<\/span>") m = re.search(qnhrx, html) if m: data["qnh"] = talkify_pressure(m.group(1)) # Barton QFE qferx = re.compile("BARTON QFE:\s?<\/span>\s?<span class=\"style_green_data_text\">([0-9]+)<\/span>") m = re.search(qferx, html) if m: data["qfe"] = talkify_pressure(m.group(1)) return data def extract_data(key, data): body = "" try: body = f"{key} {data[key.lower()]}.</br>" except KeyError: body = f"{key} unknown.</br>" return body @app.route('/', methods=['GET']) def home(): return "<h1>EGCB ATIS retriever</h1><p>Use /atis/text to retrieve textual atis</p>" @app.route('/atis/text', methods=['GET']) def atis_text(): try: atis_data = get_atis() except Exception as e: return f"Error: {e}." if atis_data is None or len(atis_data) == 0: return "No data available." body = "Barton Information.</br>" body += extract_data("Time", atis_data) body += extract_data("Information", atis_data) body += extract_data("Runway", atis_data) body += extract_data("Circuit", atis_data) body += extract_data("QNH", atis_data) body += extract_data("QFE", atis_data) return body if __name__ == "__main__": app.run(host='0.0.0.0')
f4b5520a58f7c06ff7078eab71c98c0fe16e1546
[ "Markdown", "Python" ]
2
Markdown
arron-h/egcb-atis
9f24492f2504922f8b6846fbf5b83273ea8ed610
278be8b044e7ee183e0ca25df9999d02ae1b8b01
refs/heads/master
<repo_name>wzj7531/netcoreservices<file_sep>/README.md # netcoreservices .net core test project <file_sep>/src/SimpleWebApp/docker_entrypoint.sh #!/bin/bash cd /pipeline/source/app/publish dotnet SimpleWebApp.dll
ee19edeb2349cbed3be915976b9c0b4cf48c8786
[ "Markdown", "Shell" ]
2
Markdown
wzj7531/netcoreservices
b9a2b1d347b5b610a79d19fe91767eb2ac7ce4f4
b9684dd8075a841795a9fac79acaf9689ed8c599
refs/heads/master
<file_sep>import createRispaContext, { RispaContext, StartHandler } from './RispaContext' import PluginModule from './PluginModule' import { readPlugins, importPluginModules, PluginInfo } from './plugins' import { logError } from './log' export default function init(startHandler: StartHandler): Promise<RispaContext> { const pluginsInfo: PluginInfo[] = readPlugins(process.cwd()) const plugins: PluginModule[] = importPluginModules(pluginsInfo) const context = createRispaContext(plugins) return context.start(startHandler) .catch(error => { logError(error) process.exit(1) throw error }) } <file_sep>export { default as init } from './init' export { default as PluginInstance } from './PluginInstance' export { default as PluginApi } from './PluginApi' export { RispaContext } from './RispaContext' <file_sep>import { RispaContext } from './RispaContext' import PluginInstance from './PluginInstance' import PluginApi from './PluginApi' export interface IPluginName extends String { } type PluginModule = { name: IPluginName, path: string, instance: { new(context: RispaContext): PluginInstance }, api?: { new(instance: PluginInstance): PluginApi<PluginInstance>, pluginName: IPluginName }, after?: IPluginName[], } export default PluginModule <file_sep>import * as fs from 'fs-extra' import * as path from 'path' import PluginModule, { IPluginName } from './PluginModule' export const importModule = <T = any>(id: string): T => { const module = require(id) if (!module.default) { module.default = module } return module } export const searchForFile = (dir: string, filename: string): string => { let rootDir: string let currentDir: string = dir while (currentDir !== path.dirname(currentDir)) { if (fs.existsSync(path.resolve(currentDir, `./${filename}`))) { rootDir = currentDir break } currentDir = path.dirname(currentDir) } return rootDir } export const searchRootProjectDir = (dir: string): string => searchForFile(dir, 'rispa.json') export type PluginInfo = { name: string, packageName: IPluginName, packageAlias?: string, path: string, activator?: string, generators?: string, } export const readPlugins = (cwd: string): PluginInfo[] => { const pluginsCachePath = path.resolve(searchRootProjectDir(cwd), './build/plugins.json') const { plugins } = fs.readJsonSync(pluginsCachePath, { throws: false }) if (!plugins || plugins.length === 0) { throw new Error('Can\'t find plugins') } return plugins } export const importPluginModules = (plugins: PluginInfo[]): PluginModule[] => ( plugins.reduce((modules, plugin) => { if (plugin.activator) { const { default: instance, api, after = [], } = importModule(plugin.activator) modules.push({ name: api ? api.pluginName : plugin.packageName, path: plugin.path, instance, api, after, }) } return modules }, []) ) <file_sep># Plugin specification To create new plug-ins that are integrated into the project using `rispa`, you need the following: - Package should be identified as plugin for `rispa`, identification is carried out as follows * `package.json` should contain key `"rispa:name": "plugin-name"`, where `plugin-name` is treated as an alias of the package full name specified in the key `"name"` * package defined in scope `@rispa` - Package may declare a configuration file use key `"rispa:activator": "./relative/path/to/activator.js"` * File should exists, if file was not found error will be raised * The file will be processed during the initialization of any command executed in the context of the plugins `rispa` * If no such file is specified, the package simply remains as a passive dependency in the project - Activator should implement interface `Plugin` * `{ new(context: RispaContext): PluginInstance }` - default export of activator module, should return plugin instance constructor * `api` - named export. This constructor create instance, describes a public api for interacting with the plugin * `after` - named export. Describes the dependencies between plugins. Here are the names of the plugins, which must be initialized before the plugin starts working. It is assumed that there is a dependency graph, the cycles are blocked at initialization - The public API of the plugin must be accessible through the import of `plugin-name` and coincide with that specified in the activator - The plugin instance will implement the internal logic of the plugin. The method of pairing with api is not regulated and remains on the developer of the plugin, that is, there are no requirements for the matching of method names. - All plug-ins provide for import code ready for execution, without the use of additional means of transpiration. ## Plugin example `@application/plugin-name/package.json` ```json { "name": "plugin-name", "rispa:name": "pn", "rispa:activator": "./lib/activator.js", "rispa:generators": "./generators.js" } ``` `@application/plugin-name/src/activator.js` ```typescript import { RispaContext, PluginInstance, PluginApi } from '@rispa/core' import EventBusApi from '@rispa/events' import ConfigApi from '@rispa/config' export default class PluginNameInstance implements PluginInstance { config: object context: RispaContext eventBus: EventBusApi unsubscribe: Function constructor(context: RispaContext) { super(context) this.config = context.get(ConfigApi.pluginName).getConfig() this.eventBus = this.context.get(EventBusApi.pluginName) } public start() { this.eventBus.on('event:name', this.handleEvent) } public someMethod(name, value) {} private handleEvent() {} } class PluginNameApi extends PluginApi<PluginNameInstance> { static pluginName = 'plugin-name' someMethod(name, value) { this.instance.someMethod(name, value) } } export const api = PluginNameApi export const after = [EventBusApi.pluginName, ConfigApi.pluginName] ``` <file_sep>import { PluginManager } from './PluginManager' import PluginModule from './PluginModule' export class RispaValidateError extends Error { constructor(message: string, pluginModule: PluginModule) { const pluginInfo = pluginModule.name ? `[${pluginModule.name}] ` : '' const trace = `at rispa plugin (${pluginModule.path})` const spaces = ' ' super(`${pluginInfo}${message}\n${spaces}${trace}`) } } export type PluginValidatorErrors = RispaValidateError[] export type PluginValidator = (manager: PluginManager, pluginModule: PluginModule) => PluginValidatorErrors const error = (message: string, pluginModule: PluginModule) => ( new RispaValidateError(message, pluginModule) ) const validatePluginName = name => name && typeof name === 'string' function validateName(manager: PluginManager, pluginModule: PluginModule): PluginValidatorErrors { const errors = [] if (!validatePluginName(pluginModule.name)) { errors.push(error('Invalid plugin name', pluginModule)) } return errors } function validateInit(manager: PluginManager, pluginModule: PluginModule): PluginValidatorErrors { const errors = [] if (!pluginModule.instance) { errors.push(error('Init constructor required', pluginModule)) } else if (typeof pluginModule.instance !== 'function') { errors.push(error('Invalid init constructor type', pluginModule)) } return errors } function validateApi(manager: PluginManager, pluginModule: PluginModule): PluginValidatorErrors { const errors = [] if (pluginModule.api) { if (typeof pluginModule.api !== 'function') { errors.push(error('Invalid api constructor type', pluginModule)) } if (!validatePluginName(pluginModule.api.pluginName)) { errors.push(error(`Must be define 'pluginName' for api constructor`, pluginModule)) } } return errors } function validateDependencies(manager: PluginManager, pluginModule: PluginModule): PluginValidatorErrors { const errors = [] if (pluginModule.after) { if (!Array.isArray(pluginModule.after)) { errors.push(error('Invalid \'after\' type', pluginModule)) } else if (!pluginModule.after.every(validatePluginName)) { errors.push(error('Invalid \'after\' dependency plugin name', pluginModule)) } } return errors } const pluginValidators: PluginValidator[] = [ validateName, validateInit, validateApi, validateDependencies, ] export default pluginValidators <file_sep>import { DepGraph } from 'dependency-graph' import { RispaContext } from './RispaContext' import PluginInstance from './PluginInstance' import PluginModule, { IPluginName } from './PluginModule' import PluginApi from './PluginApi' import pluginValidators from './pluginValidators' export default function create(context: RispaContext): PluginManager { return new PluginManager(context) } export class PluginManager { private context: RispaContext private graph: DepGraph<PluginModule> private instances: Map<IPluginName, PluginInstance> private apiInstances: Map<IPluginName, PluginApi<PluginInstance>> constructor(context: RispaContext) { this.context = context this.graph = new DepGraph() this.instances = new Map() this.apiInstances = new Map() } /* Add plugin */ public add = (pluginModule: PluginModule) => { if (!this.has(pluginModule.name)) { this.graph.addNode(pluginModule.name as string, pluginModule) } else { throw `[${pluginModule.name}]: Plugin already added` } } /* Add plugin dependencies */ public addDependencies = (pluginModule: PluginModule) => { if (pluginModule.after) { pluginModule.after.forEach(dependencyName => { this.graph.addDependency( pluginModule.name as string, dependencyName as string, ) }) } } /* Remove plugin Throws if not started */ public remove = (pluginName: IPluginName) => { if (this.isStarted(pluginName)) { throw `[${pluginName}]: Can\'t remove started plugin` } this.graph.removeNode(pluginName as string) } /* Get plugin */ public get = (pluginName: IPluginName): PluginApi<PluginInstance> => { const instance = this.instances.get(pluginName) const pluginModule = this.graph.getNodeData(pluginName as string) if (!instance) { throw `[${pluginName}]: Instance is not yet created (add this plugin to the after)` } if (!pluginModule.api) { throw `[${pluginName}]: Not available API` } if (this.apiInstances.has(pluginName)) { return this.apiInstances.get(pluginName) } const apiInstance = new pluginModule.api(instance) this.apiInstances.set(pluginName, apiInstance) return apiInstance } /* Has plugin */ public has(pluginName: IPluginName): boolean { return this.graph.hasNode(pluginName as string) } /* Create instance */ public instantiate(pluginName: IPluginName): PluginInstance { const pluginModule = this.graph.getNodeData(pluginName as string) return new pluginModule.instance(this.context) } /* Validate plugin */ public validate(pluginModule): Array<Error | TypeError> { const errors = pluginValidators .reduce((results, validator) => ([ ...results, ...validator(this, pluginModule), ]), []) return errors } /* Create plugin instance and call start */ public start = (pluginName: IPluginName) => { if (this.isStopped(pluginName)) { const instance: PluginInstance = this.instantiate(pluginName) instance.start() this.instances.set(pluginName, instance) } } /* Stop started plugin */ public stop = (pluginName: IPluginName) => { if (this.isStarted(pluginName)) { this.instances.get(pluginName).stop() this.instances.delete(pluginName) } } public isStarted(pluginName: IPluginName): boolean { return this.instances.has(pluginName) } public isStopped(pluginName: IPluginName): boolean { return !this.isStarted(pluginName) } private validateAll() { const { plugins } = this.context const errors = plugins.reduce((results, pluginModule) => ([ ...results, ...this.validate(pluginModule), ]), []) if (errors.length > 0) { throw errors } } private build() { const { plugins } = this.context plugins.forEach(this.add) plugins.forEach(this.addDependencies) } private startAll() { const pluginsOrder = this.graph.overallOrder() pluginsOrder.forEach(this.start) } public async loadAll(): Promise<void> { // validate this.validateAll() // build this.build() // start all not started this.startAll() } } <file_sep>declare module "dependency-graph" { export class DepGraph<T> { nodes: { [key: string]: T, } // Node -> [Dependency Node] outgoingEdges: { [key: string]: string } // Node -> [Dependant Node] incomingEdges: { [key: string]: string } /** * Add a node to the dependency graph. If a node already exists, this method will do nothing. */ addNode: (node: string, data?: T) => void /** * Remove a node from the dependency graph. If a node does not exist, this method will do nothing. */ removeNode: (node: string) => void /** * Check if a node exists in the graph */ hasNode: (node: string) => boolean /** * Get the data associated with a node name */ getNodeData: (node: string) => T /** * Set the associated data for a given node name. If the node does not exist, this method will throw an error */ setNodeData: (node: string, data: T) => void /** * Add a dependency between two nodes. If either of the nodes does not exist, * an Error will be thrown. */ addDependency: (from: string, to: string) => void /** * Remove a dependency between two nodes. */ removeDependency: (from: string, to: string) => void /** * Get an array containing the nodes that the specified node depends on (transitively). * * Throws an Error if the graph has a cycle, or the specified node does not exist. * * If `leavesOnly` is true, only nodes that do not depend on any other nodes will be returned * in the array. */ dependenciesOf: (node: string, leavesOnly?: boolean) => string[] /** * get an array containing the nodes that depend on the specified node (transitively). * * Throws an Error if the graph has a cycle, or the specified node does not exist. * * If `leavesOnly` is true, only nodes that do not have any dependants will be returned in the array. */ dependantsOf: (node: string, leavesOnly?: boolean) => string[] /** * Construct the overall processing order for the dependency graph. * * Throws an Error if the graph has a cycle. * * If `leavesOnly` is true, only nodes that do not depend on any other nodes will be returned. */ overallOrder: (leavesOnly?: boolean) => string[] } } <file_sep>const createDebug = require('debug') export const log = createDebug('rispa:info:core') export const logError = createDebug('rispa:error:core') <file_sep>import createPluginManager, { PluginManager } from './PluginManager' import { IPluginName, default as PluginModule } from './PluginModule' import PluginInstance from './PluginInstance' import PluginApi from './PluginApi' export type StartHandler = (this: void, context: RispaContext) => RispaContext | Promise<RispaContext> export default function create(plugins: PluginModule[]): RispaContext { return new RispaContext(plugins) } export class RispaContext { public plugins: PluginModule[] private pluginManager: PluginManager constructor(plugins: PluginModule[]) { this.plugins = plugins this.pluginManager = createPluginManager(this) } public get(pluginName: IPluginName): PluginApi<PluginInstance> { if (!pluginName || typeof pluginName !== 'string') { throw 'Invalid plugin name' } return this.pluginManager.get(pluginName) } public start(startHandler: StartHandler): Promise<RispaContext> { return this.pluginManager.loadAll() .then(() => startHandler(this)) } } <file_sep>import { RispaContext } from './RispaContext' export default abstract class PluginInstance { context: RispaContext constructor(context?: RispaContext) { if (!context || !(context instanceof RispaContext)) { throw new TypeError('`context` must be passed in super') } this.context = context } // tslint:disable-next-line: no-empty public start() { } // tslint:disable-next-line: no-empty public stop() { } } <file_sep>import PluginInstance from './PluginInstance' import { StartHandler } from './RispaContext' import { IPluginName } from './PluginModule' abstract class PluginApi<TPluginInstance extends PluginInstance> { static pluginName: IPluginName static startHandler?: StartHandler instance: TPluginInstance constructor(instance: TPluginInstance) { this.instance = instance } } export default PluginApi
758e7febe6930c4ce6cd27f2bf7948fe48a07759
[ "Markdown", "TypeScript" ]
12
TypeScript
rispa-io/rispa-core
58a94adc62ab04c02d359b3f642414563f4578e0
75bd4b386c60f84f03673cad0caeb4e23f970e98
refs/heads/master
<repo_name>lennontu/ipackages<file_sep>/fs/mkdirp/main/index.js const fs = require('fs') const path = require('path') module.exports = async function mkdirp (dir) { const canAccess = await new Promise((resolve) => { fs.access(dir, (err) => { err ? resolve(false) : resolve(true) }) }) if (!canAccess) { await mkdirp(path.resolve(dir, '../')) return new Promise((resolve, reject) => { fs.mkdir(dir, (err) => { err ? reject(err) : resolve(true) }) }) } } <file_sep>/fs/loop/main/index.js const fs = require('fs') const path = require('path') module.exports = async function loop (dir) { } fs.readdir('./test', (err, files) => { if (err) console.log(err) else { console.log(files) } }) <file_sep>/fs/ls/main/index.js const fs = require('fs') module.exports = async function ls (dir) { return new Promise((resolve, reject) => { fs.readdir(dir, (err, files) => { err ? reject(err) : resolve(files) }) }) } <file_sep>/config/docker/1.Dockerfile # 参考 https://docs.docker.com/engine/reference/builder/ # 参考 https://docs.docker.com/develop/develop-images/dockerfile_best-practices/ FROM registry.cn-hangzhou.aliyuncs.com/aliyun-node/alinode:3.12.0-alpine ENV HOME=/home/daniujia RUN apk add --update tzdata && cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo "Asia/Shanghai" > /etc/timezone # clean cache RUN rm -rf /var/cache/apk/* && rm -rf /usr/local/share/.cache ENV TZ "Asia/Shanghai" # add group and user RUN addgroup -S daniujia -g 1001 && \ adduser -S -g daniujia -u 1001 daniujia # Create log and app directory RUN mkdir -p /var/log/daniujia /home/daniujia/src/app && \ cp /root/default.config.js /home/daniujia/default.config.js && \ chown -R daniujia:daniujia /var/log/daniujia /home/daniujia/ # Change workdir WORKDIR /home/daniujia/src/app USER daniujia RUN date # Check the env RUN (node -v | grep 8.12.0) && npm -v COPY --chown=daniujia:daniujia package.json ./ RUN npm install --production COPY --chown=daniujia:daniujia ./ ./ EXPOSE $EXPORT_WEB_PORT CMD npm run $START_SCRIPT <file_sep>/config/docker/Dockerfile # 参考 https://docs.docker.com/engine/reference/builder/ # 参考 https://docs.docker.com/develop/develop-images/dockerfile_best-practices/ # 参考 https://blog.csdn.net/wo18237095579/article/details/80540571 # 参考 http://www.runoob.com/docker/docker-tutorial.html # 参考 https://www.cnblogs.com/xiadongqing/p/6144053.html # 参考 多种方式(含docker容器)实现零停机时间(Zero-Downtime)部署 https://blog.csdn.net/shawyeok/article/details/51968554 # docker ps -a # https://docs.docker.com/engine/reference/commandline/docker/ # docker build . -t fe:fe # docker build --cache-from $CONTAINER_IMAGE:latest -t $CONTAINER_IMAGE:latest . # docker run -e WHO=craggy -e I=123 -i -t fe:fe env # docker run -i -t node:8.11.4-alpine /bin/ash # docker exec -it c938b3b1bc08 /bin/ash # docker run -v /var/log/test-docker:/var/log/test-docker -it registry.cn-hangzhou.aliyuncs.com/aliyun-node/alinode:3.12.0-alpine /bin/sh # docker rmi $(docker images | grep "none" | awk '{print $3}') //删除镜像 # sudo iptables -t nat -nvL # docker inspect -f '{{ .NetworkSettings.IPAddress }}' containerA # docker history --no-trunc registry.cn-hangzhou.aliyuncs.com/aliyun-node/alinode:latest | tac | tr -s ' ' | cut -d " " -f 5- | sed 's,^/bin/sh -c #(nop) ,,g' | sed 's,^/bin/sh -c,RUN,g' | sed 's, && ,\n & ,g' | sed 's,\s*[0-9]*[\.]*[0-9]*[kMG]*B\s*$,,g' | head -n -1 # https://store.docker.com/images/node # https://github.com/nodejs/docker-node FROM keymetrics/pm2:8-alpine # Install build dependencies for some modules # --no-cache: Download package index on-the-fly, no need to cleanup afterwards # --virtual: Bundle packages, remove whole bundle at once, when done RUN apk add --no-cache --virtual .gyp \ python \ make \ g++ # The module 'uws' need C++11 compiler and reinstall RUN apk add --update \ libc6-compat # Don’t run the application as root RUN deluser --remove-home node && \ delgroup node || true && \ addgroup -S ilennon -g 1001 && \ adduser -S -g ilennon -u 1001 ilennon # Create app directory WORKDIR /home/ilennon/src/app # Modify the workdir's group/user RUN chown -R ilennon:ilennon /home/ilennon/src/app # Check the env RUN node -v && npm -v # Create the logs folder RUN mkdir -p /var/log/ilennon && \ mkdir -p /home/ilennon/src/app/logs && \ chown -R ilennon:ilennon /var/log/ilennon # Install PM2 # RUN npm install -g pm2 # Install pm2 coffee-script v1 RUN pm2 install coffee-script # Run application with ilennon user USER ilennon # Install app dependencies # A wildcard is used to ensure both package.json AND package-lock.json are copied # where available (npm@5+) COPY package*.json ./ # If you are building your code for production # RUN npm install --only=production RUN npm install --only=production # Remove build dependencies after installed node dependencies USER root RUN rm package*.json && \ apk del .gyp USER ilennon # Bundle app source COPY --chown=ilennon:ilennon dist . EXPOSE 8080 EXPOSE 8443 EXPOSE 8445 EXPOSE 3071 EXPOSE 3072 CMD [ "pm2-runtime", "start", ".process.json", "--env=prod" ] <file_sep>/config/docker/docker-update.sh #!/bin/bash # /bin/bash docker-update.sh $APP_NAME $EXPORT_WEB_PORT APP_NAME=$1 DPORT=$2 while (( test -z "$(docker logs $APP_NAME | grep 'egg started')" )) do echo 'sleep 5s' sleep 5 done DOCKER_IP=$(docker inspect -f '{{ .NetworkSettings.IPAddress }}' $APP_NAME) LINE_NUMBERS=$(sudo iptables -t nat -L DOCKER -n --line-numbers | grep $DPORT | awk '{print $1}') if [ -n "$LINE_NUMBERS" ] then $(sudo iptables -t nat -R DOCKER $LINE_NUMBERS -p tcp --dport $DPORT -j DNAT --to-destination $DOCKER_IP:$DPORT) echo 'iptables -R successfully' else $(sudo iptables -t nat -A DOCKER -p tcp --dport $DPORT -j DNAT --to $DOCKER_IP:$DPORT) echo 'iptables -A successfully' fi <file_sep>/fs/rm/main/index.js const fs = require('fs') fs.readdir('./test', (err, files) => { if (err) console.log(err) else { console.log(files) } }) fs.rmdir('./test', (err) => { console.log('err', err) }) fs.rmdir('./test/3', (err) => { console.log('err', err) }) fs.unlink('./test/12', (err) => { console.log('err', err) }) fs.rename('./test', '../test', (err) => { console.log('err', err) }) <file_sep>/fs/find-regex/main/index.js // const fs = require('fs') // const path = require('path') module.exports = async function findRegex (dir, reg) { } <file_sep>/fs/mkdirp/README.md # mkdirp Like mkdir -p, but in node.js! # library example * How to install ``` npm install @ilennon/mkdirp ``` * How to use ```js const mkdirp = require('@ilennon/mkdirp') mkdirp('tmp/foo/bar/baz').then(() => { console.log('create tmp/foo/bar/baz successfully!') }).catch(() => { console.log('create tmp/foo/bar/baz failed!') }) ``` Output ``` create tmp/foo/bar/baz successfully! ``` And there would be a folder(tmp/foo/bar/baz) # command example * How to install ``` npm install @ilennon/mkdirp -g ``` * How to use ``` mkdirp dir1 dir2 ``` Then there would have two folders(dir1, dir2)
f975467273670a06a332827f92f9683008c10e7a
[ "JavaScript", "Dockerfile", "Markdown", "Shell" ]
9
JavaScript
lennontu/ipackages
a60252c40e0295ecee44d8fe09aec99657854980
b07a7bb83abf6e714bb60c9312e258a2f04de31b
refs/heads/main
<file_sep>// Copyright (c) 2021 The goaudiovideo developers. All rights reserved. // Project site: https://github.com/goaudiovideo/osc // Use of this source code is governed by a MIT-style license that // can be found in the LICENSE file for the project. package x32 import ( "bytes" "fmt" "testing" ) func TestMuteChannel(t *testing.T) { var tests = []struct { channel int want string expectError bool }{ {0, "/ch/01/mix/on\x00\x00\x00,i\x00\x00\x00\x00\x00\x00", true}, {1, "/ch/01/mix/on\x00\x00\x00,i\x00\x00\x00\x00\x00\x00", false}, {2, "/ch/02/mix/on\x00\x00\x00,i\x00\x00\x00\x00\x00\x00", false}, {32, "/ch/32/mix/on\x00\x00\x00,i\x00\x00\x00\x00\x00\x00", false}, {33, "/ch/01/mix/on\x00\x00\x00,i\x00\x00\x00\x00\x00\x00", true}, } for _, test := range tests { name := fmt.Sprintf("ch%2d", test.channel) t.Run(name, func(t *testing.T) { var b bytes.Buffer mixer := NewMixer(&b) err := mixer.MuteChannel(test.channel) if test.expectError { if err == nil { t.Errorf("expected error muting channel %d", test.channel) } } else { if err != nil { t.Errorf("error muting channel %d: %s", test.channel, err) } got := b.String() if got != test.want { t.Errorf("\t got = %x\n\t\t\twant = %x", got, test.want) } } }) } } func TestUnmuteChannel(t *testing.T) { var tests = []struct { channel int want string expectError bool }{ {0, "/ch/01/mix/on\x00\x00\x00,i\x00\x00\x00\x00\x00\x01", true}, {1, "/ch/01/mix/on\x00\x00\x00,i\x00\x00\x00\x00\x00\x01", false}, {2, "/ch/02/mix/on\x00\x00\x00,i\x00\x00\x00\x00\x00\x01", false}, {32, "/ch/32/mix/on\x00\x00\x00,i\x00\x00\x00\x00\x00\x01", false}, {33, "/ch/01/mix/on\x00\x00\x00,i\x00\x00\x00\x00\x00\x01", true}, } for _, test := range tests { name := fmt.Sprintf("ch%2d", test.channel) t.Run(name, func(t *testing.T) { var b bytes.Buffer mixer := NewMixer(&b) err := mixer.UnmuteChannel(test.channel) if test.expectError { if err == nil { t.Errorf("expected error unmuting channel %d", test.channel) } } else { if err != nil { t.Errorf("error unmuting channel %d: %s", test.channel, err) } got := b.String() if got != test.want { t.Errorf("\t got = %x\n\t\t\twant = %x", got, test.want) } } }) } } func TestMuteMain(t *testing.T) { want := "/main/st/mix/on\x00,i\x00\x00\x00\x00\x00\x00" var b bytes.Buffer mixer := NewMixer(&b) if err := mixer.MuteMain(); err != nil { t.Errorf("error muting main: %s", err) } got := b.String() if got != want { t.Errorf("\t got = %x\n\t\twant = %x", got, want) } } func TestUnmuteMain(t *testing.T) { want := "/main/st/mix/on\x00,i\x00\x00\x00\x00\x00\x01" var b bytes.Buffer mixer := NewMixer(&b) if err := mixer.UnmuteMain(); err != nil { t.Errorf("error unmuting main: %s", err) } got := b.String() if got != want { t.Errorf("\t got = %x\n\t\twant = %x", got, want) } } func TestNameChannel(t *testing.T) { var tests = []struct { channel int name string want string expectError bool }{ {0, "foo", "/ch/00/config/name\x00\x00,s\x00\x00foo\x00", true}, {1, "foo", "/ch/01/config/name\x00\x00,s\x00\x00foo\x00", false}, {1, "badTooLongName", "/ch/01/config/name\x00\x00,s\x00\x00foo\x00", true}, {32, "foo", "/ch/32/config/name\x00\x00,s\x00\x00foo\x00", false}, {33, "foo", "/ch/33/config/name\x00\x00,s\x00\x00foo\x00", true}, } for _, test := range tests { name := fmt.Sprintf("ch%02d_%s", test.channel, test.name) t.Run(name, func(t *testing.T) { var b bytes.Buffer mixer := NewMixer(&b) err := mixer.NameChannel(test.channel, test.name) if test.expectError { if err == nil { t.Errorf("expected error naming channel %d", test.channel) } } else { if err != nil { t.Errorf("error naming channel %d: %s", test.channel, err) } got := b.String() if got != test.want { t.Errorf("\t got = %x\n\t\t\twant = %x", got, test.want) } } }) } } func TestSetChannelIcon(t *testing.T) { var tests = []struct { channel int icon Icon want string expectError bool }{ {0, BassDrum, "/ch/00/config/icon\x00\x00,i\x00\x00\x00\x00\x00\x03", true}, {1, BassDrum, "/ch/01/config/icon\x00\x00,i\x00\x00\x00\x00\x00\x03", false}, {1, BassDrum, "/ch/01/config/icon\x00\x00,i\x00\x00\x00\x00\x00\x03", false}, {31, Laptop, "/ch/31/config/icon\x00\x00,i\x00\x00\x00\x00\x00\x3e", false}, {32, Cymbal, "/ch/32/config/icon\x00\x00,i\x00\x00\x00\x00\x00\x0a", false}, {33, Cymbal, "/ch/32/config/icon\x00\x00,i\x00\x00\x00\x00\x00\x0a", true}, } for _, test := range tests { name := fmt.Sprintf("ch%02d_%s", test.channel, test.icon) t.Run(name, func(t *testing.T) { var b bytes.Buffer mixer := NewMixer(&b) err := mixer.SetChannelIcon(test.channel, test.icon) if test.expectError { if err == nil { t.Errorf("expected error setting icon for channel %d", test.channel) } } else { if err != nil { t.Errorf("error setting icon for channel %d: %s", test.channel, err) } got := b.String() if got != test.want { t.Errorf("\t got = %x\n\t\t\twant = %x", got, test.want) } } }) } } func TestSetChannelColor(t *testing.T) { var tests = []struct { channel int color Color want string expectError bool }{ {0, RedText, "/ch/00/config/color\x00,i\x00\x00\x00\x00\x00\x01", true}, {1, RedText, "/ch/01/config/color\x00,i\x00\x00\x00\x00\x00\x01", false}, {32, BlueBackground, "/ch/32/config/color\x00,i\x00\x00\x00\x00\x00\x0c", false}, {33, RedText, "/ch/33/config/color\x00,i\x00\x00\x00\x00\x00\x01", true}, } for _, test := range tests { name := fmt.Sprintf("ch%02d_%s", test.channel, test.color) t.Run(name, func(t *testing.T) { var b bytes.Buffer mixer := NewMixer(&b) err := mixer.SetChannelColor(test.channel, test.color) if test.expectError { if err == nil { t.Errorf("expected error setting color for channel %d", test.channel) } } else { if err != nil { t.Errorf("error setting color for channel %d: %s", test.channel, err) } got := b.String() if got != test.want { t.Errorf("\t got = %x\n\t\t\twant = %x", got, test.want) } } }) } } func TestConvertDBToDecimal(t *testing.T) { var tests = []struct { given float64 want float64 }{ {-150.0, 0.0}, {-90.0, 0.0}, {-78.0, 0.025}, {-60.0, 0.0625}, {-42.0, 0.175}, {-30.0, 0.25}, {-20.0, 0.375}, {-10.0, 0.50}, {0.0, 0.75}, {10.0, 1.0}, {20.0, 1.0}, } for _, test := range tests { name := fmt.Sprintf("%.3fdB", test.given) t.Run(name, func(t *testing.T) { if got := dbLevelToDecimal(test.given); got != test.want { t.Errorf("\t got = %.4f\n\t\t\twant = %.4f", got, test.want) } }) } } func TestConvertDecimalToDB(t *testing.T) { var tests = []struct { given float64 want float64 }{ {-10.00, -90.0}, {0.0000, -90.0}, {0.0250, -78.0}, {0.0625, -60.0}, {0.1750, -42.0}, {0.2500, -30.0}, {0.3750, -20.0}, {0.5000, -10.0}, {0.7500, +0.00}, {1.0000, +10.0}, {1.1000, +10.0}, } for _, test := range tests { name := fmt.Sprintf("%.3fdB", test.given) t.Run(name, func(t *testing.T) { if got := decimalToDBLevel(test.given); got != test.want { t.Errorf("\t got = %.4f\n\t\t\twant = %.4f", got, test.want) } }) } } <file_sep>// Copyright (c) 2021 The goaudiovideo developers. All rights reserved. // Project site: https://github.com/goaudiovideo/osc // Use of this source code is governed by a MIT-style license that // can be found in the LICENSE file for the project. package x32 // Icon provudes an enumeration for the avialable icons. type Icon int // Enum for X32 icons. const ( EmptyIcon Icon = 1 KickDrum = 2 BassDrum = 3 SticksAboveSnareDrum = 4 SnareDrumAboveSticks = 5 HighTomDrum = 6 MediumTomDrum = 7 FloorTomDrum = 8 HighHatCymbal = 9 Cymbal = 10 DrumSet = 11 Lights = 12 Bongos = 13 Bongos2 = 14 Tambourine = 15 Xylophone = 16 Guitar1 = 17 Guitar2 = 18 Guitar3 = 19 Guitar4 = 20 Guitar5 = 21 Guitar6 = 22 Guitar7 = 23 Speaker1 = 24 Speaker2 = 25 Speaker3 = 26 GrandPiano = 27 UprightPiano = 28 Keyboard1 = 29 Keyboard2 = 30 Keyboard3 = 31 Keyboard4 = 32 Keyboard5 = 33 Keyboard6 = 34 Trumpet = 35 Trombone = 36 Saxaphone = 37 Clarinet = 38 Violin = 39 Cello = 40 MaleSinger = 41 FemaleSinger = 42 Singers = 43 Rockon = 44 ATalker = 45 BTalker = 46 InEarMic = 53 Laptop = 62 SmileyFace = 74 ) // String implements the Stringer interface for Icon. func (icon Icon) String() string { return iconDescription[icon] } var iconDescription = map[Icon]string{ EmptyIcon: "empty", KickDrum: "kick drum", BassDrum: "bass drum", SticksAboveSnareDrum: "sticks above snare drum", SnareDrumAboveSticks: "snare drum above sticks", HighTomDrum: "high tom drum", MediumTomDrum: "medium tom drum", FloorTomDrum: "floor tom drum", HighHatCymbal: "high hat cymbals", Cymbal: "cymbals", DrumSet: "full drum set", Lights: "lights", Bongos: "bongos", Bongos2: "bongos 2", Tambourine: "tambourine", Xylophone: "xylophone", Guitar1: "guitar 1", Guitar2: "guitar 2", Guitar3: "guitar 3", Guitar4: "guitar 4", Guitar5: "guitar 5", Guitar6: "guitar 6", Guitar7: "guitar 7", Speaker1: "speakers 1", Speaker2: "speakers 2", Speaker3: "speakers 3", GrandPiano: "grand piano", UprightPiano: "upright piano", Keyboard1: "keyboard 1", Keyboard2: "keyboard 2", Keyboard3: "keyboard 3", Keyboard4: "keyboard 4", Keyboard5: "keyboard 5", Keyboard6: "keyboard 6", Trumpet: "trumpet", Trombone: "trombone", Saxaphone: "saxaphone", Clarinet: "clarinet", Violin: "violin", Cello: "cello", MaleSinger: "male singer", FemaleSinger: "female singer", Singers: "trio of singers", Rockon: "rock on hand gesture", ATalker: "A talker", BTalker: "B talker", InEarMic: "in-ear microphone", Laptop: "laptop", SmileyFace: "smiley face", } // Color provudes an enumeration for the avialable colors. type Color int // Enum for X32 colors. const ( Off Color = 0 RedText = 1 GreenText = 2 YellowText = 3 BlueText = 4 MagentaText = 5 CyanText = 6 WhiteText = 7 OffBackground = 8 RedBackground = 9 GreenBackground = 10 YellowBackground = 11 BlueBackground = 12 MagentaBackground = 13 CyanBackground = 14 WhiteBackground = 15 ) // String implements the Stringer interface for Color. func (c Color) String() string { return colorDescription[c] } var colorDescription = map[Color]string{ Off: "off", RedText: "red text", GreenText: "green text", YellowText: "yellow text", BlueText: "blue text", MagentaText: "magenta text", CyanText: "cyan text", WhiteText: "white text", OffBackground: "off background", RedBackground: "red background", GreenBackground: "green background", YellowBackground: "yellow background", BlueBackground: "blue background", MagentaBackground: "magenta background", CyanBackground: "cyan background", WhiteBackground: "white background", } <file_sep>// Copyright (c) 2021 The goaudiovideo developers. All rights reserved. // Project site: https://github.com/goaudiovideo/osc // Use of this source code is governed by a MIT-style license that // can be found in the LICENSE file for the project. /* Package osc creates Open Sound Control (OSC) messages. */ package osc import ( "bytes" "encoding/binary" ) // Message creates an OSC message and returns it as a byte slice. func Message(addr, typeTag string, args ...interface{}) ([]byte, error) { // Add OSC Address Pattern to message and appropriate number of zero bytes. msg := []byte(addr) msg = append(msg, 0) msg = addZeroBytes(msg) // Add OSC Type Tag to message or add a comma and nulls if there aren't any // type tags provided and the appropriate number of zero bytes. msg = append(msg, []byte(",")...) if typeTag != "" { msg = append(msg, typeTag...) } msg = addZeroBytes(msg) // Add args to message if there are any given. for _, arg := range args { switch arg := arg.(type) { case string: msg = append(msg, arg...) msg = append(msg, 0) case int: i, err := encodeInt(arg) if err != nil { return nil, err } msg = append(msg, i...) case float64: b, err := encodeFloat64(arg) if err != nil { return nil, err } msg = append(msg, b...) case float32: b, err := encodeFloat32(arg) if err != nil { return nil, err } msg = append(msg, b...) } msg = addZeroBytes(msg) } return msg, nil } // addZeroBytes adds the proper number of zero bytes. func addZeroBytes(msg []byte) []byte { n := numZeroBytes(len(msg)) if n > 0 { padBytes := make([]byte, n) msg = append(msg, padBytes...) } return msg } // numZeroBytes calculates the number of zeo bytes to append to a message in // order to have a byte count that's a multiple of four. func numZeroBytes(l int) int { return (4 - (l % 4)) % 4 } // encodeFloat32 converts a float32 number into the big-endian binary byte // slice required by an OSC message. func encodeFloat32(f float32) ([]byte, error) { var buf bytes.Buffer if err := binary.Write(&buf, binary.BigEndian, f); err != nil { return nil, err } return buf.Bytes(), nil } // encodeFloat64 converts a float32 number into the big-endian binary byte // slice required by an OSC message. func encodeFloat64(f float64) ([]byte, error) { return encodeFloat32(float32(f)) } // encodeInt converts an integer number into the big-endian binary byte slice // required by an OSC message. func encodeInt(i int) ([]byte, error) { var buf bytes.Buffer if err := binary.Write(&buf, binary.BigEndian, int32(i)); err != nil { return nil, err } return buf.Bytes(), nil } <file_sep># osc Go-based Open Sound Control (OSC) Library [![GoDoc][godoc badge]][godoc link] [![Go Report Card][report badge]][report card] [![License Badge][license badge]][LICENSE] ## Overview [osc][] provides a Go-based [Open Sound Control (OSC)][osc.org] library. In addition to being able to create and send user specified OSC messages, [osc][] provides a Go library for specific audio equipment. ### Supported Equipment [osc][] (partially) supports the following equipment: - Behringer X32 Digital Mixer ## Contributing Contributions are welcome! To contribute please: 1. Fork the repository 2. Create a feature branch 3. Code 4. Submit a [pull request][] ### Testing Prior to submitting a [pull request][], please run: ```bash $ make check ``` To update and view the test coverage report: ```bash $ make cover ``` ## License [osc][] is released under the MIT license. Please see the [LICENSE][] file for more information. [osc]: https://github.com/goaudiovideo/osc [osc.org]: http://opensoundcontrol.org/ [godoc badge]: https://godoc.org/github.com/goaudiovideo/osc?status.svg [godoc link]: https://godoc.org/github.com/goaudiovideo/osc [LICENSE]: https://github.com/goaudiovideo/osc/blob/master/LICENSE [license badge]: https://img.shields.io/badge/license-MIT-blue.svg [pull request]: https://help.github.com/articles/using-pull-requests [report badge]: https://goreportcard.com/badge/github.com/goaudiovideo/osc [report card]: https://goreportcard.com/report/github.com/goaudiovideo/osc <file_sep>module github.com/goaudiovideo/osc go 1.16 <file_sep>// Copyright (c) 2021 The goaudiovideo developers. All rights reserved. // Project site: https://github.com/goaudiovideo/osc // Use of this source code is governed by a MIT-style license that // can be found in the LICENSE file for the project. /* Package x32 provides remote control support for the Behringer X32 Digital Mixer using Open Sound Control (OSC) remote protocol. */ package x32 import ( "bufio" "fmt" "io" "github.com/goaudiovideo/osc" ) // Info models the info received back from the mixer. type Info struct { ServerVersion string ServerName string ConsoleModel string ConsoleVersion string } // Mixer models a Behringer X32 mixer that can be controlled using Open Sound // Control (OSC). type Mixer struct { rw io.ReadWriter } // NewMixer creates a new Mixer using the given writer. func NewMixer(rw io.ReadWriter) Mixer { return Mixer{ rw: rw, } } // Write implements the Writer interface for Mixer. func (m Mixer) Write(p []byte) (int, error) { return m.rw.Write(p) } // WriteMessage writes the OSC message. func (m Mixer) WriteMessage(addr, typeTag string, args ...interface{}) error { msg, err := osc.Message(addr, typeTag, args...) if err != nil { return err } _, err = m.Write(msg) return err } // Info returns information about the X32 Mixer. // FIXME(mdr): Not working! Need to create functions to handle reading OSC // messages. func (m Mixer) Info() (Info, error) { info := Info{} err := m.WriteMessage("/info", "s") if err != nil { return info, err } p := make([]byte, 128) _, err = bufio.NewReader(m.rw).Read(p) if err != nil { return info, err } return info, nil } // MuteChannel mutes the given channel. func (m Mixer) MuteChannel(ch int) error { if !validChannelRange(ch) { return fmt.Errorf("channel %d out of range 1-32", ch) } addr := fmt.Sprintf("/ch/%02d/mix/on", ch) return m.WriteMessage(addr, "i", 0) } // MuteMain mutes the main channel. func (m Mixer) MuteMain() error { return m.WriteMessage("/main/st/mix/on", "i", 0) } // NameChannel sets the name of the given channel. The name can only be up to // 12 characters. func (m Mixer) NameChannel(ch int, name string) error { if !validChannelRange(ch) { return fmt.Errorf("channel %d out of range 1-32", ch) } if len(name) > 12 { return fmt.Errorf("channel name %s too long (12 char limit)", name) } addr := fmt.Sprintf("/ch/%02d/config/name", ch) return m.WriteMessage(addr, "s", name) } // SetChannelColor sets the color for the given channel. func (m Mixer) SetChannelColor(ch int, color Color) error { if !validChannelRange(ch) { return fmt.Errorf("channel %d out of range 1-32", ch) } addr := fmt.Sprintf("/ch/%02d/config/color", ch) return m.WriteMessage(addr, "i", int(color)) } // SetChannelIcon sets the icon for the given channel. func (m Mixer) SetChannelIcon(ch int, icon Icon) error { if !validChannelRange(ch) { return fmt.Errorf("channel %d out of range 1-32", ch) } addr := fmt.Sprintf("/ch/%02d/config/icon", ch) return m.WriteMessage(addr, "i", int(icon)) } // UnmuteChannel unmutes the given channel. func (m Mixer) UnmuteChannel(ch int) error { if !validChannelRange(ch) { return fmt.Errorf("channel %d out of range 1-32", ch) } addr := fmt.Sprintf("/ch/%02d/mix/on", ch) return m.WriteMessage(addr, "i", 1) } // UnmuteMain unmutes the main channel. func (m Mixer) UnmuteMain() error { return m.WriteMessage("/main/st/mix/on", "i", 1) } func validChannelRange(ch int) bool { return ch > 0 && ch < 33 } // dbLevelToDecimal converts a dB level from -90.0 dB to +10.0 dB to a decimal // value in the range of 0.0 to 1.0. func dbLevelToDecimal(db float64) float64 { switch { case db < -90.0: return 0.0 case db < -60.0: return (db + 90.0) / 480.0 case db < -30.0: return (db + 70.0) / 160.0 case db < -10.0: return (db + 50.0) / 80.0 case db <= 10.0: return (db + 30.0) / 40.0 default: return 1.0 } } // decimalToDBLevel converts a decimal value in the range of 0.0 to 1.0 to a dB // level from -90.0 dB to +10.0. func decimalToDBLevel(f float64) float64 { switch { case f > 1.0: return 10.0 case f >= 0.5: return f*40.0 - 30.0 case f >= 0.25: return f*80.0 - 50.0 case f >= 0.0625: return f*160.0 - 70.0 case f >= 0.0: return f*480.0 - 90. default: return -90.0 } } <file_sep>// Copyright (c) 2021 The goaudiovideo developers. All rights reserved. // Project site: https://github.com/goaudiovideo/osc // Use of this source code is governed by a MIT-style license that // can be found in the LICENSE file for the project. package osc import ( "encoding/hex" "fmt" "testing" ) func TestGoodMessages(t *testing.T) { var args1 []interface{} args1 = append(args1, "name") var args2 []interface{} args2 = append(args2, float32(0.4648)) var args3 []interface{} args3 = append(args3, 1) var args4 []interface{} args4 = append(args4, "GATE") var tests = []struct { name string addr string typeTag string args []interface{} want []byte }{ {"info", "/info", "", nil, []byte("/info\x00\x00\x00,\x00\x00\x00")}, { "config ch1 name no args", "/ch/01/config/name", "s", nil, []byte("/ch/01/config/name\x00\x00,s\x00\x00"), }, { "config ch1 name", "/ch/01/config/name", "s", args1, []byte("/ch/01/config/name\x00\x00,s\x00\x00name\x00\x00\x00\x00"), }, { "ch1 freq", "/ch/01/eq/1/q", "f", args2, []byte("/ch/01/eq/1/q\x00\x00\x00,f\x00\x00\x3e\xed\xfa\x44"), }, { "ch1 gate int", "/ch/01/gate/mode", "i", args3, []byte("/ch/01/gate/mode\x00\x00\x00\x00,i\x00\x00\x00\x00\x00\x01"), }, { "ch2 gate int", "/ch/02/gate/mode", "i", args3, []byte("/ch/02/gate/mode\x00\x00\x00\x00,i\x00\x00\x00\x00\x00\x01"), }, { "ch1 gate str", "/ch/01/gate/mode", "s", args4, []byte("/ch/01/gate/mode\x00\x00\x00\x00,s\x00\x00GATE\x00\x00\x00\x00"), }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { got, err := Message(test.addr, test.typeTag, test.args...) if err != nil { t.Errorf("Got unexpected error: %s", err) } if string(got) != string(test.want) { t.Errorf("\t got = %q\n\t\t\twant = %q", got, test.want) } }) } } func TestNumZeroBytes(t *testing.T) { var tests = []struct { given int want int }{ {0, 0}, {1, 3}, {2, 2}, {3, 1}, {4, 0}, {5, 3}, {6, 2}, {7, 1}, {8, 0}, {9, 3}, {10, 2}, {11, 1}, {12, 0}, {13, 3}, {14, 2}, {15, 1}, {16, 0}, {17, 3}, } for _, test := range tests { name := fmt.Sprintf("len %d", test.given) t.Run(name, func(t *testing.T) { if got := numZeroBytes(test.given); got != test.want { t.Errorf("\t got = %d\n\t\t\twant = %d", got, test.want) } }) } } func TestEncodeFloat32(t *testing.T) { var tests = []struct { given float32 want string }{ {0.0000, "00000000"}, {0.0010, "3a83126f"}, {0.0020, "3b03126f"}, {0.2650, "3e87ae14"}, {0.4648, "3eedfa44"}, {0.5000, "3f000000"}, {0.7500, "3f400000"}, {0.8250, "3f533333"}, } for _, test := range tests { name := fmt.Sprintf("float_%f", test.given) t.Run(name, func(t *testing.T) { h, err := hex.DecodeString(test.want) if err != nil { t.Errorf("unexepcted error decoding hex string %s: %s", test.want, err) } got, err := encodeFloat32(test.given) if err != nil { t.Errorf("unexpected error: %s", err) } if string(got) != string(h) { t.Errorf("\t got = %x\n\t\t\twant = %x", got, h) } }) } } func TestEncodeInt(t *testing.T) { var tests = []struct { given int want string }{ {0, "00000000"}, {1, "00000001"}, {2, "00000002"}, {3, "00000003"}, {4, "00000004"}, } for _, test := range tests { name := fmt.Sprintf("integer_%d", test.given) t.Run(name, func(t *testing.T) { h, err := hex.DecodeString(test.want) if err != nil { t.Errorf("unexpected error decoding hex string %s: %s", test.want, err) } got, err := encodeInt(test.given) if err != nil { t.Errorf("unexpected error: %s", err) } if string(got) != string(h) { t.Errorf("\t got = %x\n\t\t\twant = %x", got, h) } }) } }
5c2007425720aa3e0c82c8fcb8f22798a84fe8fc
[ "Markdown", "Go Module", "Go" ]
7
Go
goaudiovideo/osc
6a5ad7d0872e28ccd39b94bcfb36f650e9e7c7c0
667c699ec239b3501f4366f081dc8ef172978c81
refs/heads/master
<repo_name>nadim-jahangir-m4/postgres<file_sep>/9.6/alpine/mfpgex.c /* Author: <NAME> Compile using: # requires postgresql-devel package gcc -fpic -c mfpgex.c -I/usr/include/pgsql/server/ gcc -shared -o mfpgex.so mfpgex.o */ #include <stdlib.h> #include <string.h> #include <ctype.h> #include "postgres.h" #include "fmgr.h" #include "utils/array.h" #include "utils/builtins.h" #include "utils/lsyscache.h" #ifdef PG_MODULE_MAGIC PG_MODULE_MAGIC; #endif #define DELIMITER 0 #define NUM_OFFSET 999999999999999999LL static const char *DIGIT = "0123456789ABCDEF"; #define HEX(a, i, v) a[i++] = DIGIT[(v >> 4) & 0xf]; a[i++] = DIGIT[v & 0xf] /* http://stjarnhimlen.se/snippets/jdn.c */ static int julian(int y, int m, int d) { return (int) (d - 32076) + 1461L * (y + 4800 + (m - 14) / 12) / 4 + 367 * (m - 2 - (m - 14) / 12 * 12) / 12 - 3 * ((y + 4900 + (m - 14) / 12) / 100) / 4 + 1; } /* couldn't find a better name! */ static long long longify(char *type, char *val) { char *pdot = strchr(type, '.'); char *p; char tmp1[50]; char tmp2[50]; int i; for (i = 0; val[i]; i++) tmp1[i] = val[i]; if (pdot) /* has '.' */ { tmp1[i++] = 'e'; for (p = pdot + 1; *p && *p != '('; p++) { tmp1[i++] = *p; } } tmp1[i] = 0; sprintf(tmp2, "%.0lf", atof(tmp1)); return strtoll(tmp2, NULL, 10) + NUM_OFFSET; } /* CREATE FUNCTION norm_key_val(text[], text[]) RETURNS text AS '/usr/lib/mfpgex.so', 'norm_key_val' LANGUAGE C IMMUTABLE; */ PG_FUNCTION_INFO_V1(norm_key_val); Datum norm_key_val(PG_FUNCTION_ARGS) { ArrayType *types_arr, *vals_arr; Datum *types, *vals; Oid types_eltype, vals_eltype; int16 types_typlen, vals_typlen; bool types_typbyval, vals_typbyval; char types_typalign, vals_typalign; int ntypes, nvals; bool *types_nulls, *vals_nulls; char *ret; int ret_len; Datum retd; char *typea[10] = {0}; char *vala[10] = {0}; int val_len[10] = {0}; char typ; int i, j, k, l; int all_empty; char c; unsigned char *byte_ptr; long long ll; unsigned char byte; int hour, min, sec; int yr, mn, dy, days; char tmp[50]; types_arr = PG_GETARG_ARRAYTYPE_P(0); types_eltype = ARR_ELEMTYPE(types_arr); get_typlenbyvalalign(types_eltype, &types_typlen, &types_typbyval, &types_typalign); deconstruct_array(types_arr, types_eltype, types_typlen, types_typbyval, types_typalign, &types, &types_nulls, &ntypes); vals_arr = PG_GETARG_ARRAYTYPE_P(1); vals_eltype = ARR_ELEMTYPE(vals_arr); get_typlenbyvalalign(vals_eltype, &vals_typlen, &vals_typbyval, &vals_typalign); deconstruct_array(vals_arr, vals_eltype, vals_typlen, vals_typbyval, vals_typalign, &vals, &vals_nulls, &nvals); if (ntypes != nvals) { pfree(types); pfree(vals); pfree(types_nulls); pfree(vals_nulls); elog(ERROR, "The number of values is not equal to the number of types"); } ret_len = ntypes - 1; for (i = 0; i < ntypes; i++) { if (types_nulls[i]) { pfree(types); pfree(vals); pfree(types_nulls); pfree(vals_nulls); elog(ERROR, "Type[%d] cannot be NULL", i + 1); } typea[i] = DatumGetCString(DirectFunctionCall1(textout, types[i])); if (vals_nulls[i]) { vala[i] = NULL; val_len[i] = 0; } else { vala[i] = DatumGetCString(DirectFunctionCall1(textout, vals[i])); val_len[i] = strlen(vala[i]); } typ = typea[i][0]; switch (typ) { case 'I': case 'Z': case 'M': case 'N': ret_len += 8; break; case 'D': case 'T': ret_len += 3; break; default: ret_len += val_len[i]; } } /* check if all fields (but bookmark) are empty */ all_empty = 1; for (i = nvals - 2; i >= 0; i--) { if (val_len[i]) { all_empty = 0; break; } } /* if all fields are empty then return null */ if (all_empty) { for (i = 0; i < nvals; i++) { if (vala[i]) pfree(vala[i]); pfree(typea[i]); } pfree(types); pfree(vals); pfree(types_nulls); pfree(vals_nulls); PG_RETURN_NULL(); } ret = (char *) malloc((ret_len << 1) | 1); k = 0; for (i = 0; i < nvals; i++) { if (i) { HEX(ret, k, DELIMITER); } typ = typea[i][0]; if (typ == 'I' || typ == 'Z') { ll = 0; if (vala[i]) ll = NUM_OFFSET + strtoll(vala[i], NULL, 10); for (j = 56; j >= 0; j -= 8) { byte = (ll >> j) & 0xff; HEX(ret, k, byte); } } else if (typ == 'D') { if (!vala[i] || val_len[i] != 10) /* if not in 'YYYY-MM-DD' format */ { HEX(ret, k, 0); HEX(ret, k, 0); HEX(ret, k, 0); } else { yr = 1000 * (vala[i][0] - '0') + 100 * (vala[i][1] - '0') + 10 * (vala[i][2] - '0') + (vala[i][3] - '0'); mn = 10 * (vala[i][5] - '0') + (vala[i][6] - '0'); dy = 10 * (vala[i][8] - '0') + (vala[i][9] - '0'); days = julian(yr, mn, dy); byte = (days >> 16) & 0xff; HEX(ret, k, byte); byte = (days >> 8) & 0xff; HEX(ret, k, byte); byte = days & 0xff; HEX(ret, k, byte); } } else if (typ == 'T') { if (!vala[i] || val_len[i] != 5) /* if not in 'HH:mm' format */ { HEX(ret, k, 0); HEX(ret, k, 0); HEX(ret, k, 0); } else { hour = 10 * (vala[i][0] - '0') + (vala[i][1] - '0'); min = 10 * (vala[i][3] - '0') + (vala[i][4] - '0'); sec = 3600 * hour + 60 * min; byte = (sec >> 16) & 0xff; HEX(ret, k, byte); byte = (sec >> 8) & 0xff; HEX(ret, k, byte); byte = sec & 0xff; HEX(ret, k, byte); } } else if (typ == 'N' || typ == 'M') { ll = 0; if (val_len[i]) ll = longify(typea[i], vala[i]); for (j = 56; j >= 0; j -= 8) { byte = (ll >> j) & 0xff; HEX(ret, k, byte); } } else { if (val_len[i]) { for (j = 0; j < val_len[i]; j++) { c = toupper(vala[i][j]); HEX(ret, k, c); } } } if (vala[i]) pfree(vala[i]); pfree(typea[i]); } ret[k++] = 0; pfree(types); pfree(vals); pfree(types_nulls); pfree(vals_nulls); retd = DirectFunctionCall1(textin, CStringGetDatum(ret)); free(ret); return retd; }
d13aa8c2d2823ba8fbe7222237196b2a2932d177
[ "C" ]
1
C
nadim-jahangir-m4/postgres
d903331a8caa366ff9268e2980289892347b67af
3408c25337fd0b3f6d7e81afbf943a5d2325b8e7
refs/heads/master
<repo_name>evan69/gpaCalculator<file_sep>/calculator.py #!./python print 'calculate GPA' filename = raw_input('please input file name\n') file = open(filename,'r') tot = 0 credit = 0 for line in file.readlines(): cnt = 0 cre = ' ' score = ' ' i = 0 while 1: if line[i] == '\t': cnt += 1 if cnt >= 2: break i += 1 i += 1 while 1: if line[i] == '\t': break cre += line[i] i += 1 try: cre = int(cre) except ValueError,e: print 'this is a course with pass or fail' print line continue while 1: if line[i] == '\t': cnt += 1 if cnt >= 3: break i += 1 i += 1 while 1: if line[i] == '\t': break score += line[i] i += 1 try: score = int(score) except ValueError,e: print 'this is a course with pass or fail' print line continue tot += score * cre credit += cre print '' print 'your GPA is',1.0 * tot / credit
98a0fbacf52413fbfbea02632746540be48f8553
[ "Python" ]
1
Python
evan69/gpaCalculator
32b5dbe89031c708468699b5881544f60242ffa7
e5f97a33d53d591d379a8b8c028d4fb32e0f5efc
refs/heads/master
<file_sep>package com.nz.rpc.loadbalance.exception; public class LoadbalanceException extends Exception { public LoadbalanceException() { } public LoadbalanceException(String message) { super(message); } public LoadbalanceException(String message, Throwable cause) { super(message, cause); } } <file_sep>package com.nz.rpc.interceptor.impl; import com.nz.rpc.cluster.ClusterFaultHandler; import com.nz.rpc.interceptor.Interceptor; import com.nz.rpc.invocation.client.ClientInvocation; import lombok.extern.slf4j.Slf4j; /** *功能描述 * @author lgj * @Description 集群容错处理 * * 出错原因: * 1.服务端关闭channel,或者服务端宕机 * 2.服务端拒绝请求(请求太多,无法处理),发生IO-EXCEPTION * 3.服务端执行任务超时 * 4.服务端执行任务出现异常 * * 容错处理: * 一. Failover 失败自动切换 *    使用场景: * 1.读操作,读操作是幂等性操作 * 2. 幂等性服务,调用一次和调用多次结果一样 * 缺点: 1.延迟较大 * * 二.Failfast Cluster * 快速失败,只发起一次调用,失败立即报错。通常用于非幂等性的写操作,比如新增记录。 * 在业务高峰期,对于一些非核心的服务,希望只调用一次,失败也不再重试,为重要的核心服务节约宝贵的运行资源 * * 三.Failsafe Cluster * 失败安全,出现异常时,直接忽略。通常用于写入审计日志等操作。 * * 四.Failback Cluster * 失败自动恢复,后台记录失败请求,定时重发。通常用于消息通知操作。 * *  在集群容错设计的时候,需要考虑扩展性,主要从以下几方面进行设计: *  1)、容错接口的开放。 * 2)、屏蔽底层细节,用户定制简单。 * 3)、配置应当支持扩展,不要让用户扩展服务框架Schema。 * @date 5/7/19 */ @Slf4j public class ClusterFaultToleranceInterceptor implements Interceptor { private ClusterFaultHandler clusterFaultHandler; @Override public Object intercept(ClientInvocation invocation) throws Exception { Object result = null; log.debug("ClusterFaultToleranceInterceptor start ...."); try{ result = invocation.executeNext(); } catch(Exception ex){ if(log.isErrorEnabled()){ log.error("Cluster is Fault!!!" + ex.getMessage()); } clusterFaultHandler.handle(invocation,ex); } return result; } public void setClusterFaultHandler(ClusterFaultHandler clusterFaultHandler) { this.clusterFaultHandler = clusterFaultHandler; } } <file_sep>package com.app.consumer.controller; import com.app.common.service.PersonService; import com.nz.rpc.anno.RpcReference; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.concurrent.CompletableFuture; @Slf4j @RestController @RequestMapping("/person") public class PersonController { @RpcReference private PersonService personService; @GetMapping("/query") public String query(){ log.debug("/person/query"); CompletableFuture<String> future = personService.queryPerson("libai"); try{ return CompletableFuture.allOf(future).thenApply((T)->{ String reslut = null; try{ reslut = future.get(); log.info("reslut = "+reslut); } catch(Exception ex){ log.error(ex.getMessage()); } return reslut; }).get(); } catch(Exception ex){ log.error(ex.getMessage()); return null; } } } <file_sep>package com.nz.rpc.netty.client.handler; import com.nz.rpc.netty.NettyContext; import com.nz.rpc.netty.message.Header; import com.nz.rpc.netty.message.MessageType; import com.nz.rpc.netty.message.NettyMessage; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.timeout.IdleState; import io.netty.handler.timeout.IdleStateEvent; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.ConcurrentHashMap; /** *功能描述 * @author lgj * @Description 心跳请求处理类 * @date 4/16/19 */ @Slf4j public class HeartbeatRequestHandler extends ChannelInboundHandlerAdapter { private final int MAX_HEARTBEAT_FAIL_COUNT = 3; private ConcurrentHashMap<String,Integer> maxHeartbeatFailCountRecords = new ConcurrentHashMap<String, Integer>(); @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { NettyMessage message = (NettyMessage)msg; if((message.getHeader() != null) &&(message.getHeader().getType() == MessageType.HEARTBEAT_RESPONSE_TYPE.getValue())){ if (log.isDebugEnabled()){ log.debug("接收到[{}]的心跳响应消息",getAddress(ctx)); } // timeOutCount.put(getAddress(ctx),0); } else { super.channelRead(ctx, msg); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (log.isDebugEnabled()){ log.debug("HeartbeatRequestHandler exceptionCaught"); } super.exceptionCaught(ctx, cause); } /** *功能描述 * @author lgj * @Description 读写空闲事件 * @date 4/26/19 * @param: * @return: * */ @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if(evt instanceof IdleStateEvent){ IdleStateEvent event = (IdleStateEvent)evt; //log.debug("userEventTriggered....[{}]",event.state()); Channel channel = ctx.channel(); Integer failCount = maxHeartbeatFailCountRecords.get(channel.remoteAddress().toString()); if (event.state()== IdleState.READER_IDLE){ if(log.isWarnEnabled()){ log.warn("channel[{}]连接超时,关闭channel!" ,ctx.channel()); } NettyContext.getNettyClient().connect(ctx.channel().remoteAddress()); ChannelFuture channelFuture = ctx.channel().close(); channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { Channel channel = channelFuture.channel(); if(log.isDebugEnabled()){ log.debug("channel[{}]状态[{}]",channel.remoteAddress(),channel.isActive()); } } }); } else if (event.state()== IdleState.WRITER_IDLE){ if(log.isDebugEnabled()){ log.debug("写空闲事件发生,向[{}]发送心跳数据",ctx.channel().remoteAddress()); } NettyMessage nettyMessage = buildHeartbeatMessage(); ctx.channel().writeAndFlush(nettyMessage); } } else { super.userEventTriggered(ctx, evt); } } /** *功能描述 * @author lgj * @Description 构建心跳消息 * @date 4/16/19 * @param: * @return: * */ private NettyMessage buildHeartbeatMessage(){ NettyMessage nettyMessage = new NettyMessage(); Header header = new Header(); header.setType(MessageType.HEARTBEAT_REQUEST_TYPE.getValue()); nettyMessage.setHeader(header); return nettyMessage; } private String getAddress(ChannelHandlerContext ctx){ return ctx.channel().remoteAddress().toString(); } } <file_sep>package app.provider.service.impl; import com.app.common.service.PersonService; import com.nz.rpc.anno.RpcService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.Date; import java.util.Random; import java.util.concurrent.CompletableFuture; @Slf4j @RpcService @Service public class PersonServiceImpl implements PersonService { @Override public CompletableFuture<String> queryPerson(String name) { log.debug("PersonServiceImpl queryPerson :" + name); CompletableFuture<String> future = new CompletableFuture<String>(); String result = "PersonServiceImpl queryPerson :" +name + ":"+ new Date().toString()+ " " + new Random().nextInt(1000); future.complete(result); return future; } @Override public String doSomeThing() { return null; } } <file_sep>#!/bin/bash JAR_PATH="/home/lgj/aProject/aRealPrj/nz-rpc/app-demo/app-consumer/target/app-consumer-1.0.0.jar" JAVA_OPT="${JAVA_OPT} -server -Xms1024m -Xmx1024m -Xmn800m -XX:MetaspaceSize=800m -XX:MaxMetaspaceSize=1000m" java -jar ${JAVA_OPT} ${JAR_PATH} <file_sep>package com.nz.rpc.msg.request; import java.lang.reflect.Method; public interface RequestHandler { Object invoke(Method method, Object[] args); } <file_sep>package com.nz.rpc.serialization; import com.nz.rpc.netty.message.NettyMessage; import org.junit.Test; public class FastJsonSerializeUtilTest { @Test public void testFastJsonSerialize() throws Exception{ AbstractSerialize serialize = new ProtostuffSerializeUtil(); NettyMessage message = NettyMessageBuilder.build(); TimeUtil timeUtil = new TimeUtil(); TimeUtil timeUtil1 = new TimeUtil(); NettyMessage result = null; byte[] serByte = serialize.serialize(message); System.out.println("字节长度:" + serByte.length); result = serialize.deserialize(serByte,NettyMessage.class); for(int i = 0; i< 100000; i++){ //timeUtil.init(); timeUtil.start(); serByte = serialize.serialize(message); timeUtil.end(); //System.out.println("序列化时间:"+ timeUtil.getAvrTimeUs() + " Us"); timeUtil1.start(); result = serialize.deserialize(serByte,NettyMessage.class); timeUtil1.end(); } System.out.println("序列化时间:"+ timeUtil.getAvrTimeUs() + " Us"); System.out.println("反序列化时间:"+ timeUtil1.getAvrTimeUs() + " Us"); System.out.println("结果:" + result); } /** *功能描述 * @author lgj * @Description 序列化框架并发测试 * @date 4/18/19 * @param: * @return: * */ //@Test public void testThread(){ for(int i = 0; i< 1000000; i++){ new MyThread().start(); } } } class MyThread extends Thread{ AbstractSerialize serialize = new FastjsonSerializeUtil() ; NettyMessage message = NettyMessageBuilder.build(); @Override public void run() { try{ NettyMessage result = null; byte[] serByte = serialize.serialize(message); result = serialize.deserialize(serByte,NettyMessage.class); } catch(Exception ex){ } } }<file_sep>package com.nz.rpc.uid; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantLock; /** *功能描述 * @author lgj * @Description 雪花算法实现uid * @date 4/23/19 */ @Slf4j public class CustomProducer implements UidProducer { //序列号12 + 机器号10 + 时间戳(ms)41 = 63 private final int ENQUENCE_BITS_LEN = 12; private final int MACID_BITS_LEN = 10; private final int TIMESTAMP_BITS_LEN = 41; private final int ENQUENCE_MASK = getMask(ENQUENCE_BITS_LEN); private final int MACID_MASK = getMask(MACID_BITS_LEN); private final int TIMESTAMP_MASK = getMask(TIMESTAMP_BITS_LEN); private final int ENQUENCE_BITS_OFFSET = 0; private final int MACID_BITS_OFFSET = 12; private final int TIMESTAMP_BITS_OFFSET = 22; private long timestamp; private AtomicInteger equence = new AtomicInteger(0); private ReentrantLock lock = new ReentrantLock(); private long macId; public CustomProducer(long macId) { this.macId = macId; } @Override public long getUid(){ long result = 0; try{ lock.lock(); long curTimeStamp = System.currentTimeMillis(); //不同的ms,序列号清零 if(curTimeStamp != timestamp){ equence.set(0); timestamp=curTimeStamp; } //相同的ms else { equence.incrementAndGet(); } result = ((timestamp & TIMESTAMP_MASK)<<TIMESTAMP_BITS_OFFSET) |((macId & MACID_MASK)<<MACID_BITS_OFFSET) |((equence.get() & ENQUENCE_MASK) <<ENQUENCE_BITS_OFFSET); } catch(Exception ex){ log.error(ex.getMessage()); } finally{ lock.unlock(); } return result; } /** *功能描述 * @author lgj * @Description * 1---> 0b00000001 * 2---> 0b00000011 * 3---> 0b00000111 * 4---> 0b00001111 * * @date 4/23/19 * @param: * @return: * */ private static int getMask(int numBit){ int result = 0; for(int i = 0; i< numBit; i++){ result |= 1 << i; } return result; } public static void main(String args[]){ for(int i = 0; i< 8; i++){ System.out.println(getMask(i)+""); } } } <file_sep>package com.nz.rpc.netty.coder; import com.nz.rpc.netty.message.NettyMessage; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageEncoder; import lombok.extern.slf4j.Slf4j; import java.util.List; @Slf4j public class NettyMessageEncoder extends MessageToMessageEncoder<NettyMessage> { @Override protected void encode(ChannelHandlerContext channelHandlerContext, NettyMessage nettyMessage, List<Object> out) throws Exception { if( (nettyMessage == null) || (nettyMessage.getHeader() == null)){ throw new NullPointerException(); } ByteBuf byteBuf = Unpooled.buffer();// new PooledByteBufAllocator().directBuffer();// // log.info("NettyMessageEncoder 发送解析 : nettyMessage = " + nettyMessage); // byteBuf.writeLong(nettyMessage.getHeader().getMagic()); byteBuf.writeByte(nettyMessage.getHeader().getType()); byteBuf.writeLong(nettyMessage.getHeader().getSessionID()); byteBuf.writeInt(nettyMessage.getHeader().getLength()); byteBuf.writeInt(nettyMessage.getHeader().getCrcCode()); byteBuf = MessageBodyUtil.encoder(nettyMessage.getBody(),byteBuf); //回写byteBuf总共长度 // log.info("数据总长度="+byteBuf.readableBytes()); byteBuf.setInt(9,byteBuf.readableBytes()); out.add(byteBuf); } } <file_sep>cd ~/aProject/aRealPrj/nz-rpc/rpc-integration pwd mvn install -Dmaven.test.skip=true cd ~/aProject/aRealPrj/nz-rpc/app-demo/app-common pwd mvn install -Dmaven.test.skip=true 从 cd - <file_sep>package com.nz.rpc.netty.client; import com.nz.rpc.netty.client.handler.NettyChannelHandler; import com.nz.rpc.properties.RpcProperties; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.concurrent.DefaultThreadFactory; import io.netty.util.concurrent.GenericFutureListener; import lombok.Data; import lombok.extern.slf4j.Slf4j; import java.net.SocketAddress; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet; /** *功能描述 * @author lgj * @Description nertty操作客户端 * @date 7/14/19 */ @Slf4j @Data public class NettyClient { private EventLoopGroup group ; private Bootstrap bootstrap ; //channel缓存 key : host&port private static Map<String, Channel> channelCache = new ConcurrentHashMap<>(); //重连间隔时间 private static final int reConnectIntervalTimeMs = 5000; //value: host&port 正在连接状态的Server host&port private Set<String> connectingServer = new ConcurrentSkipListSet<String>(); private RpcProperties rpcProperties; public NettyClient(RpcProperties rpcProperties){ this.rpcProperties = rpcProperties; } public void init(){ group = new NioEventLoopGroup(rpcProperties.getNettyClient().getWorkerTheads(), new DefaultThreadFactory("client1", true)); bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, false) .option(ChannelOption.SO_SNDBUF,1024*1024) .option(ChannelOption.SO_RCVBUF,1024*1024) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT) .handler(new NettyChannelHandler()); shutdownHandler(); } public void connect(SocketAddress remoteAddress){ connect(parseToHost(remoteAddress),parseToPort(remoteAddress)); } /** *功能描述 * @author lgj * @Description 连接到端口 * @date 7/13/19 * @param: * @return: * */ public void connect(String host,int port){ if(host == null){ throw new NullPointerException("Host["+host+"] is null,Connect fail!"); } //如果和本应用的host&port一致,则拒绝执行连接 if((rpcProperties.getNhost().equals(host)) && (rpcProperties.getNport() == port)){ log.warn("Netty cann't connect to youself!"); return; } String key = getKey(host,port); synchronized (connectingServer){ Channel channel = channelCache.get(key); //host&port正在连接状态 if(connectingServer.contains(key)){ if(log.isInfoEnabled()){ log.warn("Serere [{}:{}] is connecting",host,port); } return; } else if(channel != null){ //host&port连接成功状态 if(log.isDebugEnabled()){ log.debug("Channel state isActive= [{}],isOpen= [{}],isRegistered= [{}]", channel.isActive(),channel.isOpen(),channel.isRegistered()); } if(channel.isActive()){ if(log.isDebugEnabled()){ log.debug("Channel[{}] has been active!Don't neet to connect!",channel); } return; } } if(log.isDebugEnabled()){ log.debug("Connecting to Serere [{}:{}]",host,port); } connectingServer.add(key); bootstrap.connect(host, port).addListener(new GenericFutureListener<ChannelFuture>(){ @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { Channel channel = channelFuture.channel(); //log.info("connectingServer = " + connectingServer); if(channel.isActive()){ if(log.isDebugEnabled()){ log.debug("Server[{}] connect success",channel); } connectingServer.remove(key); channelCache.put(key,channel); return; }else { if(log.isWarnEnabled()){ log.warn("Connecting to Serere [{}:{}] fail!!,Try reconect!!",host,port); } Thread.sleep(reConnectIntervalTimeMs); connectingServer.remove(key); connect(host, port); } } }); } } public Channel getChannel(String host,int port){ Channel channel = channelCache.get(getKey(host,port)); if(log.isDebugEnabled()){ log.debug("channelCache len =[{}]",channelCache.size()); } if(channel == null){ this.connect(host,port); } return channelCache.get(getKey(host,port)); } public void removeChannel(String host,int port){ String key = getKey(host,port); Channel channel = channelCache.get(key); if(channel != null){ channelCache.remove(getKey(host,port)); channel.close(); } } private String parseToHost(SocketAddress remoteAddress){ String address = remoteAddress.toString(); int end = address.indexOf(":"); return address.substring(1,end); } private int parseToPort(SocketAddress remoteAddress){ String address = remoteAddress.toString(); int start = address.indexOf(":"); return Integer.valueOf( address.substring(start+1,address.length())); } private String getKey(String host,int port){ return new StringBuilder().append(host).append("&").append(port).toString(); } /* *功能描述 应用关闭处理 * @author lgj * @Description * @date 7/26/19 * @param: * @return: void * */ private void shutdownHandler(){ new Thread(){ @Override public void run() { Runtime.getRuntime().addShutdownHook(new Thread(){ @Override public void run() { if(log.isInfoEnabled()){ log.info("系统Netty-Client正在关闭应用!"); } group.shutdownGracefully(); } }); } }.start(); } } <file_sep>package com.nz.rpc.loadbalance; import com.nz.rpc.discover.ProviderConfig; import java.util.List; import java.util.Random; /** *功能描述 * @author lgj * @Description 随机负载均衡 * @date 3/28/19 */ public class RandomLoadbalanceStrategy implements LoadbalanceStrategy{ @Override public ProviderConfig doSelect(List<ProviderConfig> configs, Object object){ int index = new Random().nextInt(configs.size()); return configs.get(index); } } <file_sep>package com.nz.rpc.properties; import com.nz.rpc.netty.client.properties.NettyClientProperties; import com.nz.rpc.netty.server.properties.NettyServerProperties; import com.nz.rpc.uid.UidProperties; import lombok.Data; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; /** *功能描述 * @author lgj * @Description Rpc参数配置类 * @date 3/27/19 */ @Data @ConfigurationProperties(prefix="nzrpc") public class RpcProperties { /* * zookeeper 连接地址: "localhost:2182,localhost:2183,localhost:2184" * 默认值: localhost:2182 */ @Value("${nzrpc.zookeeper.address:localhost:2182}") private String zookeeperAdress; /* * netty服务端口 * 默认值:8321 */ @Value("${nzrpc.netty.port:8321}") private int nport; @Value("${nzrpc.netty.host:127.0.0.1}") private String nhost; /* * 被@RpcReference注解的消费者接口引用所在的类,如有多个中间使用","隔开 * nzrpc.scan-package: "com,org" */ @Value("${nzrpc.scan-package:com}") private String scanPackage; /* 动态代理方式  1. jdk   jdk动态代理 2. cglib 3. javassit 默认值:jdk */ @Value("${nzrpc.proxy-type:jdk}") private String proxyType; @Value("${nzrpc.serialization:hessian}") public String serialization; private UidProperties uid = new UidProperties(); private NettyClientProperties nettyClient = new NettyClientProperties(); private NettyServerProperties nettyServer = new NettyServerProperties(); } <file_sep>package com.nz.rpc.lock.zk; import com.nz.rpc.lock.Lock; import com.nz.rpc.zk.ZkCreateConfig; import lombok.AllArgsConstructor; import lombok.Data; import lombok.ToString; import lombok.extern.slf4j.Slf4j; import org.apache.zookeeper.CreateMode; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; /** *功能描述 * @author lgj * @Description zookeeper 实现分布式锁 * @date 4/20/19 */ @Slf4j @Data public class ZkLockUtil implements Lock { private ZkClient zkClient; private ThreadLocal<Map<Thread,String>> lockPathMap = new ThreadLocal(); //用于保存当前线程的请求锁的原 锁名称,节点路径,重入锁技计数器 private ConcurrentHashMap<Thread,List<LockData>> lockDataMap = new ConcurrentHashMap<>(); //锁路径 LOCK_ROOT_PATH + LOCKNAME + LOCKPATH_SEPARATOR + NUMS; // -》 /locks/lockName_0000001 private final String LOCK_ROOT_PATH = "/locks"; private final String LOCKPATH_SEPARATOR = "-"; /** *功能描述 * @author lgj * @Description * @date 4/20/19 * @param: * @return: * */ public boolean lock(String lockKey, int millisecondsToExpire) { List<LockData> lockDatas = lockDataMap.get(Thread.currentThread()); //判断是否是重入锁 if(lockDatas != null){ List<LockData> selectlockData = lockDatas.stream().filter((val)-> val.lockKey.equals(lockKey)).collect(Collectors.toList()); if(selectlockData.size() != 0){ //重入锁 selectlockData.get(0).lockCount.incrementAndGet(); List<LockData> filter = lockDatas.stream().filter((val)-> !val.lockKey.equals(lockKey)).collect(Collectors.toList()); filter.add(selectlockData.get(0)); lockDataMap.put(Thread.currentThread(),filter); return true; } } //不是重入锁 //创建节点 节点 /locks/lockname_000000000001 ZkCreateConfig config = ZkCreateConfig.builder() .createMode(CreateMode.EPHEMERAL_SEQUENTIAL) .path(getCreatePath(lockKey)) .build(); //当前锁路径 -> /locks/lockname_000000013 String curLockPath = zkClient.createPath(config); long curPathNum = Long.valueOf(curLockPath.split(LOCKPATH_SEPARATOR)[1]); //获取/locks子节点列表 size >= 1 List<String> subRootPaths = zkClient.getChildren(LOCK_ROOT_PATH); log.info("获取[{}]子节点列表:{}",LOCK_ROOT_PATH,subRootPaths); //只有一个节点,说明只有刚才建立的节点,没有其他进程线程获取锁,设置LockData后便返回 if(subRootPaths.size() == 1){ log.info("[{}]获取锁",subRootPaths.get(0)); LockData lockData = new LockData(lockKey,curLockPath,new AtomicInteger(1)); List<LockData> lockData1 = lockDataMap.get(Thread.currentThread()); if(lockData1 == null){ lockData1 = new ArrayList<>(); } lockData1.add(lockData); lockDataMap.put(Thread.currentThread(),lockData1); return true; } //有其他进程线程已经获取锁 else{ TreeMap<Long,String> sortMap = new TreeMap<>(); for (String subRootPath:subRootPaths){ String[] sub = subRootPath.split(LOCKPATH_SEPARATOR); if(sub[0].equals(lockKey)){ sortMap.put(Long.valueOf(sub[1]),subRootPath); } } //subMap存储的最后元素正是比当前小的前一个节点 SortedMap<Long,String> subMap = sortMap.subMap(0L,curPathNum); if (subMap.size() == 0){ //第一个获取锁,直接返回 LockData lockData = new LockData(lockKey,curLockPath,new AtomicInteger(1)); List<LockData> lockData1 = lockDataMap.get(Thread.currentThread()); if(lockData1 == null){ lockData1 = new ArrayList<>(); } lockData1.add(lockData); lockDataMap.put(Thread.currentThread(),lockData1); return true; } //前一个节点 String prevNodePath = null; if(subMap.size() != 0){ Long key = subMap.lastKey(); prevNodePath = subMap.get(key); } log.info("[{}]前一个节点 [{}]",curLockPath,prevNodePath); //创建一个计数器 CountDownLatch countDownLatch = new CountDownLatch(1); if(prevNodePath != null){ //添加监听器 zkClient.checkExistsAndAddWatch(getWatcherPath(prevNodePath),new Thread(){ @Override public void run() { countDownLatch.countDown(); } }); try{ log.info("等待节点[{}]释放.......",prevNodePath); countDownLatch.await(); log.info("节点[{}]释放! 获取锁[{}]",prevNodePath,curLockPath); LockData lockData = new LockData(lockKey,curLockPath,new AtomicInteger(1)); List<LockData> lockData1 = lockDataMap.get(Thread.currentThread()); if(lockData1 == null){ lockData1 = new ArrayList<>(); } lockData1.add(lockData); lockDataMap.put(Thread.currentThread(),lockData1); return true; } catch(Exception ex){ log.error(ex.getMessage()); } } } return false; } public boolean tryLock(String lockStr, int millisecondsToExpire, int timeoutMs) { return false; } /** *功能描述 * @author lgj * @Description 解锁操作 * @date 4/20/19 * @param: * @return: * */ public void unlock(String lockKey) { List<LockData> lockDatas = lockDataMap.get(Thread.currentThread()); if(lockDatas != null){ List<LockData> selectlockData = lockDatas.stream().filter((val)-> val.lockKey.equals(lockKey)).collect(Collectors.toList()); if(selectlockData.size() == 0){ log.info("从未获取过该锁[{}-{}]",lockKey); return; } int count = selectlockData.get(0).lockCount.decrementAndGet(); if(count == 0){ log.info("释放锁,删除[{}]",selectlockData.get(0).createLockPath); zkClient.remove(selectlockData.get(0).createLockPath); } List<LockData> filter = lockDatas.stream().filter((val)-> !val.lockKey.equals(lockKey)).collect(Collectors.toList()); filter.add(selectlockData.get(0)); lockDataMap.put(Thread.currentThread(),filter); } } private String getCreatePath(String subPath){ return new StringBuilder().append(LOCK_ROOT_PATH).append("/").append(subPath).append(LOCKPATH_SEPARATOR).toString(); } private String getWatcherPath(String subPath){ return new StringBuilder().append(LOCK_ROOT_PATH).append("/").append(subPath).toString(); } @ToString @AllArgsConstructor private static class LockData{ //锁key -》 lockName //lock(lockName) private String lockKey; //zookeeper 中的锁节点路径 /locks/lockName_0000000001 private String createLockPath; //可重入锁计数器,初始0,每申请一次锁加1,解锁时为0才能删除节点 private AtomicInteger lockCount; } } <file_sep>package com.nz.rpc.netty.message; import io.netty.buffer.ByteBuf; public class MagicUtil { public static final long MAGIC = 0xAABBA1B2C3D4E5F6l; public static ByteBuf writeMagicToBytebuf(ByteBuf byteBuf){ byteBuf.writeLong(MAGIC); return byteBuf; } public static ByteBuf checkMagic(ByteBuf byteBuf){ if(byteBuf.readableBytes() > 4){ long magic = byteBuf.readLong(); } return null; } } <file_sep>package app.provider1; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AppProviderApplication { public static void main(String args[]){ SpringApplication.run(AppProviderApplication.class,args); } } <file_sep>package com.nz.rpc.proxy; /** *功能描述 * @author lgj * @Description 动态代理创建类接口 * @date 4/14/19 */ public interface ProxyCreate { public <T> T createInstance(Class<T> interfaceClass); public ProxyCreate invoker(RpcInvoker invoker); }<file_sep>cd ~/aProject/aRealPrj/nz-rpc/app-demo/app-test/target java -Dtest.nums=$1 -jar test-1.0.0.jar <file_sep>package com.nz.rpc.constans; public class RpcClientConstans { public static final String NETTY_REQUEST_HOST = "netty.request.host"; public static final String NETTY_REQUEST_PORT = "netty.request.port"; } <file_sep>package com.nz.rpc.interceptor; import com.nz.rpc.interceptor.exception.AddInterceptorException; import lombok.Data; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; /** *功能描述 * @author lgj * @Description 拦截器包装类 * @date 4/25/19 */ @Data public class InterceptorChain { private List<Entry> entries; private Set<String> names; public InterceptorChain() { entries = new LinkedList<>(); names = new HashSet<>(); } public void addFirst(String name,Interceptor interceptor) throws AddInterceptorException { synchronized (this){ checkDuplicateName(name); Entry entry = new Entry(name,interceptor); insertInterceptor(0,entry); } } public void addLast(String name,Interceptor interceptor)throws AddInterceptorException { synchronized (this){ checkDuplicateName(name); Entry entry = new Entry(name,interceptor); insertInterceptor(entries.size(),entry); } } public void addAfter(String baseName,String name,Interceptor interceptor)throws AddInterceptorException { synchronized (this){ checkDuplicateName(name); checkExistName(baseName); Entry entry = new Entry(name,interceptor); int index = getIndexByName(baseName); insertInterceptor(index+1,entry); } } public void addBefore(String baseName, String name,Interceptor interceptor)throws AddInterceptorException { synchronized (this){ checkDuplicateName(name); checkExistName(baseName); Entry entry = new Entry(name,interceptor); int index = getIndexByName(baseName); insertInterceptor(index,entry); } } private int getIndexByName(String name) throws AddInterceptorException { for(Entry entry:entries){ if(entry.name.equals(name)){ return entries.indexOf(entry); } } throw new AddInterceptorException("添加拦截器失败,拦截器["+name+"]未存在!"); } private void checkDuplicateName(String name) throws AddInterceptorException { if(names.contains(name)){ throw new AddInterceptorException("添加拦截器失败,拦截器["+name+"]已经存在!"); } } private void checkExistName(String name) throws AddInterceptorException { if(!names.contains(name)){ throw new AddInterceptorException("添加拦截器失败,拦截器["+name+"]未存在!"); } } private void insertInterceptor(int index,Entry entry){ names.add(entry.name); entries.add(index,entry); } @Data static class Entry{ String name; Interceptor interceptor; public Entry(String name, Interceptor interceptor) { super(); this.name = name; this.interceptor = interceptor; } } public List<Interceptor> getInterceptor(){ List<Interceptor> interceptors = new LinkedList<>(); synchronized (this){ entries.forEach((v)->{ interceptors.add(v.interceptor); }); } return interceptors; } } <file_sep>#!/bin/bash JAR_PATH="/home/lgj/aProject/aRealPrj/nz-rpc/app-demo/app-provider/target/app-provider-1.0.0.jar" JAVA_OPT="${JAVA_OPT} -server -Xms1024m -Xmx1024m -Xmn800m -XX:MetaspaceSize=800m -XX:MaxMetaspaceSize=1000m" java -jar ${JAVA_OPT} ${JAR_PATH} <file_sep>package com.nz.rpc.netty.client; import com.nz.rpc.netty.NettyContext; import com.nz.rpc.properties.RpcProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class NettyClientAutoConfiguration { @Autowired RpcProperties rpcProperties; @Bean NettyClient nettyClient(){ NettyClient nettyClient = new NettyClient(rpcProperties); nettyClient.init(); NettyContext.setNettyClient(nettyClient); // NettyContext.setSerialize(SerializationCreate.create(rpcProperties.getSerialization())); return nettyClient; } } <file_sep># 基于netty和zookeeper的RPC框架 ## 说明 nzRpc是一个基于netty和zookeeper的RPC框架,使用netty作为底层socket通信框架。使用Zookeeper作为注册中心。 * 服务提供者启动时会向服务注册中心注册相关信息[注册信息](https://github.com/lgjlife/nz-rpc/blob/master/rpc-integration%2Fsrc%2Fmain%2Fjava%2Fcom%2Fnz%2Frpc%2Fdiscover%2FProviderConfig.java) * 消费者启动时,会获取注册信息,并缓存在应用中 * 消费者会监听注册信息的变化,比如服务提供者上线,并进行更新。 * 服务调用不经过注册中心,运行过程中注册中心宕机不影响服务调用。 目前仅支持SpringBoot应用,提供端和消费端只要引入注解[@RpcService](https://github.com/lgjlife/nz-rpc/blob/master/rpc-integration%2Fsrc%2Fmain%2Fjava%2Fcom%2Fnz%2Frpc%2Fanno%2FRpcService.java)和[@RpcReference](https://github.com/lgjlife/nz-rpc/blob/master/rpc-integration%2Fsrc%2Fmain%2Fjava%2Fcom%2Fnz%2Frpc%2Fanno%2FRpcReference.java),并在application.yml中进行端口和IP配置,即可轻易使用,详细可参见如下<a href="#use">使用说明</a> *整体架构图* ![](https://github.com/lgjlife/nz-rpc/blob/master/doc/1.png) ![](https://github.com/lgjlife/nz-rpc/blob/master/doc/2.png) ## 基本特性 * 模块配置成SpringBoot Starter,引入POM依赖即可 * 每一个节点既可以作为服务消费者,也可以作为服务提供者 * 接入简单,通过添加注解[RpcReference](https://github.com/lgjlife/nz-rpc/blob/master/rpc-integration%2Fsrc%2Fmain%2Fjava%2Fcom%2Fnz%2Frpc%2Fanno%2FRpcReference.java)和[RpcService](https://github.com/lgjlife/nz-rpc/blob/master/rpc-integration%2Fsrc%2Fmain%2Fjava%2Fcom%2Fnz%2Frpc%2Fanno%2FRpcService.java),即可零配置启动。 * 使用zookeeper实现服务注册与发现 * 服务提供者,服务消费者,服务注册中心之间为长连接 * 服务提供者信息缓存在消费者本地缓存,服务注册中心挂掉不影响服务调用,但新启动应用将无法加入 * 支持服务下线通知,服务上线通知,上线和下线将会更新应用本地服务提供者的缓存信息 * 使用Netty作为底层NIO通信框架 * 心跳机制检测连接状态 * 自定义消息协议 * 连接失败自动重连 * 对端关闭则释放本端连接资源 * 动态代理支持JDK和CGLIB方式,默认为JDK方式,可配置 * 序列化支持JDK,Fastjson,Protostuff,Hessian方式,默认为Hessian方式,可配置 * 服务容错策略: failfast快速失败,failsafe安全失败,failback失败定时重试 * 通过责任链设计模式实现请求过程的链式处理,包括集群容错处理,超时处理,负载均衡选择,请求发送,各个功能间无耦合,扩展方便 * 请求支持同步请求和异步请求,异步请求的返回值需为CompletableFuture类型 * 负载均衡实现:随机,加权随机,轮轮询,加权轮询,最小时间法,一致性Hash * 全局唯一ID实现,雪花算法、redis生成、zookeeper生成 * 分布式锁实现:redis/zookeeper实现 ## 性能测试 使用Jmeter进行性能测试 jvm参数:-server -Xms1024m -Xmx1024m -Xmn800m -XX:MetaspaceSize=800m -XX:MaxMetaspaceSize=1000m 10万并发线程请求下的响应时间(更新于2019-07-26) ![](https://github.com/lgjlife/nz-rpc/blob/master/doc/responsetime.png) ## 模块介绍 ├─── nzrpc ├──── rpc-integration rpc实现框架 ├──── app-demo 使用demo ├────── app-common 用于存放demo公共接口 ├────── app-consumer 消费者 ├────── app-provider 既是消费者又是服务提供者 ├────── app-provider1 服务提供者 ├────── app-dubbo-consumer dubbo 消费者 ├────── app-dubbo-provider dubbo 提供者 ## 类说明 ├─── nz/ ├─── rpc/ ├─── anno/ ├─── RpcReference 注解在服务消费端接口引用上,用于标示该引用是消费者接口 ├─── RpcService 注解在服务提供端接口实现类上,用于标示该类为消费者提供服务 ├─── cluster/ ├─── AbstractClusterFaultConfig 集群错误配置类,用于用户配置接口对应的从错策略 ├─── ClusterFault 容错策略接口 ├─── ClusterFaultAutoconfiguration 集群容错自动配置类,配置各个容错策略Bean ├─── ClusterFaultHandler 集群容错处理类 ├─── FailbackClusterFault 失败定时重试处理方式 ├─── FailfastClusterFault 快速失败,立即抛出异常给调用者 ├─── FailoverClusterFault 失败自动切换,未实现 ├─── FailsafeClusterFault 失败安全,不作处理,返回null ├─── constans/ ├─── RpcClientConstans 用于存放一些静态变量,比去key ├─── context/ ├─── ClientContext 客户端请求过程上下文,存放一些通用属性 ├─── discover/ ├─── AbstractServiceDiscover 服务注册与发现抽象类 ├─── DiscoverAutoConfiguration    服务注册与发现自动配置类 ├─── ProviderConfig 服务注册配置类 ├─── ProviderConfigContainer ├─── ZookeeperServiceDiscover 实现类,用于服务发现 ├─── ZookeeperServiceRegister     实现类,用于服务注册 ├─── exception/ ├─── MessageSendFailException ├─── RpcRuntimeException ├─── executor/ ├─── TraceExecutorService 重写线程池,支持打印线程池异常错误堆栈 ├─── interceptor/ ├─── exception/ ├─── AddInterceptorException 添加拦截器异常 ├─── RequestTimeOutException 请求超时异常 ├─── impl/ ├─── ClusterFaultToleranceInterceptor 集群容错拦截器 ├─── RpcClientRequestInterceptor 执行最终的客户端请求拦截器 ├─── ServiceSelectInterceptor 负载均衡处理拦截器,用于选择Server ├─── TimeOutInterceptor 请求超时处理拦截器 ├─── ClientInterceptorAutoConfiguration 责任链自动配置类 ├─── Interceptor 拦截器接口 ├─── InterceptorChain 拦截器操作类,用于添加,移除拦截器等操作 ├─── invocation/ ├─── client/ ├─── ClientInvocation 用于责任链中传递消息的接口 ├─── RpcClientInvocation 实现类 ├─── loadbalabce/ ├─── exception/ ├─── LoadbalanceException 负载均衡异常 ├─── AbstractLoadbalanceConfig 用于用户配置接口对应的负载均衡该策略 ├─── LeastActiveLoadbalanceStrategy 最小调用时延 ├─── LoadbalanceAutoConfig 负载均衡自动配置类 ├─── LoadbalanceStrategy          负载均衡策略接口 ├─── LoadbanlanceHandler 负载均衡操作类 ├─── PollingLoadbalanceStrategy      轮询算法 ├─── RandomLoadbalanceStrategy    随机负载均衡 ├─── UniformityHashLoadbalanceStrategy  一致性hash算法 ├─── WeightPollingLoadbalanceStrategy   加权轮询算法 ├─── WeightRandomLoadbalanceStrategy   加权随机负载均衡 ├─── lock/ ├─── exception/ ├─── RequestLockException    请求锁异常 ├─── redis/ ├─── RedisAutoConfiguration   Redis自动配置类 ├─── RedisClient         Redis操作客户端 ├─── RedisLockUtil        Redis锁实现 ├─── RedisPoolClient       Redis连接池 ├─── zk/ ├─── ZkClient          zookeeper客户端操作 ├─── ZkLockUtil         zookeeper分布式锁实现 ├─── Lock               分布式锁接口 ├─── LockProperties         Lock模块属性配置类 ├─── msg/ ├─── request/ ├─── AbstractRequestHandler ├─── RequestHandler ├─── RpcRequestHandler ├─── ClientMessageHandler       客户端消息综合处理类 ├─── MsgAutoConfiguration       自动配置类 ├─── RpcRequest             netty通信请求pojo ├─── RpcResponse             netty通信响应pojo ├─── ServerMessageHandler       server消息综合处理类 ├─── netty/ ├─── client/ ├─── handle/ ├─── ClientChannelInboundHandler  数据输入处理handler ├─── ClientChannelOutboundHandle  数据输出处理handler ├─── HeartbeatRequestHandler    心跳请求处理类 ├─── NettyChannelHandler       责任连管理类 ├─── NettyClient              netty客户端相关处理 ├─── NettyClientAutoConfiguration    客户端自动配置类 ├─── coder/ ├─── MessageBodyUtil 消息的body编解码 ├─── MessageIndex 消息中的各个字段的相对位置 ├─── NettyMessageDecode 消息解码处理 ├─── NettyMessageEncoder         消息编码处理 ├─── message/ ├─── Header 消息头 ├─── MessageType              消息类型 ├─── NettyMessage              整个消息 ├─── server/ ├─── handle/ ├─── ChildChannelHandler       服务端责任连管理 ├─── HeartbeatResponseHandler     服务端心跳处理类 ├─── ServerChannelInboundHandler   服务端数据输入处理handler ├─── ServerChannelOutboundHandle 服务端数据输出处理handler ├─── NettyServer netty服务端相关处理 ├─── NettyServerAutoConfiguration     netty服务端自动配置类 ├─── properties/ ├─── RpcProperties           系统所有的配置,相关配置在application.yml中进行配置 ├─── proxy/ ├─── ProxyCreate           动态代理创建类接口 ├─── CglibProxyCreate         cglib动态代理创建类实现类 ├─── JavassitProxyCreate       Javassit动态代理创建类实现类 ├─── JdkProxyCreate jdk动态代理创建类实现类 ├─── ProxySelector 用于根据配置选择对应的动态代理创建类 ├─── RpcInvoker            接口动态代理类,用于执行方法拦截 ├─── RpcProxyFactory         动态代理类生成工厂 ├─── serialization/ ├─── AbstractSerialize 序列化抽象接口 ├─── FastjsonSerializeUtil        Fastjson实现类 ├─── HessianSerializeUtil       Hessian实现类 ├─── JdkSerializeUtil        Jdk实现类 ├─── ProtostuffSerializeUtil       Protostuff实现类 ├─── SerializationAutoConfiguration   序列化自动配置类 ├─── SerializationCreate          序列化创建工厂 ├─── uid/ ├─── UidProducer          分布式唯一ID生成接口 ├─── UUidProducer 使用JDK的UUID来生成唯一ID ├─── CustomProducer 自定义唯一id生成方式 ├─── UidAutoConfiguration     唯一id模块自动配置类 ├─── ZkUidProducer         zookeeper方式生成唯一id ├─── zk/ ├─── ZkCli zookeeper操作类,用于连接读写操作 ├─── ZkCreateConfig           zk创建path时的配置类 ├─── ZkListener             zk监听器 ├─── ZookeeperAutoConfigure      zk自动配置类 ├─── ZookeeperPath           zk路径的工具类 ## 使用技术 * Spring Boot-2.1 * Netty-4.1 底层通信实现 * Zookeeper-3.4 服务注册中心 <h1 id="use"></h1> ## 使用说明 * 每一个节点既可以作为服务消费者,也可以作为服务提供者,无需多余配置,使用上述配置即可。 * 启动应用需先安装zookeeper,并启动,应用的默认地址端口配置是按照zookeeper的默认参数设置,可不进行配置,只要添加相关注解即可。 * 相关使用实例参照[app-demo](https://github.com/lgjlife/nz-rpc/tree/master/app-demo) ### 服务提供端 * 依赖引入 ```xml <dependency> <groupId>com.nz.rpc</groupId> <artifactId>rpc-integration-spring-boot-starter</artifactId> <version>1.0.0</version> </dependency> ``` * application.yml配置 可以不进行配置 ,按默认配置即可启动,默认配置见[RpcProperties](https://github.com/lgjlife/nz-rpc/blob/master/rpc-integration%2Fsrc%2Fmain%2Fjava%2Fcom%2Fnz%2Frpc%2Fproperties%2FRpcProperties.java) ```yaml nzrpc: #zookeeper 连接地址,有多个通过逗号","间隔 zookeeper: address: "127.0.0.1:2181" #netty 监听地址端口 netty: port: 8121 # @RpcReference 注解的引用所在的包名,有多个使用逗号","间隔 scanPackage: "com,org" ``` * 定义公共接口 ```java public interface IUserService { String queryName(long id); } ``` * 实现上述接口 需要在接口上添加注解@RpcService ```java @Service @RpcService public class UserService implements IUserService { @Override public String queryName(long id) { return "UserService:"+id; } } ``` ### 服务消费端 * 依赖引入 ```xml <dependency> <groupId>com.nz.rpc</groupId> <artifactId>rpc-integration-spring-boot-starter</artifactId> <version>1.0.0</version> </dependency> ``` * application.yml配置 可以不进行配置 ,按默认配置即可启动,默认配置见[RpcProperties](https://github.com/lgjlife/nz-rpc/blob/master/rpc-integration%2Fsrc%2Fmain%2Fjava%2Fcom%2Fnz%2Frpc%2Fproperties%2FRpcProperties.java) ```yaml nzrpc: #zookeeper 连接地址,有多个通过逗号","间隔 zookeeper: address: "127.0.0.1:2181" #netty 监听地址端口 netty: port: 8121 # @RpcReference 注解的引用所在的包名,有多个使用逗号","间隔 scanPackage: "com,org" ``` ```java @Slf4j @RestController public class DemoController { //使用RpcReference注解 @RpcReference private UserService userService; @GetMapping("/demo") public void demo(){ //接口调用 userService.queryName("qqwq",13546L); } } ``` <file_sep>package com.nz.rpc.interceptor; import com.nz.rpc.invocation.client.ClientInvocation; import lombok.Data; import org.junit.Before; import org.junit.Test; public class InterceptorChainTest { InterceptorChain interceptorChain; @Before public void before(){ interceptorChain = new InterceptorChain(); } @Test public void addFirst() { try{ for(int i = 0; i< 5; i++){ interceptorChain.addFirst("name-"+i,new MyInterceptor()); } } catch(Exception ex){ System.out.println(ex.getMessage()); } System.out.println(interceptorChain.getEntries()); } @Test public void addLast() { try{ for(int i = 0; i< 5; i++){ interceptorChain.addLast("name-"+i,new MyInterceptor()); } } catch(Exception ex){ System.out.println(ex.getMessage()); } System.out.println(interceptorChain.getEntries()); } @Test public void addAfter() { try{ interceptorChain.addFirst("name-0",new MyInterceptor()); interceptorChain.addBefore("name-0","name-before",new MyInterceptor()); interceptorChain.addAfter("name-1","name-after",new MyInterceptor()); } catch(Exception ex){ System.out.println(ex.getMessage()); } System.out.println(interceptorChain.getEntries()); } @Test public void addBefore() { } } @Data class MyInterceptor implements Interceptor{ @Override public Object intercept(ClientInvocation invocation) throws RuntimeException { return null; } }<file_sep>package com.nz.rpc.interceptor.impl; import com.nz.rpc.constans.RpcClientConstans; import com.nz.rpc.context.ClientContext; import com.nz.rpc.interceptor.Interceptor; import com.nz.rpc.invocation.client.ClientInvocation; import com.nz.rpc.msg.ClientMessageHandler; import com.nz.rpc.msg.RpcRequest; import com.nz.rpc.netty.message.Header; import com.nz.rpc.netty.message.MessageType; import com.nz.rpc.netty.message.NettyMessage; import com.nz.rpc.time.TimeUtil; import com.nz.rpc.uid.UidProducer; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.Method; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicLong; /** *功能描述 * @author lgj * @Description 客户端请求责任链处理 * @date 5/6/19 */ @Slf4j public class RpcClientRequestInterceptor implements Interceptor { private UidProducer uidProducer ; private AtomicLong requestId = new AtomicLong(0); private ClientMessageHandler handler; public RpcClientRequestInterceptor(UidProducer uidProducer, ClientMessageHandler handler) { this.uidProducer = uidProducer; this.handler = handler; } @Override public Object intercept(ClientInvocation invocation) throws Exception { Object result = null; log.debug("RpcClientRequestInterceptor start ...."); //log.info("正在执行RpcRequestInterceptor...."); //准备消息 RpcRequest request = buildRequest(invocation.getMethod(),invocation.getArgs()); NettyMessage nettyMessage = buildNettyMessage(request); long id = ((RpcRequest)nettyMessage.getBody()).getRequestId(); TimeUtil.start("RpcClientRequestInterceptor intercept", id); handler.sendRequest(invocation.getAttachments().get(RpcClientConstans.NETTY_REQUEST_HOST), invocation.getAttachments().get(RpcClientConstans.NETTY_REQUEST_PORT), nettyMessage); if( CompletableFuture.class.isAssignableFrom(invocation.getMethod().getReturnType())){ //异步请求 log.info("异步请求"); CompletableFuture future = ClientContext.createCompletableFuture(id); return future; } else{ log.info("同步请求"); result = handler.getServerResponseResult( invocation,id); TimeUtil.endAndPrint("RpcClientRequestInterceptor intercept", id); if(log.isInfoEnabled()){ log.info("request result =[{}]",result); } return result; } } private NettyMessage buildNettyMessage(RpcRequest request){ NettyMessage nettyMessage = new NettyMessage(); Header header = new Header(); header.setType(MessageType.APP_REQUEST_TYPE.getValue()); nettyMessage.setHeader(header); nettyMessage.setBody(request); return nettyMessage; } /** *功能描述 * @author lgj * @Description 创建请求对象 * @date 5/6/19 */ private RpcRequest buildRequest(Method method, Object[] args){ String[] classes = new String[args.length]; for(int i = 0; i< args.length ; i++){ classes[i] = args[i].getClass().getName(); } RpcRequest request = new RpcRequest(); request.setRequestId(requestId.getAndIncrement());//(uidProducer.getUid()); request.setInterfaceName(method.getDeclaringClass().getName()); request.setMethodName(method.getName()); request.setParameterTypes(classes); request.setParameters(args); return request; } } <file_sep>package com.demo.test.service; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import javax.annotation.PostConstruct; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeSet; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.atomic.AtomicInteger; @Slf4j @Service @Data public class TestRequest { private Map<String,String> urlMap = new LinkedHashMap<>(); private int defaultTestNums = 1; private int nums = defaultTestNums; private Map<String,TreeSet<Long>> takeTimeMap = new LinkedHashMap<>(); public TreeSet startTest(String type){ AtomicInteger successCount =new AtomicInteger(0); RestTemplate restTemplate = new RestTemplate(); successCount.set(0); String testNums = System.getProperty("test.nums"); log.info("testNums:{}",testNums); if(testNums != null){ nums = Integer.valueOf(testNums); } TimeRecord timeRecord = new TimeRecord(); CyclicBarrier startCyclicBarrier = new CyclicBarrier(nums,new StartTask(timeRecord)); CyclicBarrier endCyclicBarrier = new CyclicBarrier(nums,new EndTask(timeRecord,successCount,type)); for(int i = 0; i< nums; i++){ new Thread(){ @Override public void run() { try{ startCyclicBarrier.await(); long startTime = System.currentTimeMillis(); String result = new RestTemplate().getForObject(urlMap.get(type),String.class); long endTime = System.currentTimeMillis(); if(result != null){ log.info("success:[{}]",(endTime-startTime)); successCount.incrementAndGet(); } else { log.info("fail:[{}]",(endTime-startTime)); } endCyclicBarrier.await(); } catch(Exception ex){ log.error(ex.getMessage()); try{ endCyclicBarrier.await(); } catch(Exception e){ log.error(e.getMessage()); } } } }.start(); } String result = ""; if(takeTimeMap.get(type).size()>0){ result = "first:"+takeTimeMap.get(type).first() + " last:" + takeTimeMap.get(type).last(); } return takeTimeMap.get(type); } /** *功能描述 * @author lgj * @Description 数据准备 * @date 5/5/19 * @param: * @return: * */ @PostConstruct public void init(){ urlMap.put("nzrpc","http://localhost:8112/demo"); urlMap.put("dubbo","http://localhost:8583/demo"); takeTimeMap.put("nzrpc",new TreeSet<Long>()); takeTimeMap.put("dubbo",new TreeSet<Long>()); //startTest("nzrpc"); } @Data class TimeRecord{ private Long startTime = 0L; private Long endTime = 0L; } class StartTask implements Runnable{ private TimeRecord timeRecord; public StartTask(TimeRecord timeRecord) { this.timeRecord = timeRecord; } @Override public void run() { log.info("start request........."); timeRecord.startTime = System.currentTimeMillis(); } } class EndTask implements Runnable{ private TimeRecord timeRecord; private AtomicInteger successCount; private String type; public EndTask(TimeRecord timeRecord, AtomicInteger successCount, String type) { this.timeRecord = timeRecord; this.successCount = successCount; this.type = type; } @Override public void run() { long diff = System.currentTimeMillis() - timeRecord.getStartTime(); takeTimeMap.get(type).add(diff); log.info("end request........."); log.info("successCount = " + successCount.get()); log.info("All the request [{}] take time : :[{}]",nums,diff); } } } <file_sep>package com.nz.rpc.netty.client.handler; import com.nz.rpc.netty.coder.NettyMessageDecode; import com.nz.rpc.netty.coder.NettyMessageEncoder; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.timeout.IdleStateHandler; import java.util.concurrent.TimeUnit; /** *功能描述 * @author lgj * @Description 注册handler 拦截器 * @date 3/15/19 */ public class NettyChannelHandler extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { // CoderConfig.JdkCoder(socketChannel); ChannelPipeline pipeline = socketChannel.pipeline(); pipeline.addLast(new NettyMessageDecode(1024*1024,9,4)); pipeline.addLast(new IdleStateHandler(75, 25, 0, TimeUnit.SECONDS)); pipeline.addLast(new HeartbeatRequestHandler()); pipeline.addLast(new NettyMessageEncoder()); pipeline.addLast(new ClientChannelInboundHandler()); } } <file_sep>package com.nz.rpc.invocation.client; import com.nz.rpc.context.ClientContext; import com.nz.rpc.exception.MessageSendFailException; import com.nz.rpc.interceptor.Interceptor; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @Slf4j public class RpcClientInvocation implements ClientInvocation { private Method method; private Object[] args; private List<Interceptor> interceptors; private int index = 0; private Map<String, String> attachments = new ConcurrentHashMap<>(); public RpcClientInvocation(Method method, Object[] args) { this.method = method; this.args = args; this.interceptors = ClientContext.interceptors; } public RpcClientInvocation(Method method, Object[] args, List<Interceptor> interceptors) { this.method = method; this.args = args; } @Override public Object executeNext() throws Exception { Object result = null; if (index < interceptors.size()){ result = interceptors.get(index++).intercept(this); } else { throw new MessageSendFailException("No server can be to send the request message!"); } return result; } @Override public Method getMethod() { return method; } @Override public Object[] getArgs() { return args; } @Override public Map<String, String> getAttachments() { return attachments; } @Override public void resetIndex() { index = 0; } } <file_sep>package com.nz.rpc.time; import lombok.extern.slf4j.Slf4j; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @Slf4j public class TimeUtil { private static Map<String,Long> timeMap = new ConcurrentHashMap(); public static void start(String name ,Long id){ String key = name+id; timeMap.put(key,System.currentTimeMillis()); } public static void endAndPrint(String name ,Long id){ String key = name+id; if(timeMap.containsKey(key)){ log.debug("{} time is {} ms ",key,System.currentTimeMillis() -timeMap.get(key)); timeMap.remove(key); } } } <file_sep>package com.nz.rpc.proxy; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.Proxy; /** *功能描述 * @author lgj * @Description jdk * @date 4/14/19 */ @Slf4j public class JdkProxyCreate implements ProxyCreate { private RpcInvoker rpcInvoker; public <T> T createInstance(Class<T> interfaceClass){ log.info("use jdk dynamic proxy : " + interfaceClass.getSimpleName()); log.debug("getClassLoader = " + interfaceClass.getClassLoader() + " getInterfaces = " + interfaceClass.getInterfaces()); T instance = (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, rpcInvoker); return instance; } @Override public ProxyCreate invoker(RpcInvoker invoker) { this.rpcInvoker = invoker; return this; } }<file_sep> echo ################################# echo ################################# echo ################################# pwd echo echo ################################ cd ~/aProject/aRealPrj/nz-rpc/app-demo/app-consumer pwd mvn package -Dmaven.test.skip=true cd - ############################################ echo ################################# echo ################################# echo ################################# pwd echo echo ################################ cd ~/aProject/aRealPrj/nz-rpc/app-demo/app-provider pwd echo mvn package -Dmaven.test.skip=true cd - ################################### echo ################################# echo ################################# echo ################################# echo echo ################################ cd ~/aProject/aRealPrj/nz-rpc/app-demo/app-provider pwd mvn package -Dmaven.test.skip=true cd - ############################################ echo ################################# echo ################################# echo ################################# pwd echo echo ################################ cd ~/aProject/aRealPrj/nz-rpc/app-demo/app-test pwd echo mvn package -Dmaven.test.skip=true cd - <file_sep>package com.nz.rpc.proxy; import lombok.extern.slf4j.Slf4j; /** *功能描述 * @author lgj * @Description 动态代理选择 * @date 4/14/19 */ @Slf4j public class ProxySelector { public static ProxyCreate select(String type){ log.debug("ProxySelector 动态代理:{}",type); switch (type){ case "jdk": return new JdkProxyCreate(); case "cglib": return new CglibProxyCreate(); case "javassit": return new JavassitProxyCreate(); default: return new JdkProxyCreate(); } } } <file_sep>package com.nz.rpc.serialization; /** *功能描述 * @author lgj * @Description 序列化工厂类 * @date 7/11/19 */ public class SerializeFactory { private static volatile AbstractSerialize fastjsonSerialize; private static volatile AbstractSerialize hessianSerialize; private static volatile AbstractSerialize jacksonSerialize; private static volatile AbstractSerialize jdkjsonSerialize; private static volatile AbstractSerialize protostuffSerialize; public static AbstractSerialize getFastjsonSerialize() { if(fastjsonSerialize == null){ synchronized (FastjsonSerializeUtil.class){ if(fastjsonSerialize == null){ fastjsonSerialize = new FastjsonSerializeUtil(); } } } return fastjsonSerialize; } public static AbstractSerialize getHessianSerialize() { if(hessianSerialize == null){ synchronized (HessianSerializeUtil.class){ if(hessianSerialize == null){ hessianSerialize = new HessianSerializeUtil(); } } } return hessianSerialize; } public static AbstractSerialize getJacksonSerialize() { if(jacksonSerialize == null){ synchronized (JacksonSerializeUtil.class){ if(jacksonSerialize == null){ jacksonSerialize = new JacksonSerializeUtil(); } } } return jacksonSerialize; } public static AbstractSerialize getJdkjsonSerialize() { if(jdkjsonSerialize == null){ synchronized (JdkSerializeUtil.class){ if(jdkjsonSerialize == null){ jdkjsonSerialize = new JdkSerializeUtil(); } } } return jdkjsonSerialize; } public static AbstractSerialize getProtostuffSerialize() { if(protostuffSerialize == null){ synchronized (ProtostuffSerializeUtil.class){ if(protostuffSerialize == null){ protostuffSerialize = new ProtostuffSerializeUtil(); } } } return protostuffSerialize; } } <file_sep>package com.nz.rpc.loadbalance; import com.nz.rpc.discover.ProviderConfig; import java.util.Arrays; import java.util.Comparator; import java.util.List; /** *功能描述 * @author lgj * @Description 负载均衡-最小调用时延 * @date 3/28/19 */ public class LeastActiveLoadbalanceStrategy implements LoadbalanceStrategy{ public ProviderConfig doSelect(List<ProviderConfig> configs, Object object){ ProviderConfig[] registryConfigs= new ProviderConfig[configs.size()]; configs.toArray(registryConfigs); Arrays.sort(registryConfigs, new Comparator<ProviderConfig>() { @Override public int compare(ProviderConfig o1, ProviderConfig o2) { if(o1.getCallTime() < o2.getCallTime()){ return -1; } else if(o1.getCallTime() == o2.getCallTime()){ return 0; } else { return 1; } } }); return registryConfigs[0]; } } <file_sep>package com.nz.rpc.loadbalance; import com.nz.rpc.discover.ProviderConfig; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** *功能描述 * @author lgj * @Description 负载均衡--轮询 * @date 3/28/19 */ public class PollingLoadbalanceStrategy implements LoadbalanceStrategy { //使用一个Map来缓存每类应用的轮询索引 private Map<String,Integer> indexMap = new ConcurrentHashMap<>(); public ProviderConfig doSelect(List<ProviderConfig> configs, Object object){ Integer index = indexMap.get(getKey(configs.get(0))); if(index == null){ indexMap.put(getKey(configs.get(0)),0); return configs.get(0); } else { index++; if(index >= configs.size()){ index = 0; } indexMap.put(getKey(configs.get(0)),index); return configs.get(index); } } public String getKey(ProviderConfig config){ return config.getInterfaceName(); } } <file_sep>package com.nz.rpc.msg.request; import com.nz.rpc.msg.RpcRequest; import java.lang.reflect.Method; public abstract class AbstractRequestHandler implements RequestHandler { @Override public Object invoke(Method method, Object[] args) { return null; } public abstract Object doInvoke(); private RpcRequest buildRequest(Method method, Object[] args){ String[] classes = new String[args.length]; for(int i = 0; i< args.length ; i++){ classes[i] = args[i].getClass().getName(); } RpcRequest request = new RpcRequest(); // request.setRequestId(uidProducer.getUid()); request.setInterfaceName(method.getDeclaringClass().getName()); request.setMethodName(method.getName()); request.setParameterTypes(classes); request.setParameters(args); return request; } } <file_sep>package com.nz.rpc.serialization; public class TimeUtil { private long startTime; private long endTime; private long timeSum; private long count; public void init(){ timeSum = 0; count = 0; } public void start(){ startTime = System.nanoTime(); } public void end(){ endTime = System.nanoTime(); timeSum += (endTime-startTime); count++; } public long getAvrTimeNs(){ return (timeSum/count); } public long getAvrTimeUs(){ return (timeSum/count)/1000; } public long getAvrTimeMs(){ return (timeSum/count)/1000000; } } <file_sep>package com.nz.rpc.cluster; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** *功能描述 * @author lgj * @Description 集群容错配置类 * @date 7/12/19 */ @Configuration public class ClusterFaultAutoconfiguration { @Autowired private ApplicationContext context; @Bean public ClusterFaultHandler clusterFaultHandler(){ ClusterFaultHandler clusterFaultHandler = new ClusterFaultHandler(); clusterFaultHandler.setContext(context); clusterFaultHandler.scan(); return clusterFaultHandler; } @Bean public ClusterFault failfastClusterFaultTolerance(){ return new FailfastClusterFault(); } @Bean public FailsafeClusterFault failsaveClusterFault(){ return new FailsafeClusterFault(); } @Bean FailbackClusterFault failbackClusterFault(){ return new FailbackClusterFault(); } } <file_sep>package com.nz.rpc.serialization; public abstract class AbstractSerialize { public abstract <T> byte[] serialize(T obj) throws Exception; public abstract <T> T deserialize(byte[] data, Class<T> clazz) throws Exception; } <file_sep>package com.nz.rpc.lock.redis; import com.nz.rpc.lock.LockProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; @Configuration @EnableConfigurationProperties(LockProperties.class) public class RedisAutoConfiguration { /* @Autowired private LockProperties lockProperties; @Bean RedisPoolClient redisPoolClient(){ RedisPoolClient redisPoolClient = new RedisPoolClient(lockProperties); return redisPoolClient; } @Bean public RedisClient redisClient(){ RedisClient redisClient = new RedisClient(); redisClient.setRedisPoolClient(redisPoolClient()); return redisClient; }*/ } <file_sep>cd ~/java/zookeeper-3.4.13/bin pwd ./zkServer.sh restart cd - pwd <file_sep>package com.nz.rpc.discover; import com.nz.rpc.netty.client.NettyClient; import com.nz.rpc.properties.RpcProperties; import com.nz.rpc.proxy.RpcProxyFactory; import com.nz.rpc.zk.ZkCli; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @ConditionalOnClass(RpcProperties.class) @EnableConfigurationProperties(RpcProperties.class) @Configuration public class DiscoverAutoConfiguration { @Autowired ApplicationContext context; @Autowired RpcProperties rpcProperties; @Autowired private ZkCli zkCli; @Autowired public RpcProxyFactory rpcProxyFactory; @Autowired private NettyClient nettyClient; /** *功能描述 * @author lgj * @Description 注册服务提供者 * @date 4/13/19 * @param: * @return: * */ @Bean public ZookeeperServiceRegister zookeeperServiceRegister(){ ZookeeperServiceRegister register = new ZookeeperServiceRegister(); register.setZkCli(zkCli); register.setContext(context); register.setProperties(rpcProperties); register.setRpcProxyFactory(rpcProxyFactory); //向zookeeper注册被 {@link com.nz.rpc.anno.RpcService}注解的类 register.registerService(); //查找被@RpcReference注解的消费者接口引用,并注入bean容器 register.consumerDiscover(); return register; } /** *功能描述 * @author lgj * @Description * @date 4/13/19 * @param: * @return: * */ @Bean public ZookeeperServiceDiscover zookeeperServiceDiscover(){ ZookeeperServiceDiscover discover = new ZookeeperServiceDiscover(zkCli); discover.setZkCli(zkCli); discover.setContext(context); discover.setProperties(rpcProperties); discover.setNettyClient(nettyClient); discover.queryService(); return discover; } } <file_sep>package com.nz.rpc.interceptor; import com.nz.rpc.invocation.client.ClientInvocation; /** *功能描述 * @author lgj * @Description 责任链接口 * @date 5/6/19 */ public interface Interceptor { Object intercept(ClientInvocation invocation) throws Exception; } <file_sep>package com.nz.rpc.cluster; import com.nz.rpc.invocation.client.ClientInvocation; import lombok.extern.slf4j.Slf4j; import java.util.Map; import java.util.UUID; import java.util.concurrent.*; /** *功能描述 * @author lgj * @Description 集群容错处理 Failback Cluster * 失败自动恢复,后台记录失败请求,定时重发。通常用于消息通知操作。 * @date 5/8/19 */ @Slf4j public class FailbackClusterFault implements ClusterFault { //重试间隔 private static final long RETRY_FAILED_PERIOD = 5 * 1000; private final ScheduledExecutorService retryExecutorService= Executors.newSingleThreadScheduledExecutor(); private Map<String,ScheduledFuture> futureMap = new ConcurrentHashMap<>(); public Object doHandle(ClientInvocation invocation,Exception ex) throws Exception{ final String uid = UUID.randomUUID().toString(); if(log.isErrorEnabled()){ log.error("Failback:Request[{}] error,ex = [{}]",invocation.getMethod(),ex.getMessage()); } ScheduledFuture<?> future = retryExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try{ invocation.resetIndex(); invocation.executeNext(); ScheduledFuture<?> future = futureMap.get(uid); future.cancel(false); futureMap.remove(uid); } catch(Exception ex){ log.error(ex.getMessage()); } } },RETRY_FAILED_PERIOD,RETRY_FAILED_PERIOD, TimeUnit.MILLISECONDS); futureMap.put(uid,future); return null; } } <file_sep>package com.nz.rpc.loadbalance; import com.nz.rpc.discover.ProviderConfig; import com.nz.rpc.loadbalance.exception.LoadbalanceException; import java.util.List; /** *功能描述 * @author lgj * @Description 负载均衡接口 * @date 3/28/19 */ public interface LoadbalanceStrategy { default public ProviderConfig select(List<ProviderConfig> configs, Object object) throws Exception{ if((configs == null) || (configs.isEmpty())){ throw new LoadbalanceException("Loadbalance fail!,No provider can select! "); } if(configs.size() == 1){ return configs.get(0); } return doSelect(configs,object); } ProviderConfig doSelect(List<ProviderConfig> configs, Object object) ; } <file_sep>package com.nz.rpc.loadbalance; import com.nz.rpc.discover.ProviderConfig; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** *功能描述 * @author lgj * @Description 负载均衡--加权轮询 * @date 3/28/19 */ public class WeightPollingLoadbalanceStrategy implements LoadbalanceStrategy { private Map<String,Integer> indexMap = new ConcurrentHashMap<>(); public ProviderConfig doSelect(List<ProviderConfig> configs, Object object) { Integer index = indexMap.get(getKey(configs.get(0))); if(index == null){ indexMap.put(getKey(configs.get(0)),0); return configs.get(0); } else { List<ProviderConfig> newConfigs = new ArrayList<>(); for(ProviderConfig config:configs){ for(int i = 0; i< config.getWeight(); i++){ newConfigs.add(config); } } index++; if(index >= newConfigs.size()){ index = 0; } indexMap.put(getKey(configs.get(0)),index); return newConfigs.get(index); } } public String getKey(ProviderConfig config){ return config.getInterfaceName(); } } <file_sep>./install.sh ./package.sh <file_sep>package com.nz.rpc.serialization; import com.caucho.hessian.io.HessianInput; import com.caucho.hessian.io.HessianOutput; import lombok.extern.slf4j.Slf4j; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Serializable; import java.util.concurrent.CompletableFuture; @Slf4j public class HessianSerializeUtil extends AbstractSerialize { public <T> byte[] serialize(T obj) throws Exception{ if (obj == null){ throw new NullPointerException(); } try{ ByteArrayOutputStream bos = new ByteArrayOutputStream(); HessianOutput ho = new HessianOutput(bos); ho.writeObject(obj); return bos.toByteArray(); } catch(Exception ex){ log.error("HessianSerializeUtil序列化发生异常!"+ex); throw new RuntimeException(); } } public <T> T deserialize(byte[] data, Class<T> clazz) throws Exception{ if (data == null){ throw new NullPointerException(); } try{ ByteArrayInputStream bis = new ByteArrayInputStream(data); HessianInput hi = new HessianInput(bis); return (T)hi.readObject(); } catch(Exception ex){ log.error("HessianSerializeUtil反序列化发生异常!"+ex); throw new RuntimeException(); } } public static void main(String args[]) throws Exception{ AsyncFuture future = new HessianSerializeUtil().new AsyncFuture(); AbstractSerialize serializeUtil = new HessianSerializeUtil(); serializeUtil.serialize(future); } class AsyncFuture<T> extends CompletableFuture<T> implements Serializable { } } <file_sep>package com.nz.rpc.lock.zk; import com.nz.rpc.lock.LockProperties; public class ZkClientFatory { public static LockProperties lockProperties(){ LockProperties lockProperties = new LockProperties(); lockProperties.setZookeeperAdress("localhost:2181"); return lockProperties; } public static ZkClient zkClient(){ ZkClient zkClient = new ZkClient(); zkClient.setProperties(lockProperties()); zkClient.connect(); return zkClient; } public static ZkLockUtil zkLockUtil(){ ZkLockUtil zkLockUtil = new ZkLockUtil(); zkLockUtil.setZkClient(zkClient()); return zkLockUtil; } } <file_sep>cd ~/java/redis-5.0.3/user pwd nohup ./redis-server redis.conf & cd - pwd <file_sep>package com.app.consumer.controller; import com.app.common.service.DemoService; import com.app.common.service.UserService; import com.nz.rpc.anno.RpcReference; import com.nz.rpc.uid.UidProducer; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.concurrent.atomic.AtomicInteger; @Slf4j @RestController public class DemoController { private AtomicInteger allCount = new AtomicInteger(0); private AtomicInteger successCount = new AtomicInteger(0); private AtomicInteger failCount = new AtomicInteger(0); @RpcReference private UserService userService; @RpcReference private DemoService demoService; @Autowired private UidProducer uidProducer; @RequestMapping("/reset") public void reset(){ allCount.set(0); successCount.set(0); failCount.set(0); } @GetMapping("/demo") public String demo(){ log.debug("/demo"); String reslut = null; long startTime = System.currentTimeMillis(); reslut = demoService.setName(13546L); long endTime = System.currentTimeMillis(); if(reslut != null){ allCount.incrementAndGet(); successCount.incrementAndGet(); } else { allCount.incrementAndGet(); } //log.debug(reslut); int fail = allCount.get() - successCount.get(); double percent = (successCount.get()*1.0*100/allCount.get()); reslut = "allCount=" + allCount + "," + " successCount=" + successCount + "," + " failCount=" + (fail) + ", " + String.format("%.2f",percent)+"%" + " time = "+ (endTime-startTime); log.debug("DemoController reslut = " + reslut); return reslut; } @GetMapping("/uid") public String demo1(){ long zkCount = uidProducer.getUid(); long customCount = uidProducer.getUid(); return "zkCount: " + zkCount + " " + "customCount : " + customCount; } public static void main(String args[]){ System.out.println( System.getProperty("os.name")); } } /* class UserSemo implements UserService{ @Override public String queryName(Long id) { return null; } @Override public String queryName(String name, Long id) { return null; } }*/ <file_sep>package com.nz.rpc.proxy; public interface Demo3 { void func(); } <file_sep>package app.provider.service.config; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.web.context.WebServerInitializedEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; import java.net.InetAddress; @Slf4j @Component public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> { @Override public void onApplicationEvent(WebServerInitializedEvent webServerInitializedEvent) { InetAddress host = null; try{ host = InetAddress.getLocalHost(); log.info(host.getHostAddress()); } catch(Exception ex){ log.error(ex.getMessage()); } log.info(host.getHostAddress() + " : " + webServerInitializedEvent.getWebServer().getPort()); } } <file_sep>rm -rf ~/.m2/repository/com/nz<file_sep>package com.nz.rpc.serialization; public class SerializationCreate { public static AbstractSerialize create(String type){ switch (type){ case "fastjson": return new FastjsonSerializeUtil(); case "jdk": return new JdkSerializeUtil(); case "hessian": return new HessianSerializeUtil(); default: return new HessianSerializeUtil() ; } } } <file_sep>package com.nz.rpc.discover; import com.alibaba.fastjson.JSON; import com.nz.rpc.netty.NettyContext; import com.nz.rpc.zk.ZkCreateConfig; import com.nz.rpc.zk.ZookeeperPath; import lombok.extern.slf4j.Slf4j; import org.apache.zookeeper.CreateMode; import org.springframework.beans.BeansException; import java.lang.reflect.Method; /** *功能描述 * @author lgj * @Description 注册服务服务提供者信息 * @date 4/13/19 */ @Slf4j public class ZookeeperServiceRegister extends AbstractServiceDiscover { public ZookeeperServiceRegister() { addShutdownHook(); } @Override public void queryService() { throw new UnsupportedOperationException(); } /** *功能描述 * @author lgj * @Description 向zookeeper注册被 {@link com.nz.rpc.anno.RpcService}注解的类 * @date 3/27/19 * @param: * @return: *  */ @Override public void registerService() throws BeansException { if(log.isDebugEnabled()){ log.debug("ServiceRegistry setApplicationContext.."); } this.providerDiscover(); if(NettyContext.getLocalServiceImplMap() != null){ NettyContext.getLocalServiceImplMap().forEach((interfaceName,implNames)->{ if(log.isDebugEnabled()){ log.debug("注册接口 {}", interfaceName); } implNames.forEach((implName)->{ registerConfig1(interfaceName,implName); }); }); } } /** * 功能描述 * * @author lgj * @Description 注册服务应用信息 * @date 1/26/19 * @param: * @return: */ private void registerConfig1(String interfaceName,String implName) { String regPath = getPath(interfaceName); regPath = regPath + "/" + properties.getNhost()+":"+properties.getNport(); try { //获取注册信息 ProviderConfig config = new ProviderConfig(); config.setHost(properties.getNhost()); config.setPort(properties.getNport()); config.setApplication(context.getId()); config.setImplName(implName); config.setInterfaceName(interfaceName); Class clz = Class.forName(interfaceName); Method[] methods = clz.getDeclaredMethods(); String[] methodNames = new String[methods.length]; for (int i = 0; i < methods.length; i++) { methodNames[i] = methods[i].getName(); } config.setMethods(methodNames); String configStr = JSON.toJSONString(config); if(log.isDebugEnabled()){ log.debug("configStr = {}",configStr); } ZkCreateConfig zkCreateConfig = ZkCreateConfig .builder() .path(regPath + "/" + configStr) .createMode(CreateMode.EPHEMERAL) .build(); zkCli.createPath(zkCreateConfig); } catch (Exception ex) { if(log.isErrorEnabled()){ log.error("注册服务失败 {}",ex); } } } private String getPath(String serviceClass) { return ZookeeperPath.rootPath + "/" + serviceClass + ZookeeperPath.providersPath; } /** *功能描述 * @author lgj * @Description 添加应用关闭时的回调函数,用于删除zk节点 * @date 7/14/19 * @param: * @return: * */ private void addShutdownHook(){ Runtime.getRuntime().addShutdownHook(new Thread(){ @Override public void run() { NettyContext.getLocalServiceImplMap().forEach((interfaceName,implNames)->{ String deletePath = getPath(interfaceName); deletePath = deletePath + "/" + properties.getNhost()+":"+properties.getNport(); if(zkCli.checkExists(deletePath)){ if(log.isDebugEnabled()){ log.debug("deletePath[{}] exists",deletePath); } zkCli.deleteNodeAndChildren(deletePath); return; } if(log.isWarnEnabled()){ log.warn("deletePath[{}] not exists",deletePath); } }); } }); } } <file_sep>package com.nz.rpc.serialization; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class JdkSerializeUtil extends AbstractSerialize { public <T> byte[] serialize(T obj) throws Exception{ if (obj == null){ throw new NullPointerException(); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(obj); return bos.toByteArray(); } catch (Exception ex) { ex.printStackTrace(); } return new byte[0]; } public <T> T deserialize(byte[] data, Class<T> clazz) throws Exception { ByteArrayInputStream bis = new ByteArrayInputStream(data); try { ObjectInputStream ois = new ObjectInputStream(bis); T obj = (T)ois.readObject(); return obj; } catch (Exception ex) { ex.printStackTrace(); } return null; } } <file_sep>package com.nz.rpc.msg; import com.nz.rpc.executor.TraceExecutorService; import com.nz.rpc.netty.NettyContext; import com.nz.rpc.netty.message.Header; import com.nz.rpc.netty.message.MessageType; import com.nz.rpc.netty.message.NettyMessage; import com.nz.rpc.time.TimeUtil; import io.netty.channel.ChannelHandlerContext; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.Method; import java.util.concurrent.*; /** *功能描述 * @author lgj * @Description RPC请求消息处理 * @date 5/7/19 */ @Slf4j public class ServerMessageHandler { private static ServerMessageHandler serverMessageHandler = new ServerMessageHandler(); //处理线程池定义 private static ThreadPoolExecutor executorService = new TraceExecutorService(10,10, 1000, TimeUnit.MICROSECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy()); private ServerMessageHandler(){ } public static ServerMessageHandler getInstance(){ return serverMessageHandler; } /** *功能描述 * @author lgj * @Description 提交任务到线程池 * @date 7/12/19 * @param: * * @return: * * */ public void submit(ChannelHandlerContext ctx,RpcRequest request){ Future<?> future = executorService.submit(new RequestHandler(ctx,request)); //log.debug("executorService = {}",executorService.toString()); } /** *功能描述 * @author lgj * @Description 线程池任务类 * @date 7/12/19 */ class RequestHandler implements Runnable{ private ChannelHandlerContext ctx; private RpcRequest request; public RequestHandler(ChannelHandlerContext ctx, RpcRequest request) { this.ctx = ctx; this.request = request; } @Override public void run() { NettyMessage nettyMessage = null; try{ Object result = doInvoke(request); nettyMessage = buildNettyMessage(result,null); } catch(Exception ex){ log.error(ex.getMessage()); nettyMessage = buildNettyMessage(null,ex); } ctx.writeAndFlush(nettyMessage); TimeUtil.endAndPrint("RequestHandler-run",request.getRequestId()); } /** *功能描述 * @author lgj * @Description 构建消息 * @date 5/7/19 * @param:  result: 方法调用结果  ex:方法调用异常 * @return:  NettyMessage * */ private NettyMessage buildNettyMessage(Object result,Exception ex){ NettyMessage nettyMessage = new NettyMessage(); Header header = new Header(); header.setType(MessageType.APP_RESPONE_TYPE.getValue()); nettyMessage.setHeader(header); RpcResponse response = new RpcResponse(); response.setResponseId(request.getRequestId()); response.setResult(result); response.setException(ex); nettyMessage.setBody(response); return nettyMessage; } /** *功能描述 * @author lgj * @Description 执行反射调用 * @date 5/7/19 * @param: * @return: * */ private Object doInvoke(RpcRequest request) throws Exception{ log.debug("request = " + request); String clzImplName = NettyContext.getLocalServiceImpl(request.getInterfaceName()); Class clzImpl = Class.forName(clzImplName); Object bean = clzImpl.newInstance(); Class[] paramTypes = new Class[request.getParameterTypes().length]; for(int i = 0; i< request.getParameterTypes().length ; i++){ paramTypes[i] = Class.forName(request.getParameterTypes()[i]); } Method method = clzImpl.getDeclaredMethod(request.getMethodName(),paramTypes); Object result = method.invoke(bean,request.getParameters()); //异步调用处理 //判断返回值是否是CompletableFuture类型 if(CompletableFuture.class.isAssignableFrom(result.getClass())){ //异步调用 result = ((CompletableFuture) result).get(); } if(log.isDebugEnabled()){ log.debug("method [{}] done !result = [{}]",method,result); } return result; } } } <file_sep>package com.nz.rpc.netty.message; public enum MessageType { //业务请求消息 APP_REQUEST_TYPE((byte)10), //业务响应消息 APP_RESPONE_TYPE((byte)11), //one way 消息,只发送消息,无需回复 ONE_WAY_TYPE((byte)12), //握手请求消息 HANDSHAKE_REQUEST_TYPE((byte)13), //握手应答消息 HANDSHAKE_RESPONSE_TYPE((byte)14), //心跳请求信息 HEARTBEAT_REQUEST_TYPE((byte)15), //心跳应答消息 HEARTBEAT_RESPONSE_TYPE((byte)16); private byte value; MessageType(byte value) { this.value = value; } public byte getValue() { return value; } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.nz.rpc</groupId> <artifactId>rpc-integration-spring-boot-starter</artifactId> <version>1.0.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/io.netty/netty-all --> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.34.Final</version> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.4</version> <scope>provided</scope> </dependency> <!--<dependency> <groupId>com.github.sgroschupf</groupId> <artifactId>zkclient</artifactId> <version>0.1</version> </dependency>--> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-recipes</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.6</version> <exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </exclusion> <exclusion> <groupId>log4j</groupId> <artifactId>log4j</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.esotericsoftware</groupId> <artifactId>kryo-shaded</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>org.reflections</groupId> <artifactId>reflections</artifactId> <version>0.9.9-RC2</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api --> <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>com.utils</groupId> <artifactId>serialization</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.javassist/javassist --> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.25.0-GA</version> <scope>compile</scope> <optional>true</optional> </dependency> <!-- https://mvnrepository.com/artifact/com.esotericsoftware.kryo/kryo --> <dependency> <groupId>com.esotericsoftware.kryo</groupId> <artifactId>kryo</artifactId> <version>2.24.0</version> </dependency> <!-- https://mvnrepository.com/artifact/redis.clients/jedis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.0.1</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.9</version> <scope>compile</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency> </dependencies> </project><file_sep>package com.nz.rpc.netty.client.properties; import lombok.Data; @Data public class NettyClientProperties { private int workerTheads = 4; } <file_sep>package com.nz.rpc.utils; public class MathUtil { /** *功能描述 * @author lgj * @Description 求取平均数 * @date 4/28/19 * @param: last_avg:上一次的平均值 *      next_val: 本次的值 * num: 到目前为止次数 * new_avg = ( (last_avg * (num-1)) + cur_val) / num *       * @return: * */ public static float calcAverage(float last_avg, float cur_val, long num) { float avg_val=0; if(num<=1) { avg_val=cur_val; } else { avg_val=(last_avg*(((float)num-1)/(float)num)+cur_val*(1/(float)num));/*必须强转float*/ } return avg_val; } } <file_sep>package com.nz.rpc.netty.server; import com.nz.rpc.netty.server.handler.ChildChannelHandler; import com.nz.rpc.properties.RpcProperties; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.util.concurrent.DefaultThreadFactory; import io.netty.util.concurrent.GenericFutureListener; import lombok.Data; import lombok.extern.slf4j.Slf4j; @Data @Slf4j public class NettyServer { //bossGroup接受传入的连接 EventLoopGroup bossGroup; //一旦bossGroup接受连接并注册到workerGroup,workerGroup则处理连接相关的流量 EventLoopGroup workerGroup; RpcProperties rpcProperties; public NettyServer(RpcProperties rpcProperties) { this.rpcProperties = rpcProperties; //bossGroup接受传入的连接 bossGroup = new NioEventLoopGroup(rpcProperties.getNettyServer().getBossTheads(), new DefaultThreadFactory("server1", true)); //一旦bossGroup接受连接并注册到workerGroup,workerGroup则处理连接相关的流量 workerGroup = new NioEventLoopGroup(rpcProperties.getNettyServer().getWorkerTheads(), new DefaultThreadFactory("server2", true)); shutdownHandler(); } public void bind(int port) { log.debug("Server bind to port[{}]",port); //reactor 主从模式 EventLoopGroup 线程池 //bossGroup 用于安全认证,登录,握手,一但3链路建立成功,就将链路注册到workerGroup线程上 //后续有其处理IO操作 try { ServerBootstrap serverBootstrap = new ServerBootstrap(); //用于设置服务端 serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) //.option(ChannelOption.TCP_NODELAY, false) //.option(ChannelOption.SO_SNDBUF,1024*1024) .option(ChannelOption.SO_RCVBUF,1024*1024) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.RCVBUF_ALLOCATOR,AdaptiveRecvByteBufAllocator.DEFAULT) .childHandler(new ChildChannelHandler()); //绑定端口,同步等待成功 log.debug("Binding the port[{}].....",port); ChannelFuture channelFuture = serverBootstrap.bind(port); Channel channel = channelFuture.channel(); channelFuture.addListener(new GenericFutureListener<ChannelFuture>(){ @Override public void operationComplete(ChannelFuture future) throws Exception { Channel channel = future.channel(); if(channel.isActive()){ log.debug("Binding the port:[{}] successs,channel state [{}]",port,channel.isActive()); } else { log.error("Binding the port:[{}]fail,The port had been bind to other applicatiocn]",port); System.exit(1); } } }); } catch (Exception ex) { log.error("Binding the port:[{}]fail,ex={}!",port,ex); System.exit(1); } finally { // log.info("shutdownGracefully...."); // bossGroup.shutdownGracefully(); // workerGroup.shutdownGracefully(); } } /* *功能描述 应用关闭处理 * @author lgj * @Description * @date 7/26/19 * @param: * @return: void * */ private void shutdownHandler(){ new Thread(){ @Override public void run() { Runtime.getRuntime().addShutdownHook(new Thread(){ @Override public void run() { log.info("系统Netty-Server正在关闭应用!"); bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }); } }.start(); } } <file_sep>package com.nz.rpc.interceptor.impl; import com.nz.rpc.interceptor.Interceptor; import com.nz.rpc.invocation.client.ClientInvocation; import com.nz.rpc.loadbalance.LoadbanlanceHandler; import lombok.extern.slf4j.Slf4j; /** *功能描述 * @author lgj * @Description 负载均衡责任链处理 * @date 5/6/19 */ @Slf4j public class ServiceSelectInterceptor implements Interceptor { private LoadbanlanceHandler loadbanlanceHandler; @Override public Object intercept(ClientInvocation invocation) throws Exception { log.debug("ServiceSelectInterceptor start ...."); //负载均衡选择Server loadbanlanceHandler.serviceSelect(invocation); Object result = invocation.executeNext(); return result; } public void setLoadbanlanceHandler(LoadbanlanceHandler loadbanlanceHandler) { this.loadbanlanceHandler = loadbanlanceHandler; } } <file_sep>package com.nz.rpc.netty.server.handler; import com.nz.rpc.msg.RpcRequest; import com.nz.rpc.msg.ServerMessageHandler; import com.nz.rpc.netty.message.MessageType; import com.nz.rpc.netty.message.NettyMessage; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import lombok.extern.slf4j.Slf4j; @Slf4j public class ServerChannelInboundHandler extends ChannelInboundHandlerAdapter { public ServerChannelInboundHandler() { super(); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); if(log.isInfoEnabled()){ log.info("与客户端[{}]建立连接",ctx.channel().remoteAddress()); } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); if(log.isInfoEnabled()){ log.info("与客户端[{}]断开连接",ctx.channel().remoteAddress()); } ctx.channel().close(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { /*if(log.isDebugEnabled()){ log.debug("ServerChannelInboundHandler channelRead ,remoteAddress[{}],",ctx.channel().remoteAddress()); log.debug("接收到客户端消息:"+msg); }*/ NettyMessage nettyMessage = (NettyMessage) msg; if((nettyMessage!=null) && (nettyMessage.getHeader().getType() == MessageType.APP_REQUEST_TYPE.getValue())){ RpcRequest rpcRequest = (RpcRequest)nettyMessage.getBody(); ServerMessageHandler.getInstance().submit(ctx,rpcRequest); } super.channelRead(ctx, msg); } } <file_sep>package com.nz.rpc.netty.server.handler; import com.nz.rpc.netty.coder.NettyMessageDecode; import com.nz.rpc.netty.coder.NettyMessageEncoder; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.timeout.IdleStateHandler; import java.util.concurrent.TimeUnit; /** *功能描述 * @author lgj * @Description 配置责任链 handler * @date 3/16/19 */ public class ChildChannelHandler extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { //CoderConfig.JdkCoder(socketChannel); ChannelPipeline pipeline = socketChannel.pipeline(); pipeline.addLast(new NettyMessageDecode(1024*1024,9, 4)); pipeline.addLast(new IdleStateHandler(75, 0, 0, TimeUnit.SECONDS)); pipeline.addLast(new HeartbeatResponseHandler()); pipeline.addLast(new NettyMessageEncoder()); pipeline.addLast(new ServerChannelInboundHandler()); // pipeline.addLast(new ServerChannelOutboundHandle()); } } <file_sep>package com.nz.rpc.interceptor.exception; public class AddInterceptorException extends Exception{ public AddInterceptorException(String message) { super(message); } public AddInterceptorException(String message, Throwable cause) { super(message, cause); } } <file_sep>package com.nz.rpc.loadbalance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** *功能描述 * @author lgj * @Description 负载均衡配置类 * @date 7/12/19 */ @Configuration public class LoadbalanceAutoConfig { @Autowired private ApplicationContext context; @Bean public LoadbanlanceHandler loadbanlanceHandler(){ LoadbanlanceHandler loadbanlanceHandler = new LoadbanlanceHandler(context); loadbanlanceHandler.scan(); return loadbanlanceHandler; } //轮询 @Bean LoadbalanceStrategy pollingLoadbalanceStrategy(){ LoadbalanceStrategy loadbalanceStrategy = new PollingLoadbalanceStrategy(); return loadbalanceStrategy; } //加权轮询 @Bean LoadbalanceStrategy weightPollingLoadbalanceStrategy(){ LoadbalanceStrategy loadbalanceStrategy = new WeightPollingLoadbalanceStrategy(); return loadbalanceStrategy; } //随机 @Bean LoadbalanceStrategy randomLoadbalanceStrategy(){ LoadbalanceStrategy loadbalanceStrategy = new RandomLoadbalanceStrategy(); return loadbalanceStrategy; } //加权随机 @Bean LoadbalanceStrategy weightRandomLoadbalanceStrategy(){ LoadbalanceStrategy loadbalanceStrategy = new WeightRandomLoadbalanceStrategy(); return loadbalanceStrategy; } //一致性hash @Bean LoadbalanceStrategy uniformityHashLoadbalanceStrategy(){ LoadbalanceStrategy loadbalanceStrategy = new UniformityHashLoadbalanceStrategy(); return loadbalanceStrategy; } } <file_sep>package com.nz.rpc.cluster; import com.nz.rpc.invocation.client.ClientInvocation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ApplicationContext; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @Slf4j public class ClusterFaultHandler { private ApplicationContext context; private Class defaultClusterFaultType = FailfastClusterFault.class; private Map<String,Class<? extends ClusterFault>> clusterMap = new ConcurrentHashMap<>(); /** *功能描述 * @author lgj * @Description 扫描集群容错的配置 * @date 7/12/19 * @param: * @return: * */ public void scan(){ DefaultListableBeanFactory listableBeanFactory = (DefaultListableBeanFactory) context.getAutowireCapableBeanFactory(); Map<String,AbstractClusterFaultConfig> clusterFaultConfigMap = listableBeanFactory.getBeansOfType(AbstractClusterFaultConfig.class); clusterFaultConfigMap.forEach((name,configs)->{ Map<String,Class<? extends ClusterFault>> clusterFaultToleranceMap = configs.config(); clusterFaultToleranceMap.forEach((serviceName,clusterFaultClass)->{ clusterMap.put(serviceName,clusterFaultClass); }); }); log.debug("clusterMap = " +clusterMap); } /** *功能描述 * @author lgj * @Description 根据接口名称获取集群容错实现类 * @date 7/12/19 * @param: * @return: * */ private ClusterFault getClusterFault(String serviceName){ Class clusterFaultType = clusterMap.get(serviceName); if(clusterFaultType == null){ clusterFaultType = defaultClusterFaultType; } ClusterFault clusterFault = (ClusterFault)context.getBean(clusterFaultType); return clusterFault; } /** *功能描述 * @author lgj * @Description 集群容错处理 * @date 7/12/19 * @param: * @return: * */ public Object handle(ClientInvocation invocation,Exception ex) throws Exception{ //获取接口对应的容错处理对象 ClusterFault clusterFault = getClusterFault(invocation.getMethod().getDeclaringClass().getName()); Object result = clusterFault.handle(invocation,ex); return result; } public void setContext(ApplicationContext context) { this.context = context; } } <file_sep>package com.nz.rpc.loadbalance; import com.nz.rpc.discover.ProviderConfig; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; public class LoadbalanceStrategyTest { @Test public void loadbalace()throws Exception{ if(false){ System.out.println("随机负载均衡...."); LoadbalanceStrategy strategy1 = new RandomLoadbalanceStrategy(); loadbalace(strategy1,10,1000); } if(false){ System.out.println("加权随机负载均衡...."); LoadbalanceStrategy strategy2 = new WeightRandomLoadbalanceStrategy(); loadbalace(strategy2,10,1000); } if(false){ System.out.println("\r\n轮询负载均衡....."); LoadbalanceStrategy strategy3 = new PollingLoadbalanceStrategy(); loadbalace(strategy3,10,1000); } if(false){ System.out.println("\r\n加权轮询负载均衡....."); LoadbalanceStrategy strategy4 = new WeightPollingLoadbalanceStrategy(); loadbalace(strategy4,10,1000); } if(false){ System.out.println("\r\n最小时延负载均衡....."); LoadbalanceStrategy strategy5 = new LeastActiveLoadbalanceStrategy(); leastActiveLoadbalance(strategy5,10); } if(true){ System.out.println("\r\n一致性hash负载均衡....."); uniformityHashLoadbalanceStrategyTest(new UniformityHashLoadbalanceStrategy(),10); } } public void uniformityHashLoadbalanceStrategyTest(LoadbalanceStrategy strategy ,int configNum) throws Exception{ List<ProviderConfig> configs = new ArrayList<>(); for(int i = 0; i< configNum; i++){ ProviderConfig config = new ProviderConfig(); config.setInterfaceName("com.serviceImpl"); config.setHost("127.0.0.1"); config.setPort(new Random().nextInt(9999)); config.setWeight(i); config.setCallTime(new Random().nextInt(100)); configs.add(config); } ProviderConfig config = strategy.select(configs,"127.0.0.1:0234"); System.out.println("选择结果:" + config.getHost() + ":" + config.getPort()); } public void hashTest(int count){ int[] result = new int[count]; for(int i = 0; i< count; i++){ String str = "127.0.0.1"+":"+ new Random().nextInt(9999); result[i] = caculHash(str); } Arrays.sort(result); for(int i = 0; i< count; i++){ System.out.println(result[i]); } System.out.println(); System.out.println(Integer.MAX_VALUE); } private int caculHash(String str){ int hashCode = str.hashCode(); hashCode = (hashCode<0)?(-hashCode):hashCode; return hashCode; } private int getHash(String str) { final int p = 16777619; int hash = (int)2166136261L; for (int i = 0; i < str.length(); i++) hash = (hash ^ str.charAt(i)) * p; hash += hash << 13; hash ^= hash >> 7; hash += hash << 3; hash ^= hash >> 17; hash += hash << 5; // 如果算出来的值为负数则取其绝对值 if (hash < 0) hash = Math.abs(hash); return hash; } public void loadbalace(LoadbalanceStrategy strategy ,int configNum,int testCount )throws Exception{ List<ProviderConfig> configs = new ArrayList<>(); int[] counts = new int[configNum]; for(int i = 0; i< configNum; i++){ ProviderConfig config = new ProviderConfig(); config.setInterfaceName("com.serviceImpl"); config.setHost("127.0.0.1"); config.setPort(i); config.setWeight(new Random().nextInt(100)); configs.add(config); } //System.out.println(configs); for(int i = 0; i< testCount ; i++){ ProviderConfig config = strategy.select(configs,null); // System.out.println("选中的:"+config); Integer count = counts[config.getPort()]; counts[config.getPort()] = ++count; } for(int i = 0; i< configNum; i++){ System.out.println("序号:" + i + " 权重:" + configs.get(i).getWeight() + "--次数:" + counts[i]); } } public void leastActiveLoadbalance(LoadbalanceStrategy strategy ,int configNum)throws Exception{ List<ProviderConfig> configs = new ArrayList<>(); for(int i = 0; i< configNum; i++){ ProviderConfig config = new ProviderConfig(); config.setInterfaceName("com.serviceImpl"); config.setHost("127.0.0.1"); config.setPort(i); config.setWeight(i); config.setCallTime(new Random().nextInt(100)); configs.add(config); } for(ProviderConfig c:configs){ System.out.println("序号:" + c.getPort() +"--时延:" + c.getCallTime() ); } System.out.println("--------------"); ProviderConfig config = strategy.select(configs,null); System.out.println("最终选择 序号:" + config.getPort() +"--时延:" + config.getCallTime() ); } }<file_sep>package com.nz.rpc.zk; /** *功能描述 * @author lgj * @Description /nzRpc/className/providers * @date 3/28/19 */ public class ZookeeperPath { public static final String separator = "/"; public static final String rootPath = "/nzRpc"; public static final String providersPath = "/providers"; } <file_sep>package com.nz.rpc.invocation.client; import com.nz.rpc.interceptor.Interceptor; import com.nz.rpc.interceptor.InterceptorChain; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Test; import java.lang.reflect.Method; import java.util.List; @Slf4j public class RpcClientInvocationTest { InterceptorChain interceptorChain; @Before public void before(){ interceptorChain = new InterceptorChain(); } @Test public void executeNext() { Class clz = Demo.class; RpcClientInvocation invocation = null; try{ Method method = clz.getMethod("func",String.class); Object[] args = new String[1]; args[0] = "libai"; interceptorChain.addFirst("time",new TimeInterceptor()); interceptorChain.addBefore("time","log",new LogInterceptor()); interceptorChain.addLast("request",new RpcRequestInterceptor()); List<Interceptor> interceptors = interceptorChain.getInterceptor(); System.out.println("interceptors = " + interceptors); invocation = new RpcClientInvocation(method,args,interceptors); Object result = invocation.executeNext(); log.info("result = " + result); } catch(Exception ex){ log.error(ex.getMessage()); } } } class Demo{ public String func(String name){ return name; } }<file_sep>package com.nz.rpc.proxy; import javassist.util.proxy.MethodHandler; import javassist.util.proxy.ProxyFactory; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.Method; /** *功能描述 * @author lgj * @Description javassit  存在问题,无法代理接口!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * @date 4/14/19 */ @Slf4j public class JavassitProxyCreate implements ProxyCreate { private RpcInvoker rpcInvoker; public <T> T createInstance(Class<T> interfaceClass){ return getProxy(interfaceClass); } public <T> T getProxy(Class<T> interfaceClass){ ProxyFactory proxyFactory = new ProxyFactory(); if(interfaceClass.isInterface()){ Class[] clz = new Class[1]; clz[0] = interfaceClass; proxyFactory.setInterfaces(clz); } else { proxyFactory.setSuperclass(interfaceClass); } proxyFactory.setHandler(new MethodHandler() { public Object invoke(Object proxy, Method method, Method method1, Object[] args) throws Throwable { //method 被代理类的方法 //method1代理类的方法 使用这个方法 Object result = (T)rpcInvoker.invoke(proxy,method1,args); return result; } }); try{ T bean = (T)proxyFactory.createClass().newInstance(); return bean; } catch(Exception ex){ log.error("Javassit 创建代理失败:{}",ex.getMessage()); return null; } } @Override public ProxyCreate invoker(RpcInvoker invoker) { this.rpcInvoker = invoker; return this; } public static void main(String args[]){ JavassitProxyCreate create = new JavassitProxyCreate(); Demo3 de = create.createInstance(Demo3.class); de.func(); } interface Demo{ void func(); } class Demo1{ void func(){} } }<file_sep>package com.nz.rpc.lock.zk; import com.nz.rpc.zk.ZkCreateConfig; import lombok.extern.slf4j.Slf4j; import org.apache.zookeeper.CreateMode; import org.junit.Test; @Slf4j public class ZkClientTest { @Test public void zkcli(){ ZkClient zkClient = ZkClientFatory.zkClient(); ZkCreateConfig config = ZkCreateConfig.builder() .createMode(CreateMode.EPHEMERAL) .path("/node/demo2") .build(); String result = zkClient.createPath(config); log.info("创建结果:{}",result); } }<file_sep>package app.provider.service.impl; import com.app.common.service.DemoService; import com.nz.rpc.anno.RpcService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.Date; import java.util.Random; @Slf4j @RpcService @Service public class DemoServiceImpl implements DemoService { public String setName(Long id){ return "DemoServiceImpl setName :" +id + ":"+ new Date().toString()+ " " + new Random().nextInt(1000); } public String setName(String name, Long id){ try{ Thread.sleep(3000); } catch(Exception ex){ log.error(ex.getMessage()); } return "DemoServiceImpl queryName :" + name +":" +id + new Date().toString() + " " + new Random().nextInt(1000); } } <file_sep>package com.nz.rpc.netty.exception; public class RpcRequestException extends Exception{ } <file_sep>package com.nz.rpc.netty; import com.nz.rpc.netty.client.NettyClient; import com.nz.rpc.netty.exception.RpcResponseException; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; public class NettyContext { //netty操作客户端 private static NettyClient nettyClient; //存放接口名称对应的实现类名称 key:接口名称,value:实现类名称 private static Map<String,List<String>> localServiceImplMap = new ConcurrentHashMap<>(); public static NettyClient getNettyClient() { return nettyClient; } public static void setNettyClient(NettyClient nettyClient) { NettyContext.nettyClient = nettyClient; } public static Map<String, List<String>> getLocalServiceImplMap() { return localServiceImplMap; } /** *功能描述 * @author lgj * @Description 通过接口名称获取实现类 * @date 7/13/19 * @param: * @return: * */ public static String getLocalServiceImpl(String interfaceName)throws Exception{ List<String> serviceImplLists = NettyContext.getLocalServiceImplMap().get(interfaceName); if (serviceImplLists!= null){ //随机获取实现类 return serviceImplLists.get(new Random().nextInt(serviceImplLists.size())); } throw new RpcResponseException("The interface[{}] can not find its implementation class"); } public static void setLocalServiceImplMap(Map<String, List<String>> localServiceImplMap) { NettyContext.localServiceImplMap = localServiceImplMap; } } <file_sep>package com.nz.rpc.lock.exception; public class RequestLockException extends Exception { public RequestLockException(String message) { super(message); } public RequestLockException(String message, Throwable cause) { super(message, cause); } }
74bc3343643c4ffc6664fe1e48bbb239795fd00c
[ "Markdown", "Java", "Maven POM", "Shell" ]
79
Java
wangzaidali/nz-rpc
0007a124cc5ed2b9347f4224ac5260b39110e7fd
7b82e0cae4e3fb99e6324da52a85539d2a43c4b9
refs/heads/master
<file_sep>const express = require("express"); const app = express(); const mongoose = require("mongoose"); const path = require("path"); const _ = require("lodash"); const bodyParser = require("body-parser"); mongoose.connect("mongodb://localhost:27017/todolistDB",{useNewUrlParser: true, useUnifiedTopology: true }); //Include body parser to read requests app.use(bodyParser.urlencoded({extended: true})); app.use(express.static(path.join(__dirname, "public"))); // Use EJS app.set('view engine', 'ejs'); //////////////////////////Main//////////////////////////////////// const wishSchema = { name: String }; const Wish = mongoose.model('wish',wishSchema); const List = mongoose.model("list", { name: String, wishes: [wishSchema] }); // Wish.insertMany([wish1,wish2,wish3], function(err) { // if(err) { // console.log(err); // } else { // console.log("All wishes created!"); // } // }); app.get("/", function(req, res) { const customListName = _.capitalize(req.params.customListName); Wish.find({},{_id:1, name:1},function(err, wishes) { if(err){ console.log(err); } else { res.render("bucket-list",{listName : "Today", wishList : wishes}); } }); }); app.post("/", function(req, res) { const customListName = _.capitalize(req.body.button); const wishObject = new Wish({name: req.body.wish}); if(customListName === "Today") { wishObject.save(); res.redirect("/"); } else { List.findOne({name: customListName}, function(err, wishList) { wishList.wishes.push(wishObject); wishList.save(); res.redirect("/" + customListName); }); } }); app.get("/:customListName", function(req, res) { const customListName = _.capitalize(req.params.customListName); List.findOne({name: customListName},{_id: 0, wishes: 1},function(err, wishLists) { if(err){ console.log(err); } else { if(wishLists == null) { wishLists = []; const list = new List({name: customListName, wishes: []}); list.save(); res.render("bucket-list",{listName : customListName, wishList : []}) } res.render("bucket-list",{listName : customListName, wishList : wishLists.wishes}); } }); }); app.post("/delete/:id/:listName", function(req, res) { const listName = _.capitalize(req.params.listName); const deleteWish = req.params.id; if(listName === "Today") { Wish.deleteOne({_id: deleteWish},function(err) { res.redirect("/"); }); } else { const list = List.findOne({name: listName}, function(err, wishes) { wishes["wishes"].forEach(function(wish,index) { if(deleteWish == wish["_id"]) { wishes.wishes.splice(index, 1); wishes.save(); res.redirect("/" + listName); } }); }); } }); //About app.get("/about",function(req, res) { res.render("about"); }); // Enable Port app.listen(3000, function() { console.log("Server listening on port 3000"); }); <file_sep># mybucketlist ##It allows user to create their bucket list. ### Launch: https://shielded-plateau-11674.herokuapp.com/
f4e03f95ce84b43487cbc00c13138d1e86e08022
[ "JavaScript", "Markdown" ]
2
JavaScript
singla-s/mybucketlist
32e4a294e6073e6018707f99eabfb0a2161ca3a5
4b4f634df9189744b6d67969efcf45ba875b7dc2
refs/heads/master
<repo_name>josephmathewp/ProgrammingAssignment2<file_sep>/cachematrix.R ## Function to cache matrix inversion ## TESTING ## Create an object to store a matrix ## cacheableMatrix <- makeCacheMatrix(rbind(c(10,20), c(30,40))) ## Make a call to cacheSolve to find the inverse of the matrix ## inverse1 <- cacheSolve(cacheableMatrix) ## Make the cacheSolve call again to to calculate the inverse of the matrix ## inverse2 <- cacheSolve(cacheableMatrix) ## this time the cached value from the previous call will be returned ## The following function makeCacheMatrix provide an interface to cache a matrix ## and access the cached inverse value makeCacheMatrix <- function(x = matrix()) { cachedinverse <- NULL # set the value of the matrix set <- function(y) { x <<- y cachedinverse <<- NULL } # get the value of the matrix get <- function() x # set the value of the inverse of the matrix setCacheInverse <- function(inverse) cachedinverse <<- inverse # get the value of the inverse of the matrix getCacheInverse <- function() cachedinverse list(set = set, get = get, setCacheInverse = setCacheInverse, getCacheInverse = getCacheInverse) } ## This function cacheSolve returns the inverse of the matrix after ## checking the cache to see if it has already been calculated and cached. ## If inverse is already been calculated it returns the cached value ## otherwise it will calculate the inverse, cache it and returns the value cacheSolve <- function(x, ...) { ## get the value of the inverse that is already been stored in the cache invValue <- x$getCacheInverse() ## check to see whether the inverse is already been calculated ## if it is not present in cache invValue will be NULL if(!is.null(invValue)) { message("getting cached data") # return cached inverse value of the matrix x return(invValue) } ## get the value of the matrix data <- x$get() ## calculate the inverse invValue <- solve(data, ...) ## store inverse in the cache x$setCacheInverse(invValue) ## return the matrix that is the inverse of the matrix x invValue }
c92b59e9f16c55a955263219b64f10792e6d7985
[ "R" ]
1
R
josephmathewp/ProgrammingAssignment2
75861da59c92c75f389fb52c6d37960985fe525d
8f60351872b64cbe505b0506cc119d3198d3ed7a
refs/heads/main
<repo_name>KoshiroSato/Rust_practice<file_sep>/smartcore-sample/Cargo.toml [package] name = "smartcore-sample" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] smartcore = { version = "0.2.0", default-features = false, features=["nalgebra-bindings", "ndarray-bindings", "datasets"]} rand = "0.3.0"<file_sep>/smartcore-sample/src/main.rs use smartcore::dataset::iris; use smartcore::linalg::naive::dense_matrix::DenseMatrix; use smartcore::tree::decision_tree_classifier::DecisionTreeClassifier; use smartcore::model_selection::train_test_split; use smartcore::metrics::accuracy; fn main() { let iris_data = iris::load_dataset(); let x = DenseMatrix::from_array( iris_data.num_samples, iris_data.num_features, &iris_data.data, ); let y = iris_data.target; let (x_train, x_test, y_train, y_test) = train_test_split(&x, &y, 0.2, true); let model = DecisionTreeClassifier::fit( &x_train, &y_train, Default::default(), ).unwrap(); let pred_1 = model.predict(&x_test).unwrap(); println!("{}", accuracy(&y_test, &pred_1)); }<file_sep>/Docker/Dockerfile FROM rust:latest RUN apt-get update -y && apt-get upgrade -y &&\ apt-get install curl vim git -y &&\ apt-get autoremove -y &&\ apt-get clean &&\ rm -rf /usr/local/src/*
2c0115f91838fb4106dd0f0f337ed7fd12bdc8d2
[ "TOML", "Rust", "Dockerfile" ]
3
TOML
KoshiroSato/Rust_practice
3e51e9c0e4dc2b7f137aa5c5e1a8a4f4ab7f9e3e
dba9d13314e434e3d4e3e22d79f7dadd6db7bae9
refs/heads/master
<file_sep>import React, { Component } from 'react' import DevTools from './DevTools' export default class App extends Component { render() { return ( <div> <p className='test' color='blue'>Hello world</p> { process.env.NODE_ENV !== 'production' && <DevTools /> } </div> ) } }<file_sep># react-boilerplate A minimal react/redux boilerplate with hot reloading and redux devtools
17d4081c547fd94eb0d4557c1ce38015d52b4538
[ "JavaScript", "Markdown" ]
2
JavaScript
quinnstinchurchill/react-boilerplate
4481d7019a8be5c6bca0012f3955fd7d92bda6d3
5142879f57b6d11851363e413597a64ae25c21dc
refs/heads/master
<repo_name>Preetam078/TextUtils-<file_sep>/src/components/TextForm.js import { useState } from "react" import React from 'react' function TextForm(props) { const HandleOnChange = (event) =>{ setText(event.target.value); } const HandleOnClick = () =>{ let newText = text.toUpperCase(); setText(newText); props.Alert("Converted to UpperCase","success") } const HandleOnClick2 = () =>{ let newText = text.toLowerCase(); setText(newText); props.Alert("Converted to LowerCase","success") } const HandleClear = () => { setText(''); props.Alert("Your text is cleared","success") } const HandleOnClick3 = () => { if(bold === false){ setBold(true); } else{ setBold(false); } } const [bold, setBold] = useState(false); const [text, setText] = useState("Please Enter your Text") return ( <> <div> <div> <br></br> <div className={`container text-${props.mode === 'dark'?'light':'dark'}`}> <h1 className="my-7">{props.title}</h1> <div className="mb-3"> <textarea className={`form-control text-${props.mode === 'dark'?'light':'dark'}`} value={text} onChange={HandleOnChange} style={{ backgroundColor: props.mode === 'dark'?'#354038':'white', fontWeight : bold === true?'bold':'normal'}} id="boxText" rows="8" ></textarea> </div> <button className="btn btn-success mx-2" onClick={HandleOnClick}>Convert Upper Case</button> <button className="btn btn-success mx-2" onClick={HandleOnClick2}>Convert Lower Case</button> <button className="btn btn-success mx-2" onClick={HandleOnClick3}>Make Bold Letter</button> <button className="btn btn-success mx-2" onClick={HandleClear}>Clear Text</button> </div> </div> <div className={`container text-${props.mode === 'dark'?'light':'dark'}`}> <h3 className="my-3">Text Summary</h3> <p>{text.split(" ").length} <strong>words</strong> and {text.length} <strong>characters</strong></p> <p>{0.008 * text.split(" ").length} <strong>Minutes</strong> to read the text</p> <div className="my-3"> <h2>Preview</h2> <p>{text.length <= 0 ?"Please enter something in the text to preview":text}</p> </div> </div> </div> </> ) } export default TextForm
c679da302fc5fc2efcd151a524d3dbd51b02a5dc
[ "JavaScript" ]
1
JavaScript
Preetam078/TextUtils-
095f8e8d383ea4b6ec490f5620aaf256d8dab728
3397f3c30c3e4c05a89c76928c1fb0cbbf0c7828
refs/heads/master
<file_sep>(function(){ "use strict"; function createTask(target) { var modal_box = document.getElementsByClassName("modal_box")[0]; modal_box.style.display = "block"; target.setAttribute("disabled","true"); } function closeTask() { var modal_box = document.getElementsByClassName("modal_box")[0], create_task = document.getElementById("create_task"); modal_box.style.display = "none"; create_task.removeAttribute("disabled"); } function handleClick(e) { e.preventDefault(); var targetEl = e.target.id || e.target.className; if(targetEl === "create_task"){ createTask(e.target); } else if(targetEl === "close_btn") { closeTask(); } } function eventListeners() { document.addEventListener("click",handleClick); } eventListeners(); })();
da53bc21134559f8ddaac1d89c8302dc0fa5f7fa
[ "JavaScript" ]
1
JavaScript
franco21191/TaskCreator
72a9d2c027e8ebd3feb92881d4e098fcf7578731
6cf8e6eb4e92aa54e72e77ca865c24767bbc74f3
refs/heads/master
<repo_name>delftdata/flink-test-scripts<file_sep>/distributed-producer.sh #!/bin/bash duration_seconds=$1 throughput=$2 kafka=$3 topic=$4 shift 4 ips=( "$@" ) size=${#ips[@]} num_prod_per_ip=2 num_prod_tot=$(( $num_prod_per_ip * $size )) #size=$(echo "$size + 1" | bc) throughput_per_prod=$(echo "$throughput / $num_prod_tot" | bc) num_records_per_prod=$(echo "$throughput_per_prod * $duration_seconds" | bc) echo "Num Producers: $num_prod_tot" echo "Requested throughput: $throughput" echo "Throughput per prod: $throughput_per_prod" echo "Num records per prod: $num_records_per_prod" prodindex=0 for ip in ${ips[@]} ; do for i in $(seq $num_prod_per_ip) ; do ssh -o StrictHostKeyChecking=no ubuntu@$ip "timeout $duration_seconds /home/ubuntu/kafka/bin/kafka-producer-perf-test.sh --dist-producer-index $prodindex --dist-producer-total $num_prod_tot --topic $topic --num-records $num_records_per_prod --throughput $throughput_per_prod --producer-props bootstrap.servers=$kafka key.serializer=org.apache.kafka.common.serialization.StringSerializer value.serializer=org.apache.kafka.common.serialization.StringSerializer | grep -v 'records sent'" & prodindex=$((prodindex+1)) done done <file_sep>/old/auto-test-run.sh #!/bin/bash i=1 parentdir=.. while true do echo "== Auto test run no $i. ==" echo "" ./cluster.sh start 4 sleep 2 echo "" #echo "Starting job WindowJoin parallel=2." #echo "Starting job StateMachine parallel=2." echo "Starting job TopSpeedWindowing parallel=2." #echo "Starting job IncrementalLearning parallel=2." # WindowJoin #nohup $dir/flink/build-target/bin/flink run -p 2 $dir/flink/build-target/examples/streaming/WindowJoin.jar --windowSize 10000 --rate 100 >$dir/flink-job.out 2>$dir/flink-job.err & # StateMachine #nohup $dir/flink/build-target/bin/flink run -p 2 $dir/flink/build-target/examples/streaming/StateMachineExample.jar --error-rate 0.2 --sleep 100 >$dir/flink-job.out 2>$dir/flink-job.err & # TopSpeedWindowing nohup $parentdir/flink/build-target/bin/flink run -p 2 $parentdir/flink/build-target/examples/streaming/TopSpeedWindowing.jar >$parentdir/flink-job.out 2>$parentdir/flink-job.err & # IncrementalLearning #nohup $dir/flink/build-target/bin/flink run -p 2 $dir/flink/build-target/examples/streaming/IncrementalLearning.jar >$dir/flink-job.out 2>$dir/flink-job.err & sleep 2 jobid=`$parentdir/flink/build-target/bin/flink list | grep -E -o ": ([a-z0-9]+) :" | grep -E -o "([a-z0-9]+)"` echo "Job's job id is $jobid." echo "" echo "==========" echo "Find and kill taskmanager producing output." ./find-kill-taskmanager.sh exitstatus=$? echo "Find and kill taskmanager command returned $exitstatus." echo "" echo "==========" echo "Present output of alive taskmanagers." ./present-output-taskmanager.sh echo "" echo "==========" echo "Present failed tasks." ./present-failed-tasks.sh echo "" echo "==========" $parentdir/flink/build-target/bin/flink cancel $jobid ./cluster.sh stop 4 echo "" if [ "$exitstatus" -eq "1" ] then echo "Flink job with $jobid crashed after introduced failure. Exit." exit 0 fi ((i++)) sleep 3 done <file_sep>/old/present-failed-tasks.sh #!/bin/bash parentdir=.. jps | grep -E -o "([0-9]+) StandaloneSessionClusterEntrypoint" | grep -E -o "^[0-9]+" | # Get the pid of jobmanager. while read -r pid; do logfilename=`ps aux | \ grep $pid | \ grep -E -o 'standalonesession.*\.log'` grep -E -o "\- .*RUNNING to FAILED\.$" $parentdir/flink/build-target/log/flink-flink-${logfilename} done <file_sep>/old/monitor_network.sh #!/bin/bash function poll() { local sleep=$1 shift 1 local pods=("$@") while true; do ts=$(( $(date '+%s%N') / 1000000)) for pod in "${pods[@]}" ; do echo -e "$ts \t $(kubectl exec $pod cat /proc/net/dev | grep eth0 | awk {'print $2 "\t" $10'})" done sleep "$sleep"s done } duration_sec=$1 shift 1 pods=("$@") sleep=$(echo "scale=2 ; 1 - 0.3 * ${#pods[@]}" | bc) for pod in "${pods[@]}" ; do echo -e "TIME \t RX \t TX" done export -f poll timeout "$duration_sec"s bash -c "poll $sleep $(echo $@)" <file_sep>/old/run-recovery-experiment.sh #!/bin/bash date=`date +%Y-%m-%d_%H:%M` results="results-$date" mkdir -p $results default_ss=10000000 #default_ss=1000000000 default_fs=10000000 default_cf=1000 default_p=2 default_d=2 default_kd=1 default_st=1000 default_as=false default_w_size=5 default_w_slide=0.1 default_attempts=1 #We are running with a kubernetes service that exposes it on all ports flink_rpc=0.0.0.0:31234 #Needs to be internal kafka loc. kubectl get svc | grep kafka | grep ClusterIP kafka_bootstrap=$(kubectl get svc | grep ClusterIP | grep kafka | grep -v headless | awk {'print $3'}):9092 node_external_ip=$(ip addr show eth0 | grep "inet\b" | awk '{print $2}' | cut -d/ -f1) kafka_ext=$node_external_ip:31090 #zk_port=$(kubectl get svc | grep zookeeper | grep NodePort | awk '{print $5}' | tr ":" "\n" | tr "/" "\n" | head -n 2 | tail -n 1) #We are running with a kubernetes service that exposes it on all ports zk_loc=$(kubectl get svc | grep ClusterIP | grep zookeeper | grep -v headless | awk {'print $3'}):2181 benchmarkers=$@ input_topic=benchmark-input output_topic=benchmark-output mapjob="clonos-map" windowjob="clonos-window" declare -a work_queue # Specify runs by pushing configurations to work_queue #Assuming we have local recovery + Standby recovery: #We run most experiments with transactions off, to be able to better vizualize the recovery delay #-------- Start off with local recovery #Show our version stops less, using nontransactional system #Get per partition data # |CHK INTERVAL|STATESIZE|PARALLELISM|DEPTHOFGRAPH|KILLDEPTH|SLEEPTIME |WINDOWSIZE |WINDOWSLIDE |ACCESSSTATE|STATEFRAGMENTSIZE| JOB| TEST_TYPE | NUM ATTEMPTS | MEASURELAT #======================= Common failures "Edge usecases" # One kill every 3 seconds "Progress under churn" work_queue+=("$default_cf;$default_ss;$default_p;$default_d;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;random_kill;1;true") ##====================== Default cases, small to large graphs #work_queue+=("$default_cf;$default_ss;1;1;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;3;true") # ##Default case, Perform this one a few times to measure overhead #work_queue+=("$default_cf;$default_ss;$default_p;$default_d;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;5;true") ##Largest graph ##Num CPUs: 10 * 10 * 2 = 200 #work_queue+=("$default_cf;$default_ss;10;8;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;1;false") # ##===================== Parallelism #work_queue+=("$default_cf;$default_ss;1;$default_d;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;1;false") ##Default (5) already done work_queue[1]="$default_cf;$default_ss;$default_p;$default_d;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;1000000;map" #work_queue+=("$default_cf;$default_ss;10;$default_d;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;1;false") ##work_queue[5]="$default_cf;$default_ss;15;$default_d;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;map" ##Max. Num CPUs: 20 * 5 * 2 = 200 #work_queue+=("$default_cf;$default_ss;20;3;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;1;false") # ##===================== Depth #work_queue+=("$default_cf;$default_ss;$default_p;1;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;1;false") ##Default (3) already done work_queue[1]="$default_cf;$default_ss;$default_p;$default_d;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;1000000;map" ##work_queue[8]="$default_cf;$default_ss;$default_p;5;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;map" #work_queue+=("$default_cf;$default_ss;$default_p;8;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;1;false") ##Num CPUs: 5 * 20 * 2 = 200, here we want to see what the effect in number of determinants is. #work_queue+=("$default_cf;$default_ss;$default_p;18;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;1;false") # ##===================== State Size ##work_queue+=("$default_cf;100000000;$default_p;$default_d;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;1;false") #work_queue+=("$default_cf;100000000;$default_p;$default_d;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;1;false") ##work_queue+=("$default_cf;1000000000;$default_p;$default_d;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;1;false") #work_queue+=("$default_cf;5000000000;$default_p;$default_d;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;1;true") # ##====================== Checkpoint Interval #work_queue+=("1000;$default_ss;$default_p;$default_d;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;1;false") ##work_queue+=("1000;$default_ss;$default_p;$default_d;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;1;false") #work_queue+=("10000;$default_ss;$default_p;$default_d;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;1;false") ##Expect this one to stall due to lack of buffers #work_queue+=("100000;$default_ss;$default_p;$default_d;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;1;false") # ##======================== ##Processing time windows ##Change window size #work_queue+=("$default_cf;$default_ss;$default_p;$default_d;$default_kd;$default_st;1;$default_w_slide;$default_as;$default_fs;$windowjob;single_kill;1;false") #work_queue+=("$default_cf;$default_ss;$default_p;$default_d;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$windowjob;single_kill;1;false") #work_queue+=("$default_cf;$default_ss;$default_p;$default_d;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$windowjob;random_kill;1;false") #work_queue+=("$default_cf;$default_ss;$default_p;$default_d;$default_kd;$default_st;5;$default_w_slide;$default_as;$default_fs;$windowjob;single_kill;1;false") #work_queue+=("$default_cf;$default_ss;$default_p;$default_d;$default_kd;$default_st;10;$default_w_slide;$default_as;$default_fs;$windowjob;single_kill;1;false") # ##======================= Kill depth ##Kill depth affects the determinant state transfer size. Deeper = more determinants need to be retransfered # #work_queue+=("$default_cf;$default_ss;$default_p;$default_d;3;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;1;true") ##Kill source and sink. Only for our solution #work_queue+=("$default_cf;$default_ss;$default_p;$default_d;0;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;1;true") #work_queue+=("$default_cf;$default_ss;$default_p;$default_d;4;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;$mapjob;single_kill;1;true") #Sink will not have exactly-once #======================= Transactions #work_queue+=("$default_cf;$default_ss;$default_p;$default_d;$default_kd;$default_st;$default_w_size;$default_w_slide;$default_as;$default_fs;map-trans;single_kill;1") clear_make_topics() { local p=$1 local measure_lat=$2 echo "Trying to clear topic" >&2 ./kafka/bin/kafka-configs.sh --zookeeper $zk_loc --alter --entity-type topics --add-config retention.ms=1000 --entity-name $input_topic >&2 ./kafka/bin/kafka-configs.sh --zookeeper $zk_loc --alter --entity-type topics --add-config retention.ms=1000 --entity-name $output_topic >&2 sleep 5 echo "Remove deletion mechanism" >&2 ./kafka/bin/kafka-configs.sh --zookeeper $zk_loc --alter --entity-type topics --delete-config retention.ms --entity-name $input_topic >&2 ./kafka/bin/kafka-configs.sh --zookeeper $zk_loc --alter --entity-type topics --delete-config retention.ms --entity-name $output_topic >&2 sleep 5 echo "Now delete topic" >&2 ./kafka/bin/kafka-topics.sh --zookeeper $zk_loc --topic $input_topic --delete >&2 ./kafka/bin/kafka-topics.sh --zookeeper $zk_loc --topic $output_topic --delete >&2 sleep 10 echo "Create topic" >&2 ./kafka/bin/kafka-topics.sh --create --zookeeper $zk_loc --topic $input_topic --partitions $p --replication-factor 1 >&2 ./kafka/bin/kafka-topics.sh --create --zookeeper $zk_loc --topic $output_topic --partitions $p --replication-factor 1 >&2 echo "Done creating" >&2 if [ "$measure_lat" = "false" ]; then ./kafka/bin/kafka-configs.sh --zookeeper $zk_loc --alter --entity-type topics --add-config retention.ms=30000 --entity-name $input_topic >&2 ./kafka/bin/kafka-configs.sh --zookeeper $zk_loc --alter --entity-type topics --add-config retention.ms=30000 --entity-name $output_topic >&2 sleep 5 fi } kill_taskmanager() { local jobid=$1 local path=$2 local depth_to_kill=$3 local par_to_kill=$4 # Get taskmanagers used by job local response=$(curl -sS -X GET "http://$flink_rpc/jobs/$1") local vertex_ids=($(echo $response | jq '.vertices[] | .id' | tr -d '"')) echo "Vertexes used: ${vertex_ids[@]}" local taskmanagers_used=($(for vid in ${vertex_ids[@]} ; do curl -sS -X GET "http://$flink_rpc/jobs/$jobid/vertices/$vid/taskmanagers" | jq '.taskmanagers[] | .host' | tr -d '"' | tr ":" " " | awk {'print $1'} ; done)) echo "Taskmanagers used: ${taskmanagers_used[@]}" # Kill the zeroeth tm of subtask of index to kill local taskmanager_to_kill=$(curl -sS -X GET "http://$flink_rpc/jobs/$jobid/vertices/${vertex_ids[$depth_to_kill]}/subtasks/$par_to_kill" | jq '.host' | tr -d '"') local kill_time=$(( $(date '+%s%N') / 1000000)) kubectl delete pod $taskmanager_to_kill echo "Kiled taskmanager $taskmanager_to_kill at $kill_time" echo "$taskmanager_to_kill $depth_to_kill $par_to_kill $kill_time" >> $path/killtime } push_job() { local job=$1 local response=$(curl -sS -X POST -H "Expect:" -F "jarfile=@job-$job.jar" http://$flink_rpc/jars/upload) echo "$response" >&2 local id=$(echo $response | jq '.filename' | tr -d '"' | tr "/" "\n" | tail -n1) echo "$id" } measure_sustainable_throughput() { jobstr=$1 IFS=";" read -r -a params <<< "${jobstr}" local cf="${params[0]}" local ss="${params[1]}" local p="${params[2]}" local d="${params[3]}" local kd="${params[4]}" local st="${params[5]}" local wsize="${params[6]}" local wslide="${params[7]}" local as="${params[8]}" local frag="${params[9]}" local job="${params[10]}" local jobtype="${params[11]}" local attempts="${params[12]}" local measure_lat="${params[13]}" clear_make_topics $p $measure_lat local id=$(push_job $job) response=$(curl -sS -X POST --header "Content-Type: application/json;charset=UTF-8" --data "{\"programArgs\":\" --bootstrap.servers $kafka_bootstrap --experiment-window-size $wsize --experiment-window-slide $wslide --experiment-state-size $ss --experiment-checkpoint-interval-ms $cf --experiment-state-fragment-size $frag --experiment-access-state $as --experiment-depth $d --experiment-parallelism $p --sleep $st\"}" "http://$flink_rpc/jars/$id/run?allowNonRestoredState=false") echo "$response" >&2 sleep 15 ./distributed-producer.sh 220 2000000 $kafka_ext $input_topic $benchmarkers >&2 & sleep 60 local max1=$(python3 ./throughput-measurer/Main.py 20 1 $kafka_ext $output_topic silent) echo "measure 1 $max1" >&2 local max2=$(python3 ./throughput-measurer/Main.py 20 1 $kafka_ext $output_topic silent) echo "measure 2 $max2" >&2 local max3=$(python3 ./throughput-measurer/Main.py 20 1 $kafka_ext $output_topic silent) echo "measure 3 $max3" >&2 local max4=$(python3 ./throughput-measurer/Main.py 20 1 $kafka_ext $output_topic silent) echo "measure 4 $max4" >&2 local max5=$(python3 ./throughput-measurer/Main.py 20 1 $kafka_ext $output_topic silent) echo "measure 5 $max5" >&2 local max6=$(python3 ./throughput-measurer/Main.py 20 1 $kafka_ext $output_topic silent) echo "measure 6 $max6" >&2 local max7=$(python3 ./throughput-measurer/Main.py 20 1 $kafka_ext $output_topic silent) echo "measure 7 $max7" >&2 local max=$(echo -e "$max1\n$max2\n$max3\n$max4\n$max5\n$max6\n$max7" | sort -n -r | head -n1) local jobid=$(curl -sS -X GET "http://$flink_rpc/jobs" | jq '.jobs[0].id' | tr -d '"') curl -sS -X PATCH "http://$flink_rpc/jobs/$jobid?mode=cancel" > /dev/null sleep 3 kubectl delete pod $(kubectl get pod | grep flink | awk {'print $1'}) >&2 sleep 30 echo "$max" } run_experiment() { local jobstr=$1 echo "${jobstr}" >&2 local setting=$2 local max=$3 local path=$4 IFS=";" read -r -a params <<< "${jobstr}" local cf="${params[0]}" local ss="${params[1]}" local p="${params[2]}" local d="${params[3]}" local kd="${params[4]}" local st="${params[5]}" local wsize="${params[6]}" local wslide="${params[7]}" local as="${params[8]}" local frag="${params[9]}" local job="${params[10]}" local jobtype="${params[11]}" local attempts="${params[12]}" local measure_lat="${params[13]}" clear_make_topics $p $measure_lat id=$( push_job $job ) local sustainable=$(echo "$setting * $max" | bc) echo "Setting throughput at $sustainable r/s" >&2 mkdir -p $path/$setting echo $sustainable > $path/$setting/sustainable response=$(curl -sS -X POST --header "Content-Type: application/json;charset=UTF-8" --data "{\"programArgs\":\"--bootstrap.servers $kafka_bootstrap --experiment-window-size $wsize --experiment-window-slide $wslide --experiment-state-size $ss --experiment-state-fragment-size $frag --experiment-access-state $as --experiment-checkpoint-interval-ms $cf --experiment-depth $d --experiment-parallelism $p --sleep $st\"}" "http://$flink_rpc/jars/$id/run?allowNonRestoredState=false") echo "Job run: $response" sleep 15 local jobid=$(curl -sS -X GET "http://$flink_rpc/jobs" | jq '.jobs[0].id' | tr -d '"') response=$(curl -sS -X GET "http://$flink_rpc/jobs/$jobid") vertex_ids=($(echo $response | jq '.vertices[] | .id' | tr -d '"')) local src_pod=$(curl -sS -X GET "http://$flink_rpc/jobs/$jobid/vertices/${vertex_ids[0]}/subtasks/0" | jq '.host' | tr -d '"') local sink_pod=$(curl -sS -X GET "http://$flink_rpc/jobs/$jobid/vertices/${vertex_ids[$(( $d + 1 ))]}/subtasks/0" | jq '.host' | tr -d '"') . ./distributed-producer.sh 200 $sustainable $kafka_ext $input_topic $benchmarkers > /dev/null & sleep 60 python3 ./throughput-measurer/Main.py 120 3 $kafka_ext $output_topic verbose > $path/$setting/throughput & #. ./latmeasurer.sh $jobid 0.1 1200 $d >> $path/$setting/latmeasured & . ./monitor_network.sh 120 $sink_pod >> $path/$setting/network & if [ "$jobtype" = "single_kill" ]; then sleep 60 kill_taskmanager $jobid $path/$setting $kd 0 else sleep 50 for ki in {0..$d}; do random_par=$((RANDOM % $p)) kill_taskmanager $jobid $path/$setting $kd $random_par sleep 5 done fi local maxin=$(python3 ./throughput-measurer/Main.py 20 1 $kafka_ext $input_topic silent) echo "measure input $maxin" >&2 echo "$maxin" > $path/$setting/input-throughput sleep 60 if [ "$measure_lat" = "true" ]; then echo "Measuring latency, this may take a while" >&2 sustrounded=$(echo "${sustainable%.*}") python3 ./endtoendlatency/Main.py -k $kafka_ext -i $input_topic -o $output_topic -r $((sustrounded / 10)) -p $p >> $path/$setting/latency fi echo "Saving logs" local jobmanager=$(kubectl get pods | grep jobmanager | awk '{print $1}') local new_host=$(curl -sS -X GET "http://$flink_rpc/jobs/$jobid/vertices/${vertex_ids[$kd]}/subtasks/0" | jq '.host' | tr -d '"') echo "Canceling the job with id $jobid" curl -sS -X PATCH "http://$flink_rpc/jobs/$jobid?mode=cancel" kubectl logs $jobmanager > $path/$setting/JOBMANAGER-LOGS kubectl logs $new_host > $path/$setting/STANDBY-LOGS kubectl logs $src_pod > $path/$setting/SRC-LOGS kubectl logs $sink_pod > $path/$setting/SINK-LOGS #mkdir -p $path/$setting/logs #for pod in $(kubectl get pod | grep flink | awk {'print $1'}) ; do kubectl logs $pod > $path/$setting/logs/$pod ; done kubectl delete pod $(kubectl get pod | grep flink | awk {'print $1'}) } echo "Beggining experiments" experiment_number=0 for jobstr in "${work_queue[@]}" do IFS=";" read -r -a params <<< "${jobstr}" cf="${params[0]}" ss="${params[1]}" p="${params[2]}" d="${params[3]}" kd="${params[4]}" st="${params[5]}" wsize="${params[6]}" wslide="${params[7]}" as="${params[8]}" frag="${params[9]}" job="${params[10]}" jobtype="${params[11]}" attempts="${params[12]}" measure_lat="${params[13]}" mkdir -p $results/experiment-$experiment_number echo -e "CI\tSS\tP\tD\tKD\tST\tWSIZE\tWSLIDE\tAS\tFG\tJOB\tKILLTYPE\tATTEMPTS\tMEASURELAT" >> $results/experiment-$experiment_number/configuration echo -e "$cf\t$ss\t$p\t$d\t$kd\t$st\t$wsize\t$wslide\t$as\t$frag\t$job\t$jobtype\t$attempts\t$measure_lat" >> $results/experiment-$experiment_number/configuration for a in $(seq 1 $attempts) ; do #attempt path=$results/experiment-$experiment_number/attempt-$a mkdir -p $path echo "Run experiment configuration:" echo " Graph topology: Source - $d operators - Sink" echo " Parallelism degree: $p" echo " State: $ss bytes" echo " Frag Size: $frag bytes" echo " Checkpoint frequency: $cf milliseconds" echo " Kill depth: $kd" echo " Sleep time: $st milliseconds" echo " Access state: $as" echo " Window size: $wsize" echo " Window slide: $wslide" echo " job: $job" echo " jobtype: $jobtype" echo " attempts: $attempts" echo " measure_late: $measure_lat" echo " Input rate: Sustainable" #max=$( measure_sustainable_throughput "${jobstr}" ) max=100000 echo -e "Maximum throughput: $max records/second" sleep 15 ########### Run throughput experiment echo -e "\n\nRunning setting 0.9" run_experiment "${jobstr}" 0.9 $max $path sleep 10 echo -e "\n\nRunning setting 0.5" ########### Run latency experiment run_experiment "${jobstr}" 0.5 $max $path #for pod in $(kubectl get pod | grep flink | awk {'print $1'}) ; do kubectl logs $pod > $path/logs/$pod ; done #kubectl delete pod $(kubectl get pod | grep flink | awk {'print $1'}) sleep 10 done experiment_number=$((experiment_number + 1)) done <file_sep>/endtoendlatency/Main.py import argparse import time import uuid import json from confluent_kafka.cimpl import Consumer, TopicPartition, OFFSET_END current_milli_time = lambda: int(round(time.time() * 1000)) def sample_output_topic(args): num_partitions = int(args["num_partitions"]) mps = int(args["measures_per_second"]) experiment_duration = int(args["duration"]) topic = args["output_topic"] resolution = int(args["resolution"]) transactional = args["transactional"] partition_table = {} consumers = create_consumers(args, num_partitions, partition_table) ms_per_update = 1000 / mps start_time = current_milli_time() last_time = start_time current_time = start_time lag = 0.0 while current_time < start_time + experiment_duration * 1000: current_time = current_milli_time() elapsed = current_time - last_time last_time = current_time lag += elapsed while lag >= ms_per_update: if current_time >= start_time + experiment_duration * 1000: break step(consumers, partition_table, resolution, topic, transactional) # time.sleep() lag -= ms_per_update for i in range(num_partitions): array = partition_table[i] sorted_array = sorted(array, key=lambda triplet: triplet[0]) partition_table[i] = sorted_array consumers[i].close() return partition_table def step(consumers, partition_table, resolution, topic, transactional): if transactional: # consume rest of data time_now = current_milli_time() for partition, c in enumerate(consumers): while True: msg = poll_next_message(c, partition, resolution, topic, transactional) if msg is None or msg.error(): if msg is not None: print("error: " + str(msg.error())) break process_message(msg, partition, partition_table, time_now) else: # Get one message from each consumer for partition, c in enumerate(consumers): msg = poll_next_message(c, partition, resolution, topic, transactional) if msg is None or msg.error(): if msg is not None: print("error:" + str(msg.error())) continue process_message(msg, partition, partition_table) def poll_next_message(c, partition, resolution, topic, transactional): msg = None try: offset = get_next_offset(c, partition, resolution, topic, transactional) c.seek(TopicPartition(topic, partition, offset)) msg = c.poll(timeout=0.05) except Exception as e: print(e) return msg def get_next_offset(c, partition, resolution, topic, transactional): if transactional: return c.position([TopicPartition(topic, partition)])[0].offset + resolution else: return OFFSET_END def process_message(msg, partition, partition_table, visibility_ts=0): dict = json.loads(msg.value()) print("timestamp: " + dict["inputTS"]) print("timestamp[2:]: " + dict["inputTS"][2:]) input_ts = int(dict["inputTS"][2:]) output_ts = int(msg.timestamp()[1]) if visibility_ts == 0: partition_table[partition].append((input_ts, output_ts, visibility_ts, output_ts - input_ts)) else: partition_table[partition].append((input_ts, output_ts, visibility_ts, visibility_ts - input_ts)) def create_consumers(args, num_partitions, partition_table): consumers = [] transactional = args["transactional"] for i in range(num_partitions): partition_table[i] = [] oc = Consumer({ 'bootstrap.servers': args["kafka"], 'group.id': str(uuid.uuid4()), 'auto.offset.reset': 'latest', 'api.version.request': True, 'isolation.level': ('read_committed' if transactional else 'read_uncommitted'), 'max.poll.interval.ms': 86400000 }) oc.assign([TopicPartition(args["output_topic"], i)]) oc.poll(0.5) consumers.append(oc) return consumers def get_latency(args): num_partitions = int(args["num_partitions"]) partition_table = sample_output_topic(args) print_header(num_partitions) print_table(num_partitions, partition_table) def print_table(num_partitions, partition_table): num_readings = min(len(partition) for partition in partition_table.values()) for i in range(num_readings): part0 = partition_table[0] row = "{}\t{}\t{}\t{}".format(part0[i][0], part0[i][1], part0[i][2], part0[i][3]) for part in range(1, num_partitions): parti = partition_table[part] row += "\t{}\t{}\t{}\t{}".format(parti[i][0], parti[i][1], parti[i][2], parti[i][3]) print(row) def print_header(num_partitions): header = "INPUT-0\tOUTPUT-0\tVISIBLE-0\tLATENCY-0" for i in range(1, num_partitions): header += "\tINPUT-{}\tOUTPUT-{}\tVISIBLE-{}\tLATENCY-{}".format(i, i, i, i) print(header) def parse_args(): parser = argparse.ArgumentParser(description='SFaaS CLI') parser.add_argument("-k", "--kafka", help="The location of kafka. A comma separated list of ip:port pairs.") parser.add_argument("-o", "--output-topic", help="The output topic") parser.add_argument("-d", "--duration", help="Duration of experiment", default=120) parser.add_argument("-mps", "--measures-per-second", help="The number of measurements to perform every second", default=2) parser.add_argument("-r", "--resolution", help="The number of records to skip between each consume", default=10000) parser.add_argument("-p", "--num-partitions", help="The number of partitions", default=1) parser.add_argument("-t", "--transactional", help="Whether the consumer is transactional") args = parser.parse_args() args = vars(args) args["transactional"] = str2bool(args["transactional"]) return args def str2bool(v): if isinstance(v, bool): return v if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.') def main(): args = parse_args() get_latency(args) if __name__ == "__main__": main() <file_sep>/old/latmeasurer.sh #!/bin/bash jobid=$1 interval=$2 num_measurements=$3 dep=$4 srcdep=0 sinkdep=$(echo "$dep + 1" | bc) response=$(curl -sS -X GET "http://0.0.0.0:31234/jobs/$jobid") vertex_ids=($(echo $response | jq '.vertices[] | .id' | tr -d '"')) vsrc=${vertex_ids[$srcdep]} isrc=0 vop=${vertex_ids[$sinkdep]} iop=0 for (( i=0; i<=num_measurements; i++ )); do latency_measured=$(curl -sS -X GET "http://0.0.0.0:31234/jobs/$jobid/metrics?get=latency.source_id.$vsrc.source_subtask_index.$isrc.operator_id.$vop.operator_subtask_index.$iop.latency_mean" | jq '.[0].value' | tr -d '"') ts=$(( $(date '+%s%N') / 1000000)) echo "$ts $latency_measured" sleep $interval done <file_sep>/console_latency.sh #!/bin/bash FLINK_RPC=0.0.0.0:31234 get_job_id() { local jobid=$(curl -sS -X GET "http://$FLINK_RPC/jobs" | jq '.jobs[0].id' | tr -d '"') echo $jobid } get_job_vertexes() { local jobid=$1 response=$(curl -sS -X GET "http://$FLINK_RPC/jobs/$jobid") vertex_ids=($(echo $response | jq '.vertices[] | .id' | tr -d '"')) echo "${vertex_ids[@]}" } measure_latency_from_metrics() { local path=$1 local p=$2 local jobid=$(get_job_id) sleep 30 rpc="http:/$FLINK_RPC/jobs/$jobid/metrics" local vertex_ids=($(get_job_vertexes $jobid)) echo -e "TIME\tLATENCY_MEAN\tLATENCY_MEDIAN\tLATENCY_P99" >>$path while true; do local ts=$(date +%s%3N) local o=$((RANDOM % p)) rpc_ops="$rpc?get=latency.operator_id.${vertex_ids[-1]}.operator_subtask_index.$o" echo "Curling: $rpc_ops.latency_mean" >> $path local lat_mean=$(curl -sS "$rpc_ops.latency_mean" | jq ".[0].value" | tr -d '"') local lat_mean=$(echo "${lat_mean%.*}") local lat_median=$(curl -sS "$rpc_ops.latency_median" | jq ".[0].value" | tr -d '"') local lat_median=$(echo "${lat_median%.*}") local lat_p99=$(curl -sS "$rpc_ops.latency_p99" | jq ".[0].value" | tr -d '"') local lat_p99=$(echo "${lat_p99%.*}") echo -e "$ts\t$lat_mean\t$lat_median\t$lat_p99" >> $path sleep 0.1 #125 done } wait_for_job() { jobid=$(get_job_id) echo "JOBID: $jobid" >&2 while [ "$jobid" == "null" ] ; do echo "KEEP WAITING" >&2 jobid=$(get_job_id) sleep 5 done } wait_for_job measure_latency_from_metrics $1 $2 <file_sep>/run-recovery-experiment.sh #!/bin/bash #Any arguments passed are expected to be bencharker IPs, not used for local experiments benchmarkers=$@ #DEFAULTS (does not matter if has "" or not ) D_CI=5000 #Checkpoint interval D_SS=1000000 #State size (100Mib=100000000) D_P=1 #Parallelism D_D=1 #Depth - Number of tasks, not counting sources and sinks D_KD=2 #Kill Depth (1 based, meaning 1 is sources) D_ST=0 #Sleep Time (Iterations in a non-yielding loop) D_W_SIZE=1000 #Window Size (Only if operator is window) D_W_SLIDE=100 #Window Slide (Only if operator is window) D_AS=0.0001 #Access State - Percentage of Records which access and mutate state D_O="map" #Operator D_T="false" #Transactional D_TC="processing" #Time Notion D_LTI="0" #Latency Tracking interval (0 is disabled) D_WM="200" #Watermark interval (0 is disabled) D_DSD="1" #Determinant Sharing Depth D_KT="single_kill" #Kill Type D_ATTEMPTS=1 #Number of attempts for the configuration D_SYSTEM="clonos" #System to test D_SHUFFLE="true" #Shuffle or fully data-parallel D_GRAPH_ONLY="true" #Graph only (data-generators in graph) or with Kafka D_THROUGHPUT="1000" #Target throughput (negative number for unlimited) D_PTI="5" #Perioc Time Interval D_KEYS_PER_PARTITION="1000" #Number of keys each partition will process (defines fragmentation of state) GEN_TS="false" #Generate Timestamps on every record? GEN_RANDOM="false" #Generate Random number on every record? GEN_SERIALIZABLE="false" #Generate Serializable test object (a Long) on every record? #Local (docker-compose) or on Kubernetes LOCAL_EXPERIMENT="true" INPUT_TOPIC=benchmark-input OUTPUT_TOPIC=benchmark-output if [ "$LOCAL_EXPERIMENT" = "true" ]; then FLINK_RPC=localhost:8081 KAFKA_BOOTSTRAP=172.17.0.1:9092 KAFKA_EXTERNAL_LOCATION=172.17.0.1:9092 ZK_LOC=localhost:2181 else #We are running with a kubernetes service that exposes it on all ports FLINK_RPC=0.0.0.0:31234 #Needs to be internal kafka loc. kubectl get svc | grep kafka | grep ClusterIP KAFKA_BOOTSTRAP=$(kubectl get svc | grep ClusterIP | grep kafka | grep -v headless | awk {'print $3'}):9092 NODE_EXTERNAL_IP=$(ip addr show eth0 | grep "inet\b" | awk '{print $2}' | cut -d/ -f1) KAFKA_PORT=31090 KAFKA_EXTERNAL_LOCATION=$NODE_EXTERNAL_IP:$KAFKA_PORT ZK_LOC=$(kubectl get svc | grep ClusterIP | grep zookeeper | grep -v headless | awk {'print $3'}):2181 fi #How long to let the system warm-up SYSTEM_INITIALIZATION_TIME=30 #Total time to measure the systems throughput or latency EXPERIMENT_DURATION=120 #How long into EXPERIMENT_DURATION is the kill performed TIME_TO_KILL=30 SLEEP_BETWEEN_RANDOM_KILLS=5 #Total time the system will run (the time external producers have to be active) TOTAL_EXPERIMENT_TIME=$((EXPERIMENT_DURATION + SYSTEM_INITIALIZATION_TIME)) SLEEP_AFTER_KILL=$((EXPERIMENT_DURATION - TIME_TO_KILL + 10)) declare -a work_queue # Specify runs by pushing configurations to work_queue # Parameter order is the order variables are defined above work_queue+=("$D_CI;$D_SS;$D_P;$D_D;$D_KD;$D_ST;$D_W_SIZE;$D_W_SLIDE;$D_AS;$D_O;$D_T;$D_TC;$D_LTI;$D_WM;$D_DSD;$D_KT;$D_ATTEMPTS;$D_SYSTEM;$D_SHUFFLE;$D_GRAPH_ONLY;$D_THROUGHPUT;$D_PTI;$D_KEYS_PER_PARTITION") clear_make_topics() { local p=$1 echo "Trying to clear topic" >&2 ./kafka/bin/kafka-configs.sh --zookeeper "$ZK_LOC" --alter --entity-type topics --add-config retention.ms=1000 --entity-name $INPUT_TOPIC >&2 ./kafka/bin/kafka-configs.sh --zookeeper "$ZK_LOC" --alter --entity-type topics --add-config retention.ms=1000 --entity-name $OUTPUT_TOPIC >&2 sleep 1 echo "Remove deletion mechanism" >&2 ./kafka/bin/kafka-configs.sh --zookeeper "$ZK_LOC" --alter --entity-type topics --delete-config retention.ms --entity-name $INPUT_TOPIC >&2 ./kafka/bin/kafka-configs.sh --zookeeper "$ZK_LOC" --alter --entity-type topics --delete-config retention.ms --entity-name $OUTPUT_TOPIC >&2 sleep 1 echo "Now delete topic" >&2 ./kafka/bin/kafka-topics.sh --zookeeper "$ZK_LOC" --topic $INPUT_TOPIC --delete >&2 ./kafka/bin/kafka-topics.sh --zookeeper "$ZK_LOC" --topic $OUTPUT_TOPIC --delete >&2 sleep 1 echo "Create topic" >&2 ./kafka/bin/kafka-topics.sh --create --zookeeper "$ZK_LOC" --topic $INPUT_TOPIC --partitions "$p" --replication-factor 1 >&2 ./kafka/bin/kafka-topics.sh --create --zookeeper "$ZK_LOC" --topic $OUTPUT_TOPIC --partitions "$p" --replication-factor 1 >&2 echo "Done creating" >&2 sleep 1 #./kafka/bin/kafka-configs.sh --zookeeper $ZK_LOC --alter --entity-type topics --add-config retention.ms=30000 --entity-name $INPUT_TOPIC >&2 #./kafka/bin/kafka-configs.sh --zookeeper $ZK_LOC --alter --entity-type topics --add-config retention.ms=30000 --entity-name $OUTPUT_TOPIC >&2 #sleep 1 } get_job_vertexes() { local jobid=$1 response=$(curl -sS -X GET "http://$FLINK_RPC/jobs/$jobid") vertex_ids=($(echo $response | jq '.vertices[] | .id' | tr -d '"')) echo "${vertex_ids[@]}" } get_vertex_host() { local jobid=$1 local vertex=$2 local p=$3 local tm=$(curl -sS -X GET "http://$FLINK_RPC/jobs/$jobid/vertices/$vertex/subtasks/$p" | jq '.host' | tr -d '"') echo "$tm" } kill_taskmanager() { taskmanager_to_kill=$1 if [ "$LOCAL_EXPERIMENT" = "true" ]; then docker kill "$taskmanager_to_kill" else kubectl delete --grace-period=0 --force pod "$taskmanager_to_kill" fi echo "Kiled taskmanager $taskmanager_to_kill" >&2 } perform_failures() { local jobid=$1 local path=$2 local d=$3 local p=$4 local kd=$5 local killtype=$6 # Get taskmanagers used by job local vertex_ids=($(get_job_vertexes $jobid)) local taskmanagers_used=($(for vid in ${vertex_ids[@]}; do curl -sS -X GET "http://$FLINK_RPC/jobs/$jobid/vertices/$vid/taskmanagers" | jq '.taskmanagers[] | .host' | tr -d '"' | tr ":" " " | awk {'print $1'}; done)) echo "VERTEX IDS: ${vertex_ids[@]}" >&2 echo "TASKMANAGERS : ${taskmanagers_used[@]}" >&2 local kill_time=$(date +%s%3N) if [ "$killtype" = "single_kill" ]; then #Kill par 0 at the requested depth depth_to_kill=$((kd - 1)) par_to_kill=0 index_to_kill=$((depth_to_kill * p + par_to_kill)) echo "Index to kill $index_to_kill" >&2 local taskmanager_to_kill=${taskmanagers_used[$index_to_kill]} kill_taskmanager "$taskmanager_to_kill" echo "$taskmanager_to_kill $depth_to_kill $par_to_kill $kill_time" >>"$path"/killtime elif [ "$killtype" = "multi_kill" ]; then #Iterate Depths, killing one at each depth at roughly same time for kdi in $(seq 1 "$d"); do par_to_kill=0 index_to_kill=$((kdi * p + par_to_kill)) echo "Index to kill $index_to_kill" >&2 local taskmanager_to_kill=${taskmanagers_used[$index_to_kill]} kill_taskmanager "$taskmanager_to_kill" echo "$taskmanager_to_kill $kdi $par_to_kill $kill_time" >>"$path"/killtime done elif [ "$killtype" = "random_kill" ]; then #Iterate Depths, killing one random task at each depth and sleeping between for kdi in $(seq 1 "$d"); do par_to_kill=$((RANDOM % $p)) index_to_kill=$((kdi * p + par_to_kill)) echo "Index to kill $index_to_kill" >&2 local taskmanager_to_kill=${taskmanagers_used[$index_to_kill]} sleep $SLEEP_BETWEEN_RANDOM_KILLS done fi } push_job() { local job=$1 local response=$(curl -sS -X POST -H "Expect:" -F "jarfile=@job-$job.jar" http://$FLINK_RPC/jars/upload) echo "PUSH: $response" >&2 local id=$(echo "$response" | jq '.filename' | tr -d '"' | tr "/" "\n" | tail -n1) sleep 10 echo "$id" } run_job() { local jarid=$1 local jobstr=$2 IFS=";" read -r -a params <<<"${jobstr}" local ci="${params[0]}" local ss="${params[1]}" local p="${params[2]}" local d="${params[3]}" #local kd="${params[4]}" NOT USED HERE local st="${params[5]}" local wsize="${params[6]}" local wslide="${params[7]}" local as="${params[8]}" local operator="${params[9]}" local trans="${params[10]}" local timechar="${params[11]}" local lti="${params[12]}" local wi="${params[13]}" local dsd="${params[14]}" #local killtype="${params[15]}" NOT USED HERE #local attempts="${params[16]}" NOT USED HERE #local system="${params[17]}" NOT USED HERE local shuffle="${params[18]}" local graph="${params[19]}" local throughput="${params[20]}" local pti="${params[21]}" local keys="${params[22]}" data_str="{\"programArgs\":\" --experiment-checkpoint-interval-ms $ci --experiment-state-size $ss --experiment-parallelism $p --experiment-depth $d --sleep $st --experiment-window-size $wsize --experiment-window-slide $wslide --experiment-access-state $as --experiment-operator $operator --experiment-transactional $trans --experiment-time-char $timechar --experiment-latency-tracking-interval $lti --experiment-watermark-interval $wi --experiment-determinant-sharing-depth $dsd --experiment-shuffle $shuffle --experiment-overhead-measurement $graph --target-throughput $throughput --experiment-time-setter-interval $pti --num-keys-per-partition $keys --bootstrap.servers $KAFKA_BOOTSTRAP --experiment-gen-ts $GEN_TS --experiment-gen-random $GEN_RANDOM --experiment-gen-serializable $GEN_SERIALIZABLE \"}" local response=$(curl -sS -X POST --header "Content-Type: application/json;charset=UTF-8" --data "$data_str" "http://$FLINK_RPC/jars/$jarid/run?allowNonRestoredState=false") echo "RUN: $response" >&2 local job_id=$(echo "$response" | jq ".jobid" | tr -d '"') sleep 5 echo $job_id } cancel_job() { local jobid=$(get_job_id) curl -sS -X PATCH "http://$FLINK_RPC/jobs/$jobid?mode=cancel" >/dev/null sleep 3 } get_job_id() { local jobid=$(curl -sS -X GET "http://$FLINK_RPC/jobs" | jq '.jobs[0].id' | tr -d '"') echo $jobid } measure_throughput_from_metrics() { local p=$1 local jobid=$2 local path=$3 local duration_measure=$4 local FLINK_RPC=$5 local response=$(curl -sS -X GET "http://$FLINK_RPC/jobs/$jobid") local vertex_ids=($(echo $response | jq '.vertices[] | .id' | tr -d '"')) echo -e "TIME\tTHROUGHPUT" >>$path/throughput local sleep_time=$(echo "scale=4 ; 0.5 - $p * 0.05" | bc) if [ "$p" = "20" ] || [ "$p" = "15" ]; then local sleep_time=0 fi while true; do local ts=$(date +%s%3N) local accum=0 for i in $(seq 0 $((p - 1))); do local vmax=$(curl -sS "http:/$FLINK_RPC/jobs/$jobid/vertices/${vertex_ids[0]}/subtasks/$i/metrics?get=numRecordsOutPerSecond" | jq ".[0].value" | tr -d '"') local vmax=$(echo "${vmax%.*}") accum=$((accum + vmax)) done echo "Throughput measured: $accum" >&2 echo -e "$ts\t$accum" >>$path/throughput sleep 5 done } measure_latency_from_metrics() { local p=$1 local d=$2 local jobid=$3 local path=$4 local duration_measure=$5 local shuffle=$6 local FLINK_RPC=$7 local response=$(curl -sS -X GET "http://$FLINK_RPC/jobs/$jobid") local vertex_ids=($(echo $response | jq '.vertices[] | .id' | tr -d '"')) echo -e "TIME\tLATENCY" >>$path/latency while true; do local ts=$(date +%s%3N) local i=$((RANDOM % p)) local o=$i if [ "$shuffle" = "true" ]; then local o=$((RANDOM % p)) fi local lat=$(curl -sS "http:/$FLINK_RPC/jobs/$jobid/metrics?get=latency.source_id.${vertex_ids[0]}.operator_id.${vertex_ids[$((d + 2 - 1))]}.operator_subtask_index.$o.latency_mean" | jq ".[0].value" | tr -d '"') echo "Measured latency: $lat" >&2 local lat=$(echo "${lat%.*}") echo -e "$ts\t$lat" >>$path/latency sleep 0.5 #125 done } measure_sustainable() { local jobstr=$1 local path=$2 echo "=== Measure sustainable ===" >&2 IFS=";" read -r -a params <<<"${jobstr}" local p="${params[2]}" local d="${params[3]}" local job="${params[17]}" local shuffle="${params[18]}" local graphonly="${params[19]}" local id=$(push_job "$job") if [ "$graphonly" = "false" ]; then clear_make_topics "$p" echo "Starting Kafka Producer!!!" >&2 if [ "$LOCAL_EXPERIMENT" = "true" ] ; then local num_records=$((throughput * TOTAL_EXPERIMENT_TIME)) timeout $TOTAL_EXPERIMENT_TIME bash -c "./kafka/bin/kafka-producer-perf-test.sh --dist-producer-index 0 --dist-producer-total 1 --topic $INPUT_TOPIC --num-records $num_records --throughput $throughput --producer-props bootstrap.servers=$KAFKA_EXTERNAL_LOCATION key.serializer=org.apache.kafka.common.serialization.StringSerializer value.serializer=org.apache.kafka.common.serialization.StringSerializer 2> kafka-err 1> kafka-out" >&2 & else ./distributed-producer.sh $TOTAL_EXPERIMENT_TIME "$KAFKA_EXTERNAL_LOCATION" $INPUT_TOPIC "$benchmarkers" >&2 & fi fi local jobid=$(run_job $id $jobstr) sleep $SYSTEM_INITIALIZATION_TIME monitor_all_vertexes_network $EXPERIMENT_DURATION $path $jobid $p $d 2>/dev/null >&2 export -f measure_latency_from_metrics export -f measure_throughput_from_metrics if [ "$graphonly" = "true" ]; then echo "Starting latency and throughput measurers" >&2 timeout $EXPERIMENT_DURATION bash -c "measure_latency_from_metrics $p $d $jobid $path $EXPERIMENT_DURATION $shuffle $FLINK_RPC" & timeout $EXPERIMENT_DURATION bash -c "measure_throughput_from_metrics $p $jobid $path $EXPERIMENT_DURATION $FLINK_RPC" & #Column indices thr_index=2 lat_index=2 else local resolution=10000 python3 ./endtoendlatency/Main.py -k "$KAFKA_EXTERNAL_LOCATION" -o "$OUTPUT_TOPIC" -r $resolution -p $p -d $EXPERIMENT_DURATION -mps 3 -t $trans >$path/latency & python3 ./throughput-measurer/Main.py $EXPERIMENT_DURATION 2 "$KAFKA_EXTERNAL_LOCATION" $OUTPUT_TOPIC verbose > $path/throughput & #Column indices thr_index=2 lat_index=4 fi #Sleep while waiting for measurements to complete sleep $((EXPERIMENT_DURATION + 2)) local max=$(cat "$path"/throughput | awk {'print $'"$thr_index"} | tail -n+10 | tac | tail -n+10 | jq -s add/length) local max=$(echo "${max%.*}") echo "Average Thr: $max" >&2 echo $max >>$path/avg-throughput local lat=$(cat "$path"/latency | awk {'print $'"$lat_index"} | tail -n+10 | tac | tail -n+10 | jq -s add/length) local lat=$(echo "${lat%.*}") echo "Average Lat: $lat" >&2 echo "$lat" >>"$path"/avg-latency log_taskmanagers $jobid $path/logs $p $d cancel_job echo "$max" } monitor_all_vertexes_network() { local duration=$1 local path=$2 local jobid=$3 local p=$4 local d=$5 mkdir -p $path/network local vertex_ids=($(get_job_vertexes $jobid)) local tms_used=($(for vid in ${vertex_ids[@]}; do curl -sS -X GET "http://$FLINK_RPC/jobs/$jobid/vertices/$vid/taskmanagers" | jq '.taskmanagers[] | .host' | tr -d '"' | tr ":" " " | awk {'print $1'}; done)) for di in $(seq 0 $((d + 2 - 1))); do for pi in $(seq 0 $((p - 1))); do tm=${tms_used[$((di * p + pi))]} . ./monitor_network.sh $duration $tm $LOCAL_EXPERIMENT >>$path/network/network-$di-$pi & done done if [ "$LOCAL_EXPERIMENT" = "true" ]; then local all_tms=($(docker ps | grep taskmanager | awk {'print $1'})) else local all_tms=($(kubectl get pods | grep taskmanager | awk {'print $1'})) fi #Standby tms are the unique ones when both lists are joined local standby_tms=$(echo ${tms_used[@]} ${all_tms[@]} | tr ' ' '\n' | sort | uniq -u) for tm in ${standby_tms[@]}; do . ./monitor_network.sh $duration $tm $LOCAL_EXPERIMENT >>$path/network/network-standby-$tm & done } run_experiment() { local jobstr=$1 local path=$2 IFS=";" read -r -a params <<<"${jobstr}" local ci="${params[0]}" local ss="${params[1]}" local p="${params[2]}" local d="${params[3]}" local kd="${params[4]}" local st="${params[5]}" local wsize="${params[6]}" local wslide="${params[7]}" local as="${params[8]}" local operator="${params[9]}" local trans="${params[10]}" local timechar="${params[11]}" local lti="${params[12]}" local wi="${params[13]}" local dsd="${params[14]}" local killtype="${params[15]}" local attempts="${params[16]}" local system="${params[17]}" local shuffle="${params[18]}" local graphonly="${params[19]}" local throughput="${params[20]}" local pti="${params[21]}" local keys="${params[22]}" if [ "$graphonly" = "false" ]; then clear_make_topics $p fi id=$(push_job $system) local sustainable=$throughput echo "Setting throughput at $sustainable r/s" >&2 mkdir -p "$path" if [ "$graphonly" = "false" ]; then if [ "$LOCAL_EXPERIMENT" = "true" ] ; then local num_records=$((throughput * TOTAL_EXPERIMENT_TIME)) timeout $TOTAL_EXPERIMENT_TIME bash -c "./kafka/bin/kafka-producer-perf-test.sh --dist-producer-index 0 --dist-producer-total 1 --topic $INPUT_TOPIC --num-records $num_records --throughput $throughput --producer-props bootstrap.servers=$KAFKA_EXTERNAL_LOCATION key.serializer=org.apache.kafka.common.serialization.StringSerializer value.serializer=org.apache.kafka.common.serialization.StringSerializer 2> kafka-err 1> kafka-out" >&2 & else echo "Starting distributed producer to $KAFKA_EXTERNAL_LOCATION" >&2 . ./distributed-producer.sh $TOTAL_EXPERIMENT_TIME "$sustainable" "$KAFKA_EXTERNAL_LOCATION" $INPUT_TOPIC "$benchmarkers" >&2 & fi fi sleep 3 local jobid=$(run_job "$id" "$jobstr") sleep $SYSTEM_INITIALIZATION_TIME local vertex_ids=($(get_job_vertexes $jobid)) local resolution=$((sustainable / 5 + 1)) local resolution=$(echo "${resolution%.*}") if [ "$operator" = "window" ]; then local resolution=$(((wsize / wslide) * 1000 / 5 + 1)) fi local resolution=$(echo "${resolution%.*}") monitor_all_vertexes_network $EXPERIMENT_DURATION $path $jobid $p $d 2>/dev/null >&2 if [ "$graphonly" = "false" ]; then python3 ./endtoendlatency/Main.py -k $KAFKA_EXTERNAL_LOCATION -o $OUTPUT_TOPIC -r $resolution -p $p -d $EXPERIMENT_DURATION -mps 3 -t $trans >$path/latency & python3 ./throughput-measurer/Main.py $EXPERIMENT_DURATION 3 $KAFKA_EXTERNAL_LOCATION $OUTPUT_TOPIC verbose >$path/throughput & else #export -f measure_latency_from_metrics export -f measure_throughput_from_metrics #timeout $EXPERIMENT_DURATION bash -c "measure_latency_from_metrics $p $d $jobid $path $EXPERIMENT_DURATION $shuffle $FLINK_RPC" & timeout $EXPERIMENT_DURATION bash -c "measure_throughput_from_metrics $p $jobid $path $EXPERIMENT_DURATION $FLINK_RPC" & fi sleep $TIME_TO_KILL perform_failures "$jobid" "$path" $d $p $kd $killtype sleep $SLEEP_AFTER_KILL if [ "$trans" = "true" ]; then ./extract-transaction-commits.sh $KAFKA_EXTERNAL_LOCATION $path fi log_taskmanagers $jobid $path/logs $p $d echo "Canceling the job with id $jobid" >&2 cancel_job } log_taskmanagers() { jobid=$1 path=$2 p=$3 d=$4 mkdir -p $path local vertex_ids=($(get_job_vertexes $jobid)) local tms_used=($(for vid in ${vertex_ids[@]}; do curl -sS -X GET "http://$FLINK_RPC/jobs/$jobid/vertices/$vid/taskmanagers" | jq '.taskmanagers[] | .host' | tr -d '"' | tr ":" " " | awk {'print $1'}; done)) echo "VERTEX IDS: ${vertex_ids[@]}" >&2 echo "TASKMANAGERS : ${tms_used[@]}" >&2 for di in $(seq 0 $((d + 2 - 1))); do for pi in $(seq 0 $((p - 1))); do tm=${tms_used[$((di * p + pi))]} if [ "$LOCAL_EXPERIMENT" = "true" ]; then docker logs $tm >>$path/worker-$di-$pi else kubectl logs $tm >>$path/worker-$di-$pi fi done done if [ "$LOCAL_EXPERIMENT" = "true" ]; then local all_tms=($(docker ps | grep taskmanager | awk {'print $1'})) else local all_tms=($(kubectl get pods | grep taskmanager | awk {'print $1'})) fi #Standby tms are the unique ones when both lists are joined local standby_tms=$(echo "${tms_used[@]} ${all_tms[@]}" | tr ' ' '\n' | sort | uniq -u) for tm in ${standby_tms[@]}; do if [ "$LOCAL_EXPERIMENT" = "true" ]; then docker logs $tm >>$path/worker-standby-$tm else kubectl logs $tm >>$path/worker-standby-$tm fi done if [ "$LOCAL_EXPERIMENT" = "true" ]; then for i in $(docker ps | grep $system | grep jobm | awk {'print $1'}); do docker logs $i >$path/master; done else for i in $(kubectl get pods | grep $system | grep jobm | awk {'print $1'}); do kubectl logs $i >$path/master; done fi } reset_cluster() { num_nodes_req=$1 if [ "$LOCAL_EXPERIMENT" = "true" ]; then docker-compose down -v && docker-compose up -d --scale taskmanager=$num_nodes_req else kubectl delete pod $(kubectl get pods | grep flink | awk {'print $1'}) fi sleep 20 #Allow cluster to initialize } echo "Beggining experiments" date=$(date +%Y-%m-%d_%H:%M) results="results-$date" mkdir -p "$results" experiment_number=0 for jobstr in "${work_queue[@]}"; do IFS=";" read -r -a params <<<"${jobstr}" ci="${params[0]}" ss="${params[1]}" p="${params[2]}" d="${params[3]}" kd="${params[4]}" st="${params[5]}" wsize="${params[6]}" wslide="${params[7]}" as="${params[8]}" operator="${params[9]}" trans="${params[10]}" timechar="${params[11]}" lti="${params[12]}" wi="${params[13]}" dsd="${params[14]}" killtype="${params[15]}" attempts="${params[16]}" system="${params[17]}" shuffle="${params[18]}" graphonly="${params[19]}" throughput="${params[20]}" pti="${params[21]}" keys="${params[22]}" num_nodes_req=$((p * (d+ 2) * 2)) # * 2 for standbys mkdir -p "$results"/experiment-$experiment_number echo -e "CI\tSS\tP\tD\tKD\tST\tWSIZE\tWSLIDE\tAS\tOPERATOR\tTRANS\tTC\tLTI\tWI\tDSD\tKILLTYPE\tATTEMPTS\tSYSTEM\tSHUFFLE\tOVERHEAD\tTHROUGHPUT\tPTI\tKEYS" >>"$results"/experiment-$experiment_number/configuration echo -e "$ci\t$ss\t$p\t$d\t$kd\t$st\t$wsize\t$wslide\t$as\t$operator\t$trans\t$timechar\t$lti\t$wi\t$dsd\t$killtype\t$attempts\t$system\t$shuffle\t$graphonly\t$throughput\t$pti\t$keys" >>$results/experiment-$experiment_number/configuration path=$results/experiment-$experiment_number mkdir -p "$path" echo "Run experiment configuration:" echo " System: $system" echo " Graph topology: Source - $d operators - Sink" echo " Parallelism degree: $p" echo " State: $ss bytes" echo " Num Keys: $keys" echo " Checkpoint frequency: $ci milliseconds" echo " Kill depth: $kd" echo " Sleep time: $st milliseconds" echo " Access state %: $as" echo " Window size: $wsize" echo " Operator: $operator" echo " Transactional: $trans" echo " Time Characteristic: $timechar" echo " Watermark Interval: $wi" echo " Determinant Sharing Depth: $dsd" echo " Kill Type: $killtype" echo " Shuffle: $shuffle" echo " Attempts: $attempts" echo " Overhead: $graphonly" echo " Throughput: throughput" #max=0 #maxes="" #for a in $(seq 1 "$attempts"); do # reset_cluster $num_nodes_req # full_path="$path"/sustainable/"$a" # mkdir -p "$full_path" # max=$(measure_sustainable "${jobstr}" "$full_path") # echo -e "Maximum throughput: $max records/second" # maxes="${maxes}$max\n" #done #echo -e "$maxes" >"$path"/avg-max-throughput #max=$(echo -e $maxes | jq -s add/length) #Average #max=$(echo "${max%.*}") #echo -e "Average of averages ($maxes): $max" >&2 reset_cluster $num_nodes_req run_experiment "${jobstr}" $path experiment_number=$((experiment_number + 1)) done <file_sep>/old/find-kill-taskmanager.sh #!/bin/bash parentdir=.. # Check the job's state after killing the taskmanager. Works only for one job. function check_state() { stateprevious="" for i in {1..10} do state=`$parentdir/flink/build-target/bin/flink list | \ grep -E -o "\([A-Z]+\)$" | \ grep -E -o "[A-Z]+"` if [ ! -z "$state" ] && [ "$state" != "RUNNING" ] then echo "Job has state $state (other than RUNNING). Exit." exit 1 elif [ -z "$state" ] && [ "$stateprevious" == "RUNNING" ] then echo "Job is not running anymore." exit 1 elif [ -z "$state" ] then echo "No job is running. Probably crashed." exit 1 else echo "Job is running." fi stateprevious=$state sleep 1 done } jps | grep -E -o "([0-9]+) TaskManagerRunner" | grep -E -o "^[0-9]+" | # Get the pid of each taskmanager. while read -r pid; do logfilename=`ps aux | \ grep $pid | \ grep -E -o 'taskexecutor.*\.log'` wc=0 # Check if the taskmanager's output file grows. for i in {1..10} do wcprevious=$wc filename=`basename $logfilename .log` outfilename=${filename}.out wc=`wc -l $parentdir/flink/build-target/log/flink-flink-${outfilename} | \ grep -E -o "^([0-9]+)"` echo "Length of ${outfilename} is $wc lines (was $wcprevious)." if [ "$wcprevious" -ne "0" ] && [ "$wc" -gt "$wcprevious" ] then echo "$outfilename with pid $pid produces output." triggerfailure="true" # Kill taskmanager if its output file grows, i.e. it's producing output. echo "Send terminate signal to pid $pid." kill -s 15 $pid break fi sleep 1 done echo "" if [ "$triggerfailure" == "true" ] then check_state break fi done <file_sep>/old/present-output-taskmanager.sh #!/bin/bash parentdir=.. jps | grep -E -o "([0-9]+) TaskManagerRunner" | grep -E -o "^[0-9]+" | # Get the pid of each taskmanager. while read -r pid; do logfilename=`ps aux | \ grep $pid | \ grep -E -o 'taskexecutor.*\.log'` filename=`basename $logfilename .log` outfilename=${filename}.out wc=`wc -l $parentdir/flink/build-target/log/flink-flink-${outfilename} | \ grep -E -o "^([0-9]+)"` if [ "$wc" -gt "31" ] then echo "" echo "First five lines of ${outfilename} are:" head -n 36 $parentdir/flink/build-target/log/flink-flink-${outfilename} | \ tail -n 5 fi done <file_sep>/throughput-measurer/Main.py import time import uuid import sys from confluent_kafka.cimpl import Consumer import statistics current_milli_time = lambda: int(round(time.time() * 1000)) def exec_benchmark(duration_s, fps, kafka_loc, output_topic, silent): """Measures throughput at the output Kafka topic, by checking the growth in all partitions""" c = Consumer({ 'bootstrap.servers': kafka_loc, 'group.id': 'benchmark-' + str(uuid.uuid4()), 'auto.offset.reset': 'latest', 'max.poll.interval.ms': 86400000, 'isolation.level': 'read_committed' }) # === Get topic partitions topic_partitions = None def store_topic_partition(consumer, partitions): nonlocal topic_partitions topic_partitions = partitions c.subscribe([output_topic], on_assign=store_topic_partition) while topic_partitions is None: c.consume(timeout=0.5) #Loop read partitions throughput_measured = [] throughput_measured_per_partition = {} last_values = {} for p in topic_partitions: low, high = c.get_watermark_offsets(p) throughput_measured_per_partition[p.partition] = [] last_values[p.partition] = high #if silent != "silent": # print("Starting value for partition {}: {}".format(p.partition, high)) MS_PER_UPDATE = 1000 / fps start_time = current_milli_time() last_time = start_time current_time = start_time last_write_time = current_time lag = 0.0 while current_time < start_time + duration_s * 1000: current_time = current_milli_time() elapsed = current_time - last_time last_time = current_time lag += elapsed while lag >= MS_PER_UPDATE: #calc new val total_new = 0 curr_time_for_print = current_milli_time() time_delta=((curr_time_for_print - last_write_time)/1000) if time_delta > 0: for p in topic_partitions: low, high = c.get_watermark_offsets(p) delta = high - last_values[p.partition] total_new += delta throughput_measured_per_partition[p.partition].append((delta / time_delta , curr_time_for_print)) last_values[p.partition] = high throughput_measured.append((total_new / time_delta, curr_time_for_print)) last_write_time = curr_time_for_print lag -= MS_PER_UPDATE if silent != "silent": #Print column names #TIME THROUGHPUT PART-0 ... PART-N columns = "TIME\tTHROUGHPUT" for i in range(len(topic_partitions)): columns += "\tPART-{}".format(str(i)) print(columns) for row in range(len(throughput_measured)): row_data = "{}\t{}".format(throughput_measured[row][1], int(throughput_measured[row][0])) for i in range(len(topic_partitions)): row_data+= "\t{}".format(int(throughput_measured_per_partition[i][row][0])) print(row_data) else: print(int(statistics.mean([x[0] for x in throughput_measured if x[0] > 0.0]))) def main(): if len(sys.argv) != 6: print("Error! Usage: python3 {} duration_in_seconds readings_per_second kafka_bootstrap output_topic") exit(1) exec_benchmark(int(sys.argv[1]),int(sys.argv[2]), sys.argv[3],sys.argv[4], sys.argv[5]) if __name__ == "__main__": main() <file_sep>/old/cluster.sh #!/bin/bash TASKMANAGERS=$2 parentdir=.. if [ $# -ne 2 ]; then echo "Wrong syntax. Expected: cluster-tm.sh (start | stop) <number-of-taskmanagers>." exit 1 fi if [[ "$1" == "start" ]]; then $parentdir/flink/build-target/bin/start-cluster.sh for ((i=1; i<TASKMANAGERS; i++)); do $parentdir/flink/build-target/bin/taskmanager.sh start done else $parentdir/flink/build-target/bin/stop-cluster.sh for ((i=1; i<TASKMANAGERS; i++)); do $parentdir/flink/build-target/bin/taskmanager.sh stop done fi <file_sep>/old/distributed-producer.sh #!/bin/bash duration_seconds=$1 throughput=$2 kafka=$3 topic=$4 shift 5 ips=$@ size=${#ips[@]} #size=$(echo "$size + 1" | bc) throughput_per_node=$(echo "$throughput / $size" | bc) remainder=$(echo "$throughput % $size" | bc ) master_throughput=$(echo "$throughput_per_node + $remainder" | bc) num_records_per_node=$(echo "$throughput_per_node * $duration_seconds" | bc) echo "Requested throughput: $throughput" echo "Throughput per node: $throughput_per_node" echo "Num records per node: $num_records_per_node" prodindex=0 for ip in $ips ; do #ssh -o StrictHostKeyChecking=no ubuntu@$ip "timeout $duration_seconds /home/ubuntu/kafka/bin/kafka-producer-perf-test.sh --topic $topic --num-records $num_records_per_node --throughput $throughput_per_node --producer-props bootstrap.servers=$kafka key.serializer=org.apache.kafka.common.serialization.StringSerializer value.serializer=org.apache.kafka.common.serialization.StringSerializer --payload-file /home/ubuntu/cracklib-small &> /dev/null" & ssh -o StrictHostKeyChecking=no ubuntu@$ip "timeout $duration_seconds /home/ubuntu/kafka/bin/kafka-producer-perf-test.sh --dist-producer-index $prodindex --dist-producer-total $size --topic $topic --num-records $num_records_per_node --throughput $throughput_per_node --producer-props bootstrap.servers=$kafka key.serializer=org.apache.kafka.common.serialization.StringSerializer value.serializer=org.apache.kafka.common.serialization.StringSerializer &> /dev/null" & prodindex=$((prodindex+1)) done #timeout $duration_seconds /home/ubuntu/kafka/bin/kafka-producer-perf-test.sh --topic $topic --num-records $num_records_per_node --throughput $throughput_per_node --producer-props bootstrap.servers=$kafka key.serializer=org.apache.kafka.common.serialization.StringSerializer value.serializer=org.apache.kafka.common.serialization.StringSerializer --payload-file /home/ubuntu/cracklib-small &> /dev/null <file_sep>/extract-input-throughput-data.sh consumer=$(./kafka/bin/kafka-console-consumer.sh \ --formatter 'kafka.coordinator.group.GroupMetadataManager$OffsetsMessageFormatter' \ --bootstrap-server $1 --topic __consumer_offsets --from-beginning \ --timeout-ms 2000 | grep benchmark-group | tr "[,]:" " " | awk '{print $1}' | tail -n1) echo -e "PARTITION\tOFFSET\tTS" >> input-offsets ./kafka/bin/kafka-console-consumer.sh \ --formatter 'kafka.coordinator.group.GroupMetadataManager$OffsetsMessageFormatter' \ --bootstrap-server $1 --topic __consumer_offsets --from-beginning \ --timeout-ms 2000 | grep $consumer | tr "[,]:" " " | awk '{print $3 "\t" $5 "\t" $8}' >> input-offsets python3 extract-input-throughtput.py <file_sep>/README.md # flink-test-scripts A set of bash scripts that repeatedly execute a native example from Flink's code base, kill a task manager, and check whether the job resumes successfully. The main script is run-recovery-experiment.sh. This script can be used to launch sequences of complex experiments and record the results. These experiments are enabled by a highly configurable synthetic job, whose parameters can be set at runtime. The job is included in both source (StatefulMapperJob) and as a jar (job-clonos.jar). ### Graph only vs. external Kafka generators The script operates in two modes, controlled by a variable (graph_only). In graph_only mode, generators are inside the graph and automatically generate data. If graph_only mode is set to false, the job attempts to connect to a kafka cluster. This cluster is assumed to be local (launched from the same docker-compose), unless execution is set to be distributed, in which case it expects a Kubernetes service to represent Kafka and attempts to create topics "benchmark-input" and "benchmark-output". ### Local experiment vs. Distributed Experiment The LOCAL_EXPERIMENT constant can be used to set whether the script should expect to be executed in Kubernetes or in Docker. If set to false (distributed), further configuration is necessary by modifying the addresses of kafka, flink and zookeeper used in the script. Furthermore, the addresses of one or more benchmark data generators must be passed as input parameters to the script. Through SSH, the script will attempt to call a Kafka generator to generate the specific kind of data this job expects. Thus, these benchmarker nodes must have installed the kafka distribution packaged with this repository. ### Measurements Two hand-developed tools are used to measure execution with high precision. The end-to-end latency measurer is used in distributed experiments to obtain the latency of a record calculated from a timestamp generated at record creation time and a timestamp generated at output topic append time. The throughput measurer uses Kafka watermarks to calculate topic size deltas, and from that calculate throughput. If the experiment is graph_only, then flinks metrics services are queried instead, though these are not reliable, and only used for internal testing (not for publishable results). <file_sep>/monitor_network.sh #!/bin/bash function poll() { local sleep=$1 local vertex=$2 local local_experiment=$3 while true; do ts=$(( $(date '+%s%N') / 1000000)) if [ "$local_experiment" = "false" ]; then echo -e "$ts\t$(kubectl exec $pod cat /proc/net/dev | grep eth0 | awk {'print $2 "\t" $10'})" else echo -e "$ts\t$(docker exec $pod cat /proc/net/dev | grep eth0 | awk {'print $2 "\t" $10'})" fi sleep "$sleep"s done } duration_sec=$1 vertex=$2 local_experiment=$3 sleep="0.5" echo -e "TIME\tRX\tTX" export -f poll timeout "$duration_sec"s bash -c "poll $sleep $vertex $local_experiment" <file_sep>/run-nexmark-recovery-experiment.sh #!/bin/bash date=`date +%Y-%m-%d_%H:%M` results="results-$date" mkdir -p $results d_query=3 d_p=5 d_kd=3 d_attempts=1 d_er=0 #We are running with a kubernetes service that exposes it on all ports flink_rpc=0.0.0.0:31234 #Needs to be internal kafka loc. kubectl get svc | grep kafka | grep ClusterIP kafka_bootstrap=$(kubectl get svc | grep ClusterIP | grep kafka | grep -v headless | awk {'print $3'}):9092 node_external_ip=$(ip addr show eth0 | grep "inet\b" | awk '{print $2}' | cut -d/ -f1) kafka_ext=$node_external_ip:31090 #zk_port=$(kubectl get svc | grep zookeeper | grep NodePort | awk '{print $5}' | tr ":" "\n" | tr "/" "\n" | head -n 2 | tail -n 1) #We are running with a kubernetes service that exposes it on all ports zk_loc=$(kubectl get svc | grep ClusterIP | grep zookeeper | grep -v headless | awk {'print $3'}):2181 benchmarkers=$@ input_topic=benchmark-input output_topic=benchmark-output system="clonos" totalexperimenttime=230 inittime=60 timetokill=60 duration=$(( totalexperimenttime - inittime )) sleep_between_kills=5 declare -a work_queue # Specify runs by pushing configurations to work_queue #Assuming we have local recovery + Standby recovery: #We run most experiments with transactions off, to be able to better vizualize the recovery delay #-------- Start off with local recovery #Show our version stops less, using nontransactional system #Get per partition data # |CHK INTERVAL|STATESIZE|PARALLELISM|DEPTHOFGRAPH|KILLDEPTH|SLEEPTIME |WINDOWSIZE |WINDOWSLIDE |ACCESSSTATE|STATEFRAGMENTSIZE| OPERATOR| TRANSACTIONAL| TIME CHARACTERISTIC | WATERMARK_INTERVAL | KILL TYPE | NUM ATTEMPTS | SYSTEM | SHUFFLE | OVERHEAD | THROUGHPUT #=================================================================================== Overhead measurements # QUERY|PAR|KD|ER|ATTEMPT| #work_queue+=("4;5;1;500000;1") #Kill the stateful task #work_queue+=("3;5;2;500000;1") #Kill the stateless task #work_queue+=("3;5;1;500000;1") # Q5 kill the stateful task work_queue+=("5;5;1;500000;1") #work_queue+=("8;10;1;500000;1") #work_queue+=("3;5;2;1000000;1") clear_make_topics() { local p=$1 echo "Trying to clear topic" >&2 ./kafka/bin/kafka-configs.sh --zookeeper $zk_loc --alter --entity-type topics --add-config retention.ms=1000 --entity-name $input_topic >&2 ./kafka/bin/kafka-configs.sh --zookeeper $zk_loc --alter --entity-type topics --add-config retention.ms=1000 --entity-name $output_topic >&2 sleep 1 echo "Remove deletion mechanism" >&2 ./kafka/bin/kafka-configs.sh --zookeeper $zk_loc --alter --entity-type topics --delete-config retention.ms --entity-name $input_topic >&2 ./kafka/bin/kafka-configs.sh --zookeeper $zk_loc --alter --entity-type topics --delete-config retention.ms --entity-name $output_topic >&2 sleep 1 echo "Now delete topic" >&2 ./kafka/bin/kafka-topics.sh --zookeeper $zk_loc --topic $input_topic --delete >&2 ./kafka/bin/kafka-topics.sh --zookeeper $zk_loc --topic $output_topic --delete >&2 sleep 1 echo "Create topic" >&2 ./kafka/bin/kafka-topics.sh --create --zookeeper $zk_loc --topic $input_topic --partitions $p --replication-factor 1 >&2 ./kafka/bin/kafka-topics.sh --create --zookeeper $zk_loc --topic $output_topic --partitions $p --replication-factor 1 >&2 echo "Done creating" >&2 sleep 1 #./kafka/bin/kafka-configs.sh --zookeeper $zk_loc --alter --entity-type topics --add-config retention.ms=30000 --entity-name $input_topic >&2 #./kafka/bin/kafka-configs.sh --zookeeper $zk_loc --alter --entity-type topics --add-config retention.ms=30000 --entity-name $output_topic >&2 #sleep 1 } get_job_vertexes() { local jobid=$1 response=$(curl -sS -X GET "http://$flink_rpc/jobs/$jobid") vertex_ids=($(echo $response | jq '.vertices[] | .id' | tr -d '"')) echo "${vertex_ids[@]}" } get_vertex_host() { local jobid=$1 local vertex=$2 local p=$3 local tm=$(curl -sS -X GET "http://$flink_rpc/jobs/$jobid/vertices/$vertex/subtasks/$p" | jq '.host' | tr -d '"') echo "$tm" } kill_taskmanager() { local jobid=$1 local path=$2 local depth_to_kill=$3 #zero based local par_to_kill=$4 #zero based local p_tot=$5 # Get taskmanagers used by job local vertex_ids=($(get_job_vertexes $jobid)) echo "VERTEX IDS: ${vertex_ids[@]}" >&2 local taskmanagers_used=($(for vid in ${vertex_ids[@]} ; do curl -sS -X GET "http://$flink_rpc/jobs/$jobid/vertices/$vid/taskmanagers" | jq '.taskmanagers[] | .host' | tr -d '"' | tr ":" " " | awk {'print $1'} ; done)) echo "TASKMANAGERS : ${taskmanagers_used[@]}" >&2 local kill_time=$(date +%s%3N) echo "Index to kill $((depth_to_kill*p_tot + par_to_kill ))" >&2 local taskmanager_to_kill=${taskmanagers_used[$((depth_to_kill*p_tot + par_to_kill ))]} kubectl delete --grace-period=0 --force pod $taskmanager_to_kill echo "Kiled taskmanager $taskmanager_to_kill at $kill_time" >&2 echo "$taskmanager_to_kill $depth_to_kill $par_to_kill $kill_time" >> $path/killtime } run_job() { local jarid=$1 local jobstr=$2 IFS=";" read -r -a params <<< "${jobstr}" # QUERY|PAR|KD|ER|ATTEMPT| local q="${params[0]}" local par="${params[1]}" local kd="${params[2]}" local er="${params[3]}" local attempts="${params[4]}" sleep 5 echo $job_id } cancel_job() { local jobid=$(get_job_id) curl -sS -X PATCH "http://$flink_rpc/jobs/$jobid?mode=cancel" > /dev/null sleep 3 } get_job_id() { #local jobid=$(curl -sS -X GET "http://$flink_rpc/jobs" | jq '.jobs[0].id' | tr -d '"') local jobid=$(cat ./jobid) echo $jobid } monitor_all_vertexes_network() { local duration=$1 local path=$2 local jobid=$3 local p=$4 local d=$5 mkdir -p $path/network local vertex_ids=($(get_job_vertexes $jobid)) local pods_used=($(for vid in ${vertex_ids[@]} ; do curl -sS -X GET "http://$flink_rpc/jobs/$jobid/vertices/$vid/taskmanagers" | jq '.taskmanagers[] | .host' | tr -d '"' | tr ":" " " | awk {'print $1'} ; done)) for di in $(seq 0 $((d+2-1))); do for pi in $(seq 0 $((p-1))); do . ./monitor_network.sh $duration ${pods_used[$((di*p + pi))]} >> $path/network/network-$di-$pi & done done local all_pods=($(kubectl get pods | grep taskmanager | awk {'print $1'})) local standby_tms=$(echo ${pods_used[@]} ${all_pods[@]} | tr ' ' '\n' | sort | uniq -u ) for x in ${standby_tms[@]} ; do . ./monitor_network.sh $duration $x >> $path/network/network-$x & done } run_experiment() { local jobstr=$1 local path=$2 IFS=";" read -r -a params <<< "${jobstr}" local q="${params[0]}" local p="${params[1]}" local kd="${params[2]}" local er="${params[3]}" local attempts="${params[4]}" clear_make_topics $p echo "Running publisher" timeout $((duration + 35)) bash -c "./nexmark-publisher.sh $system $q 5 $kafka_bootstrap $er" & sleep 5 echo "Running Job" timeout $((duration + 30)) bash -c "./nexmark-job.sh $system $q $p $kafka_bootstrap" & sleep 30 sleep $inittime jobid=$(get_job_id) local vertex_ids=($(get_job_vertexes $jobid)) local resolution=2 monitor_all_vertexes_network $duration $path/$setting $jobid $p $d 2> /dev/null >&2 python3 ./endtoendlatency/Main.py -k $kafka_ext -o $output_topic -r $resolution -p $p -d $duration -mps 1 -t false > $path/$setting/latency & python3 ./throughput-measurer/Main.py $duration 1 $kafka_ext $output_topic verbose > $path/$setting/throughput & echo "Single Kill" >&2 sleep $timetokill kill_taskmanager $jobid $path/$setting $kd 0 $p sleep $(( duration - timetokill )) echo "Saving logs" local jobmanager=$(kubectl get pods | grep jobmanager | awk '{print $1}') local new_host=$(get_vertex_host $jobid "${vertex_ids[$kd]}" 0) local vertex_ids=($(get_job_vertexes $jobid)) local pods=($(for vid in ${vertex_ids[@]} ; do curl -sS -X GET "http://$flink_rpc/jobs/$jobid/vertices/$vid/taskmanagers" | jq '.taskmanagers[] | .host' | tr -d '"' | tr ":" " " | awk {'print $1'} ; done)) mkdir -p $path/$setting/logs for pod in ${pods[@]}; do kubectl logs $pod > $path/$setting/logs/$pod done for i in $(kubectl get pods | grep flink | grep jobm | awk {'print $1'}) ; do kubectl logs $i > $path/$setting/logs/$i ; done echo "Canceling the job with id $jobid" cancel_job } echo "Beggining experiments" experiment_number=0 for jobstr in "${work_queue[@]}" do IFS=";" read -r -a params <<< "${jobstr}" q="${params[0]}" p="${params[1]}" kd="${params[2]}" er="${params[3]}" attempts="${params[4]}" mkdir -p $results/experiment-$experiment_number path=$results/experiment-$experiment_number mkdir -p $path echo "Run experiment configuration:" echo " System: $system" echo " Query: $q" echo " Par: $p" echo " KD: $kd" echo " ER: $er" run_experiment "${jobstr}" $path kubectl delete pod $(kubectl get pods | grep flink | awk {'print $1'}) sleep 4 experiment_number=$((experiment_number + 1)) done
b3345a715eaa4b128dd23e039026af5ad0df03d6
[ "Markdown", "Python", "Shell" ]
18
Shell
delftdata/flink-test-scripts
75958820e7b1127ddd12c1199bec1a140aea311c
741de6c583a9a4ca95bd26b32a62a1a2f1d6dc3f
refs/heads/master
<repo_name>DorGetter/We-Watch---S.E.-project<file_sep>/app/src/main/java/com/example/signingup/Movie.java package com.example.signingup; import java.util.ArrayList; import java.util.Collection; public class Movie { private String MovieName ; private String MovieID ; private Genre genre ; private String MovieUrl ; private Collection<String> likes = new ArrayList<>(); private Collection<String> OwnBy = new ArrayList<>(); public Movie(){} public String getMovieName() { return MovieName; } public void setMovieName(String movieName) { MovieName = movieName; } public String getMovieID() { return MovieID; } public void setMovieID(String movieID) { MovieID = movieID; } public Genre getGenre() { return genre; } public void setGenre(Genre genre) { this.genre = genre; } public Collection<String> getLikes() { return likes; } public void setLikes(Collection<String> likes) { this.likes = likes; } public Collection<String> getOwnBy() { return OwnBy; } public void setOwnBy(Collection<String> ownBy) { OwnBy = ownBy; } } <file_sep>/app/src/main/java/com/example/signingup/ProfileUser.java package com.example.signingup; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; public class ProfileUser extends AppCompatActivity implements View.OnClickListener { private FirebaseUser user; private DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");; Button moviesLibButton,feedButton,FriendsButton,myActivityButton,logOut; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile_user); //initializing objects. user = FirebaseAuth.getInstance().getCurrentUser(); final TextView greetingTextView = (TextView) findViewById(R.id.greeting); feedButton = (Button) findViewById(R.id.FeedButton) ; myActivityButton = (Button) findViewById(R.id.myActivityButton) ; moviesLibButton = (Button) findViewById(R.id.MoviesButton) ; FriendsButton = (Button) findViewById(R.id.FriendsButton) ; logOut = (Button) findViewById(R.id.signOut) ; feedButton .setOnClickListener(this); myActivityButton .setOnClickListener(this); moviesLibButton .setOnClickListener(this); FriendsButton .setOnClickListener(this); logOut .setOnClickListener(this); // greeting the User (Top Left write user name) reference.child(user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { User userProfile = snapshot.getValue(User.class); if( userProfile != null){ String fullName = userProfile.getFullName(); greetingTextView.setText("Hello "+ fullName); } } @Override public void onCancelled(@NonNull DatabaseError error) { Toast.makeText(ProfileUser.this,"Something wrong happened!",Toast.LENGTH_LONG); } }); } /** * switch case for buttons. * @param view - current view */ @Override public void onClick(View view) { switch(view.getId()){ case R.id.FeedButton: startActivity(new Intent(this,Feed.class)); break; case R.id.FriendsButton: break; case R.id.MoviesButton: startActivity(new Intent(this,VOD.class)); break; case R.id.myActivityButton: break; case R.id.signOut: startActivity(new Intent( this,MainActivity.class)); break; } } }
dcc76c5f46eebc7bca5fc9f001aef1cdf8d309d7
[ "Java" ]
2
Java
DorGetter/We-Watch---S.E.-project
3efbd890668640eb7f82cfe573acd43f6602acb8
7f67b3f782f19e3c77cac145b5aa60eb932d54f3
refs/heads/master
<repo_name>lanchongyizu/cri-containerd<file_sep>/cmd/cri-containerd/options/options.go /* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package options import ( "flag" "github.com/containerd/containerd" "github.com/spf13/pflag" ) // CRIContainerdOptions contains cri-containerd command line options. type CRIContainerdOptions struct { // SocketPath is the path to the socket which cri-containerd serves on. SocketPath string // RootDir is the root directory path for managing cri-containerd files // (metadata checkpoint etc.) RootDir string // PrintVersion indicates to print version information of cri-containerd. PrintVersion bool // ContainerdEndpoint is the containerd endpoint path. ContainerdEndpoint string // ContainerdSnapshotter is the snapshotter used by containerd. ContainerdSnapshotter string // NetworkPluginBinDir is the directory in which the binaries for the plugin is kept. NetworkPluginBinDir string // NetworkPluginConfDir is the directory in which the admin places a CNI conf. NetworkPluginConfDir string // StreamServerAddress is the ip address streaming server is listening on. StreamServerAddress string // StreamServerPort is the port streaming server is listening on. StreamServerPort string // CgroupPath is the path for the cgroup that cri-containerd is placed in. CgroupPath string // EnableSelinux indicates to enable the selinux support EnableSelinux bool } // NewCRIContainerdOptions returns a reference to CRIContainerdOptions func NewCRIContainerdOptions() *CRIContainerdOptions { return &CRIContainerdOptions{} } // AddFlags adds cri-containerd command line options to pflag. func (c *CRIContainerdOptions) AddFlags(fs *pflag.FlagSet) { fs.StringVar(&c.SocketPath, "socket-path", "/var/run/cri-containerd.sock", "Path to the socket which cri-containerd serves on.") fs.StringVar(&c.RootDir, "root-dir", "/var/lib/cri-containerd", "Root directory path for cri-containerd managed files (metadata checkpoint etc).") fs.StringVar(&c.ContainerdEndpoint, "containerd-endpoint", "/run/containerd/containerd.sock", "Path to the containerd endpoint.") fs.StringVar(&c.ContainerdSnapshotter, "containerd-snapshotter", containerd.DefaultSnapshotter, "Snapshotter used by containerd.") fs.BoolVar(&c.PrintVersion, "version", false, "Print cri-containerd version information and quit.") fs.StringVar(&c.NetworkPluginBinDir, "network-bin-dir", "/opt/cni/bin", "The directory for putting network binaries.") fs.StringVar(&c.NetworkPluginConfDir, "network-conf-dir", "/etc/cni/net.d", "The directory for putting network plugin configuration files.") fs.StringVar(&c.StreamServerAddress, "stream-addr", "", "The ip address streaming server is listening on. Default host interface is used if this is empty.") fs.StringVar(&c.StreamServerPort, "stream-port", "10010", "The port streaming server is listening on.") fs.StringVar(&c.CgroupPath, "cgroup-path", "", "The cgroup that cri-containerd is part of. By default cri-containerd is not placed in a cgroup") fs.BoolVar(&c.EnableSelinux, "selinux-enabled", false, "Enable selinux support.") } // InitFlags must be called after adding all cli options flags are defined and // before flags are accessed by the program. Ths fuction adds flag.CommandLine // (the default set of command-line flags, parsed from os.Args) and then calls // pflag.Parse(). func InitFlags() { pflag.CommandLine.AddGoFlagSet(flag.CommandLine) pflag.Parse() } <file_sep>/pkg/store/container/status_test.go /* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package container import ( "errors" "testing" "time" assertlib "github.com/stretchr/testify/assert" "k8s.io/kubernetes/pkg/kubelet/apis/cri/v1alpha1/runtime" ) func TestContainerState(t *testing.T) { for c, test := range map[string]struct { status Status state runtime.ContainerState }{ "unknown state": { status: Status{}, state: runtime.ContainerState_CONTAINER_UNKNOWN, }, "created state": { status: Status{ CreatedAt: time.Now().UnixNano(), }, state: runtime.ContainerState_CONTAINER_CREATED, }, "running state": { status: Status{ CreatedAt: time.Now().UnixNano(), StartedAt: time.Now().UnixNano(), }, state: runtime.ContainerState_CONTAINER_RUNNING, }, "exited state": { status: Status{ CreatedAt: time.Now().UnixNano(), FinishedAt: time.Now().UnixNano(), }, state: runtime.ContainerState_CONTAINER_EXITED, }, } { t.Logf("TestCase %q", c) assertlib.Equal(t, test.state, test.status.State()) } } func TestStatus(t *testing.T) { testID := "test-id" testStatus := Status{ CreatedAt: time.Now().UnixNano(), } updateStatus := Status{ CreatedAt: time.Now().UnixNano(), StartedAt: time.Now().UnixNano(), } updateErr := errors.New("update error") assert := assertlib.New(t) t.Logf("simple store and get") s, err := StoreStatus(testID, testStatus) assert.NoError(err) old := s.Get() assert.Equal(testStatus, old) t.Logf("failed update should not take effect") err = s.Update(func(o Status) (Status, error) { o = updateStatus return o, updateErr }) assert.Equal(updateErr, err) assert.Equal(testStatus, s.Get()) t.Logf("successful update should take effect") err = s.Update(func(o Status) (Status, error) { o = updateStatus return o, nil }) assert.NoError(err) assert.Equal(updateStatus, s.Get()) t.Logf("successful update should not affect existing snapshot") assert.Equal(testStatus, old) // TODO(random-liu): Test Load and Delete after disc checkpoint is added. } <file_sep>/hack/install-deps.sh #!/bin/bash # Copyright 2017 The Kubernetes Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Dependencies: # runc: # - libseccomp-dev(Ubuntu,Debian)/libseccomp-devel(Fedora, CentOS, RHEL). Note that # libseccomp in ubuntu <=trusty and debian <=jessie is not new enough, backport # is required. # - libapparmor-dev(Ubuntu,Debian)/libapparmor-devel(Fedora, CentOS, RHEL) # containerd: # - btrfs-tools(Ubuntu,Debian)/btrfs-progs-devel(Fedora, CentOS, RHEL) set -o errexit set -o nounset set -o pipefail ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"/.. . ${ROOT}/hack/versions RUNC_PKG=github.com/opencontainers/runc CNI_PKG=github.com/containernetworking/plugins CNI_DIR=/opt/cni CNI_CONFIG_DIR=/etc/cni/net.d CONTAINERD_PKG=github.com/containerd/containerd # Check GOPATH if [[ -z "${GOPATH}" ]]; then echo "GOPATH is not set" exit 1 fi # For multiple GOPATHs, keep the first one only GOPATH=${GOPATH%%:*} # Install runc go get -d ${RUNC_PKG}/... cd ${GOPATH}/src/${RUNC_PKG} git fetch --all git checkout ${RUNC_VERSION} BUILDTAGS=${BUILDTAGS:-seccomp apparmor} make BUILDTAGS="$BUILDTAGS" sudo make install which runc # Install cni go get -d ${CNI_PKG}/... cd ${GOPATH}/src/${CNI_PKG} git fetch --all git checkout ${CNI_VERSION} ./build.sh sudo mkdir -p ${CNI_DIR} sudo cp -r ./bin ${CNI_DIR} sudo mkdir -p ${CNI_CONFIG_DIR} sudo bash -c 'cat >'${CNI_CONFIG_DIR}'/10-containerd-net.conflist <<EOF { "cniVersion": "0.3.1", "name": "containerd-net", "plugins": [ { "type": "bridge", "bridge": "cni0", "isGateway": true, "ipMasq": true, "ipam": { "type": "host-local", "subnet": "10.88.0.0/16", "routes": [ { "dst": "0.0.0.0/0" } ] } }, { "type": "portmap", "capabilities": {"portMappings": true} } ] } EOF' # Install containerd go get -d ${CONTAINERD_PKG}/... cd ${GOPATH}/src/${CONTAINERD_PKG} git fetch --all git checkout ${CONTAINERD_VERSION} make sudo make install which containerd which containerd-shim <file_sep>/pkg/store/container/status.go /* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package container import ( "sync" "k8s.io/kubernetes/pkg/kubelet/apis/cri/v1alpha1/runtime" ) // TODO(random-liu): Handle versioning. // TODO(random-liu): Add checkpoint support. // version is current version of container status. const version = "v1" // nolint // versionedStatus is the internal used versioned container status. // nolint type versionedStatus struct { // Version indicates the version of the versioned container status. Version string Status } // Status is the status of a container. type Status struct { // Pid is the init process id of the container. Pid uint32 // CreatedAt is the created timestamp. CreatedAt int64 // StartedAt is the started timestamp. StartedAt int64 // FinishedAt is the finished timestamp. FinishedAt int64 // ExitCode is the container exit code. ExitCode int32 // CamelCase string explaining why container is in its current state. Reason string // Human-readable message indicating details about why container is in its // current state. Message string // Removing indicates that the container is in removing state. // This field doesn't need to be checkpointed. // TODO(random-liu): Reset this field to false during state recoverry. Removing bool } // State returns current state of the container based on the container status. func (c Status) State() runtime.ContainerState { if c.FinishedAt != 0 { return runtime.ContainerState_CONTAINER_EXITED } if c.StartedAt != 0 { return runtime.ContainerState_CONTAINER_RUNNING } if c.CreatedAt != 0 { return runtime.ContainerState_CONTAINER_CREATED } return runtime.ContainerState_CONTAINER_UNKNOWN } // UpdateFunc is function used to update the container status. If there // is an error, the update will be rolled back. type UpdateFunc func(Status) (Status, error) // StatusStorage manages the container status with a storage backend. type StatusStorage interface { // Get a container status. Get() Status // Update the container status. Note that the update MUST be applied // in one transaction. // TODO(random-liu): Distinguish `UpdateSync` and `Update`, only // `UpdateSync` should sync data onto disk, so that disk operation // for non-critical status change could be avoided. Update(UpdateFunc) error // Delete the container status. // Note: // * Delete should be idempotent. // * The status must be deleted in one trasaction. Delete() error } // TODO(random-liu): Add factory function and configure checkpoint path. // StoreStatus creates the storage containing the passed in container status with the // specified id. // The status MUST be created in one transaction. func StoreStatus(id string, status Status) (StatusStorage, error) { return &statusStorage{status: status}, nil // TODO(random-liu): Create the data on disk atomically. } // LoadStatus loads container status from checkpoint. func LoadStatus(id string) (StatusStorage, error) { // TODO(random-liu): Load container status from disk. return nil, nil } type statusStorage struct { sync.RWMutex status Status } // Get a copy of container status. func (m *statusStorage) Get() Status { m.RLock() defer m.RUnlock() return m.status } // Update the container status. func (m *statusStorage) Update(u UpdateFunc) error { m.Lock() defer m.Unlock() newStatus, err := u(m.status) if err != nil { return err } // TODO(random-liu) *Update* existing status on disk atomically, // return error if checkpoint failed. m.status = newStatus return nil } // Delete deletes the container status from disk atomically. func (m *statusStorage) Delete() error { // TODO(random-liu): Rename the data on the disk, returns error // if fails. No lock is needed because file rename is atomic. // TODO(random-liu): Cleanup temporary files generated, do not // return error. return nil } <file_sep>/hack/test-utils.sh #!/bin/bash # Copyright 2017 The Kubernetes Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"/.. . ${ROOT}/hack/versions # start_cri_containerd starts containerd and cri-containerd. start_cri_containerd() { local report_dir=$1 if [ ! -x ${ROOT}/_output/cri-containerd ]; then echo "cri-containerd is not built" exit 1 fi # Start containerd if [ ! -x "$(command -v containerd)" ]; then echo "containerd is not installed, please run hack/install-deps.sh" exit 1 fi kill_cri_containerd sudo containerd -l debug &> ${report_dir}/containerd.log & # Wait for containerd to be running by using the containerd client ctr to check the version # of the containerd server. Wait an increasing amount of time after each of five attempts local MAX_ATTEMPTS=5 local attempt_num=1 until sudo ctr version &> /dev/null || (( attempt_num == MAX_ATTEMPTS )) do echo "attempt $attempt_num to connect to containerd failed! Trying again in $attempt_num seconds..." sleep $(( attempt_num++ )) done # Start cri-containerd sudo ${ROOT}/_output/cri-containerd --alsologtostderr --v 4 &> ${report_dir}/cri-containerd.log & } # kill_cri_containerd kills containerd and cri-containerd. kill_cri_containerd() { sudo pkill containerd }
80749b689a122758b0a3b59770cd5cbae2b82973
[ "Go", "Shell" ]
5
Go
lanchongyizu/cri-containerd
86e8a24977ef20a4fe968961d261d2d51892f9b5
83fdc7da985d3ba86e11cacc749915d7b90e7a41
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Book; class BookController extends Controller { public function index() { $books = Book::all(); return view('book.index', compact('books')); } public function show($id) { $book = Book::find($id); return view('book.show', compact('book')); } public function create() { return view('book.create'); } public function store(Request $request) { $book = [ "title" => $request->title, "author" => $request->author, "year" => $request->year ]; Book::create($book); return redirect()->route('book.index'); } public function edit($id) { $book = Book::find($id); return view('book.edit', compact('book')); } public function update($id, Request $request) { $book = Book::find($id); $newBook = [ "title" => $request->title, "author" => $request->author, "year" => $request->year ]; $book->update($newBook); return redirect()->route('book.index'); } public function destroy($id) { $book = Book::find($id); $book->delete(); return redirect()->route('book.index'); } }
fcb3503546defaab2a901e990991a1cb524f4fea
[ "PHP" ]
1
PHP
afrijaldz/laravel-crud-basic
db6f6310282cfba6aed32de18536f76a50f2fe03
8a18a2a2baf614141ec88f942bb4c12cfff622b5
refs/heads/master
<file_sep>/** * Created by gaoqikai on 7/29/16. */ console.log("got here"); var page = require('webpage').create(); page.onConsoleMessage = function(msg) { console.log(msg); }; page.open("http://id.qlteacher.com/?do=logout", function(status) { if ( status === "success" ) { page.evaluate(function() { document.querySelector("#username").value = "email"; document.querySelector("#userpd").value = "pass"; console.log(document.querySelector("#btn-login")); document.querySelector("#btn-login").submit(); console.log("Login submitted!"); }); window.setTimeout(function () { page.render('colorwheel.png'); phantom.exit(); }, 5000); } });<file_sep>/** * Created by gaoqikai on 7/29/16. */ console.log(new Date(1469769590100));<file_sep>/** * Created by ???? on 2015/9/18. */ var learningDirectives = angular.module("CourseRescourseDirectives", ["BaseServices", 'FrameworkServices', 'LearningServices', 'ProjectServices']); learningDirectives.directive("courseRes", ["$q", "$stateParams", "LayoutService", "LearningService", "ProjectService", "PermissionService", "CurrentUser", "CurrentProject", "Base", function ($q, $stateParams, LayoutService, LearningService, ProjectService, PermissionService, CurrentUser, CurrentProject, Base) { return { restrict: 'E', scope: {}, replace: true, templateUrl: function () { return LayoutService.getFunctionModuleTmplAddress('course-res'); }, link: function (scope, element, attr) { //判断是否国培评审项目 scope.isGpps = Base.getProjectId().substr(0,4).toLocaleLowerCase()=="gpps"; //????? ????????? scope.comboLoading = true; //??????????????????? var allPackage = PermissionService.isAllow('learning', 'all-package-view'); var allCoursePackage = PermissionService.isAllow('learning', 'all-course-package-view'); var isStudy = false; //PermissionService.isAllow('learning', 'study'); scope.isStudy = isStudy; var courses = {}; if (allCoursePackage) { scope.subjectCodes = CurrentProject.project.subjects; scope.currentSubjectId = $stateParams.subjectId || scope.subjectCodes[0].subjectCode; courses = ProjectService.queryCourseGroupAndCourseByCourse({courseId: scope.currentSubjectId}); } else if (allPackage) { courses = ProjectService.queryCourseGroupAndCourseByCourse({courseId: CurrentUser.subjectCode}); } else { courses = ProjectService.queryCourseGroupAndCourseByCourse({courseId: CurrentUser.subjectCode}); } //??????????? var systemDateTime = ProjectService.getSystemDateTime(); $q.all([courses, systemDateTime]).then(function (results) { //????? var systemTime = results[1].time; if (isStudy) { //?????????? ProjectService.setCoursesOpenStatus(results[0][0], systemTime); } scope.courses = results[0]; scope.currentPackageId = results[0][0].id; //???????????? scope.comboLoading = false; }, function (error) { var data = error.data; //????????? scope.comboErrorMessage = data.message; //?????????? scope.comboLoading = false; }); scope.setCurrentPackage = function (id) { scope.currentPackageId = id; }; } } }]); learningDirectives.directive("courseResSection", ["$timeout","$stateParams", "$q", "LayoutService", "PermissionService", "LearningService", "CurrentUser", "ProjectService", "Base", function ($timeout,$stateParams, $q, LayoutService, PermissionService, LearningService, CurrentUser, ProjectService, Base) { return { restrict: 'E', scope: {}, replace: true, templateUrl: function () { return LayoutService.getFunctionModuleTmplAddress('course-res-section'); }, link: function (scope, element, attr) { //??????????? var isStudy = false; //PermissionService.isAllow('learning', 'study'); //???????????? scope.sectionLoading = true; var courses = LearningService.getCourseSectionAndGroup({courseId: $stateParams.courseId}); //?????????????scope scope.isStudy = isStudy; scope.showTitle = PermissionService.isAllow('learning', 'study'); //??????? var func = [courses]; //???????????? if (isStudy) { var learningRecod = LearningService.queryLearningRecodeByCourse({courseId: $stateParams.courseId}); //???????????????? func.push(learningRecod); } //??????? $q.all(func).then(function (results) { // :courseId/:sectionId/groupId/:rescoureId scope.course = results[0] ; var learningRecord = results[1] || {}; if(angular.isUndefined(learningRecord.s_index)){ learningRecord = {s_index : 0}; //learningRecord.s_index = 0; } //??????sectionId if (!$stateParams.sectionId) { $stateParams.sectionId = scope.course.section[0].id; } //????????? scope.sectionLoading = false; if ($stateParams.sectionId) { //??????? scope.resourceLoading = true; //???sectionID scope.currentSectionId = $stateParams.sectionId; var r = LearningService.queryCourseGroupResource({sectionId: $stateParams.sectionId}); $q.when(r).then(function (resource) { // console.log(scope.course); //????????????????? LearningService.createSectionResourceReference(scope.course.section, resource, $stateParams.sectionId,'courseres'); //???????????? ?????????? if (isStudy) { var pass = LearningService.learningPass({courseId : $stateParams.courseId,sectionCount : learningRecord.s_index+1,groupCount :0,rescoureCount : 0}); $q.when(pass).then(function(pass){ learningRecord.pass = pass; //????????? LearningService.LearningProgress(scope.course, learningRecord); //??????????? function check(){ function learning(){ var learningStatus = LearningService.checkLearningPace(scope.course); if(learningStatus){ //???????? LearningService.setLearningProgress(scope.course,learningStatus.resouceId,learningStatus.status); }else{ //???????????? LearningService.openNextResource(scope.course); } } function timer(){ //??????? ???? if(window.location.hash.indexOf('training/learning') > -1){ $timeout(function(){ learning(); timer(); },10000); } } learning(); timer(); } //??????? check(); }); } //?????????? scope.resourceLoading = false; }, function (error) { var data = error.data; //????????? scope.resourceErrorMessage = data.message; //?????????? scope.resourceLoading = false; }); } }, function (error) { var data = error.data; //????????? scope.sectionErrorMessage = data.message; //?????????? scope.sectionLoading = false; }); //????????? scope.setFinish = function (res) { //res.finish = 2; }; } } }]); learningDirectives.directive("courseResourceText", ["$stateParams", "$q", "LayoutService", "LearningService", "ProjectService", "Base", function ($stateParams, $q, LayoutService, LearningService, ProjectService, Base) { return { restrict: 'E', scope: {}, replace: true, templateUrl: function () { return LayoutService.getFunctionModuleTmplAddress('learning-text-res'); }, link: function (scope, element, attr) { //?????????? scope.loading = true; var resource = LearningService.getCourseResourceByType( { resourceId: $stateParams.resourceId, sectionIndex: $stateParams.sectionIndex, activityGroupIndex: $stateParams.activityGroupIndex, activityIndex: $stateParams.activityIndex }); $q.when(resource).then(function (activity) { //?????????? scope.loading = false; scope.activity = activity; //??????? // LearningService.recordLearningPace(activity); }, function (error) { var data = error.data; //????????? scope.errorMessage = data.message; //?????????? scope.loading = false; }); } } }]); learningDirectives.directive("courseResourceLink", ["$stateParams", "$q", "LayoutService", "LearningService", "ProjectService", "Base", function ($stateParams, $q, LayoutService, LearningService, ProjectService, Base) { return { restrict: 'E', scope: {}, replace: true, templateUrl: function () { return LayoutService.getFunctionModuleTmplAddress('learning-link-res'); }, link: function (scope, element, attr) { //?????????? scope.loading = true; var resource = LearningService.getCourseResourceByType( { resourceId: $stateParams.resourceId, sectionIndex: $stateParams.sectionIndex, activityGroupIndex: $stateParams.activityGroupIndex, activityIndex: $stateParams.activityIndex }); $q.when(resource).then(function (activity) { //?????????? scope.loading = false; scope.activity = activity; //??????? //LearningService.recordLearningPace(activity); //?????? window.location.href = activity.refUrl; }, function (error) { var data = error.data; //????????? scope.errorMessage = data.message; //?????????? scope.loading = false; }); } } }]); learningDirectives.directive("courseResourceHomework", ["$stateParams", "$q", "LayoutService", "LearningService", "ProjectService", "Base", function ($stateParams, $q, LayoutService, LearningService, ProjectService, Base) { return { restrict: 'E', scope: {}, replace: true, templateUrl: function () { return LayoutService.getFunctionModuleTmplAddress('learning-homework-res'); }, link: function (scope, element, attr) { //?????????? scope.loading = true; var resource = LearningService.getCourseResourceByType( { resourceId: $stateParams.resourceId, sectionIndex: $stateParams.sectionIndex, activityGroupIndex: $stateParams.activityGroupIndex, activityIndex: $stateParams.activityIndex }); $q.when(resource).then(function (activity) { //?????????? scope.loading = false; scope.activity = activity; //??????? // LearningService.recordLearningPace(activity); }, function (error) { var data = error.data; //????????? scope.errorMessage = data.message; //?????????? scope.loading = false; }); } } }]); learningDirectives.directive("courseResourceDiscussion", ["$stateParams", "$q", "LayoutService", "LearningService", "ProjectService", "Base", function ($stateParams, $q, LayoutService, LearningService, ProjectService, Base) { return { restrict: 'E', scope: {}, replace: true, templateUrl: function () { return LayoutService.getFunctionModuleTmplAddress('learning-discussion-res'); }, link: function (scope, element, attr) { //?????????? scope.loading = true; var resource = LearningService.getCourseResourceByType( { resourceId: $stateParams.resourceId, sectionIndex: $stateParams.sectionIndex, activityGroupIndex: $stateParams.activityGroupIndex, activityIndex: $stateParams.activityIndex }); $q.when(resource).then(function (activity) { //?????????? scope.loading = false; scope.activity = activity; //??????? // LearningService.recordLearningPace(activity); }, function (error) { var data = error.data; //????????? scope.errorMessage = data.message; //?????????? scope.loading = false; }); } } }]); learningDirectives.directive("courseResourceTest", ["$stateParams", "$q", "LayoutService", "LearningService", "ProjectService", "Base", "CurrentUser", "CurrentProject","PermissionService", function ($stateParams, $q, LayoutService, LearningService, ProjectService, Base, CurrentUser, CurrentProject,PermissionService) { return { restrict: 'E', scope: {}, replace: true, templateUrl: function () { return LayoutService.getFunctionModuleTmplAddress('course-res-test-res'); }, link: function (scope, element, attr) { scope.loading = true; scope.noSubmit = true; scope.isSubmit = false; //??????? scope.isSubmit = PermissionService.isAllow("courseres","testSubmit"); var resource = LearningService.getCourseResourceByType( { resourceId: $stateParams.resourceId, sectionIndex: $stateParams.sectionIndex, activityGroupIndex: $stateParams.activityGroupIndex, activityIndex: $stateParams.activityIndex }); $q.when(resource).then(function (activity) { scope.activity = activity; if (activity && activity.refUrl.length > 0) { var test = LearningService.getResourceStdTest({id: activity.refUrl}); $q.when(test).then(function (mTest) { scope.loading = false; scope.test = mTest; //??????? // LearningService.recordLearningPace(scope.activity,true,false); }, function (error) { var data = error.data; //????????? scope.errorMessage = data.message; //?????????? scope.loading = false; }); } }, function (error) { var data = error.data; //????????? scope.errorMessage = data.message; //?????????? scope.loading = false; }); function verification() { var msg = {result: true}; var result = {}; var actStdTestAnswers = []; var score = 0; var optionContent = []; for (var questionIndex = 0; questionIndex < scope.test.actStdTestProlems.length; questionIndex++) { var question = scope.test.actStdTestProlems[questionIndex]; question.error = null; var checkedCount = 0; var answer = []; for (var i = 0; i < question.actStdTestOpts.length; i++) { var options = []; var option = question.actStdTestOpts[i]; if (!question.multiple) { if (typeof(question.checked) != 'undefined' && question.checked == option.title) { option.checked = true; } else { option.checked = false; } } if (option.checked) { checkedCount++; answer.push(option.title); } } if (checkedCount < question.mincount) { question.error = Base.stringFormat("最少选择{0}项。", question.mincount); msg.result = false; msg.error = Base.stringFormat("问题{0}:{1} 最少选择{2}项。", questionIndex + 1, question.title, question.mincount); // alert(); return msg; } if (checkedCount > question.maxcount) { question.error = Base.stringFormat("最多选择{0}项。", question.maxcount); msg.result = false; msg.error = Base.stringFormat("问题{0}:{1} 最多选择{2}项。", questionIndex + 1, question.title, question.maxcount); return msg; } var isCorrect = answer.join('') == question.correctanswer; if (isCorrect) { score += parseInt(question.score); } actStdTestAnswers.push({ correctanswer: question.correctanswer, flag: isCorrect, score: question.score, sortorder: questionIndex }); options.push(option.id); options.push(answer.join('')); optionContent.push(options.join("^")); result.optionContent = optionContent.join("|"); } result.actStdTestAnswers = actStdTestAnswers; result.score = score; msg.data = result; return msg; } scope.submiting = function () { scope.submitLoading = true; scope.resultErrorMessage = null; scope.score = null; var result = verification(); //???????? if (result && !result.result && !result.data) { scope.resultErrorMessage = result.error; scope.submitLoading = false; return false; } result = result.data; result.authorId = CurrentUser.id; result.courseId = $stateParams.resourceId; result.mainId = scope.activity.refUrl; result.consumerId = CurrentProject.project.code; // console.log(scope.activity.id); angular.forEach(scope.test.actStdTestProlems, function (question, index) { question.result = result.actStdTestAnswers[index]; question.result.flag = question.result.flag ? 2 : 1; }); var urlParam = { s_index: $stateParams.sectionIndex, g_index: $stateParams.activityGroupIndex, a_index: $stateParams.activityIndex }; var saveResult = LearningService.saveResourceStdTest(urlParam, result); $q.when(saveResult) .then(function (succesModel) { scope.submitLoading = false; scope.score = result.score; scope.isShowScope = true; //??????? // LearningService.recordLearningPace(scope.activity,true,true); // console.log(result); }, function (error) { var data = error.data; //????????? scope.resultErrorMessage = data.message; //?????????? scope.submitLoading = false; }); } } } }]); learningDirectives.directive("courseResourceSurvey", ["$stateParams", "$q", "LayoutService", "LearningService", "ProjectService", "Base", "CurrentUser", 'CurrentProject', function ($stateParams, $q, LayoutService, LearningService, ProjectService, Base, CurrentUser, CurrentProject) { return { restrict: 'E', scope: {}, replace: true, templateUrl: function () { return LayoutService.getFunctionModuleTmplAddress('course-res-survey-res'); }, link: function (scope, element, attr) { scope.loading = true; scope.noSubmit = true; var resource = LearningService.getCourseResourceByType( { resourceId: $stateParams.resourceId, sectionIndex: $stateParams.sectionIndex, activityGroupIndex: $stateParams.activityGroupIndex, activityIndex: $stateParams.activityIndex }); $q.when(resource).then(function (activity) { scope.activity = activity; if (activity && activity.refUrl.length > 0) { var survey = LearningService.getResourceSurvey({id: activity.refUrl}); $q.when(survey) .then(function (survey) { scope.loading = false; scope.survey = survey; //??????? //LearningService.recordLearningPace(scope.activity,true,true); }, function (error) { var data = error.data; //????????? scope.errorMessage = data.message; //?????????? scope.loading = false; }); } }); function verification() { var msg = {result: true}; var result = {}; // var actStdTestAnswers = []; var score = 0; var optionContent = []; for (var questionIndex = 0; questionIndex < scope.survey.actSurveyProlems.length; questionIndex++) { var question = scope.survey.actSurveyProlems[questionIndex]; question.error = null; var checkedCount = 0; var answer = []; for (var i = 0; i < question.actSurveyOpts.length; i++) { var options = []; var option = question.actSurveyOpts[i]; if (!question.multiple) { if (typeof(question.checked) != 'undefined' && question.checked == option.title) { option.checked = true; } else { option.checked = false; } } if (option.checked) { checkedCount++; answer.push(option.title); } } if (checkedCount < question.mincount) { question.error = Base.stringFormat("???????{0}??", question.mincount); msg.result = false; msg.error = Base.stringFormat("????{0}:{1} ???????{2}??", questionIndex + 1, question.title, question.mincount); // alert(); return msg; } if (checkedCount > question.maxcount) { question.error = Base.stringFormat("??????{0}??", question.maxcount); msg.result = false; msg.error = Base.stringFormat("????{0}:{1} ??????{2}??", questionIndex + 1, question.title, question.maxcount); return msg; } //var isCorrect = answer.join('') == question.correctanswer; //if (isCorrect) { // score += parseInt(question.score); //} //actStdTestAnswers.push({ // correctanswer: question.correctanswer, // flag: isCorrect, // score: question.score, // sortorder: questionIndex //}); options.push(option.id); options.push(answer.join('')); optionContent.push(options.join("^")); result.optionContent = optionContent.join("|"); } //result.actStdTestAnswers = actStdTestAnswers; //result.score = score; msg.data = result; return msg; } scope.submiting = function () { scope.submitLoading = true; scope.resultErrorMessage = null; var result = verification(); //???????? if (result && !result.result && !result.data) { scope.resultErrorMessage = result.error; scope.submitLoading = false; return false; } result = result.data; result.id = scope.activity.id; result.authorId = CurrentUser.id; result.courseId = $stateParams.resourceId; result.mainId = scope.activity.refUrl; result.consumerId = CurrentProject.project.code; var urlParam = { s_index: $stateParams.sectionIndex, g_index: $stateParams.activityGroupIndex, a_index: $stateParams.activityIndex }; var submitSurvey = LearningService.saveResourceSurvey(urlParam, result); $q.when(submitSurvey) .then(function (success) { //?????????? scope.submitLoading = false; scope.score = result.score; //??????? // LearningService.recordLearningPace(scope.activity,true,true); //console.log(success); }, function (error) { var data = error.data; //????????? scope.resultErrorMessage = data.message; //?????????? scope.submitLoading = false; }); } } } }]); learningDirectives.directive("courseResourceVideo", ["$stateParams", "$q", "LayoutService", "LearningService", "ProjectService", "Base", function ($stateParams, $q, LayoutService, LearningService, ProjectService, Base) { return { restrict: 'E', scope: {}, replace: true, templateUrl: function () { if (!!window.ActiveXObject || "ActiveXObject" in window) { //IE??????? return LayoutService.getFunctionModuleTmplAddress('learning-ie-video-res'); } else if (navigator.userAgent.indexOf('Firefox') >= 0) { //???????? return LayoutService.getFunctionModuleTmplAddress('learning-ff-video-res'); } else { //???? return LayoutService.getFunctionModuleTmplAddress('learning-other-video-res'); } }, link: function (scope, element, attr) { scope.resorceNum = 0;//???????? //????????? scope.loading = true; var resource = LearningService.getCourseResourceByType( { resourceId: $stateParams.resourceId, sectionIndex: $stateParams.sectionIndex, activityGroupIndex: $stateParams.activityGroupIndex, activityIndex: $stateParams.activityIndex }); $q.when(resource).then(function (activity) { //??????? scope.loading = false; scope.activity = activity; var getSWF = function ( swfID ) { if (window.document[ swfID ]) { return window.document[ swfID ]; } else if (navigator.appName.indexOf("Microsoft") == -1) { if (document.embeds && document.embeds[ swfID ]) { return document.embeds[ swfID ]; } } else { return document.getElementById( swfID ); } }; //??????? // LearningService.recordLearningPace(activity); var i = 0; var postTime = 5; var ccplay = undefined; /* scope.activity.completionCriteria = {duration:5000}; scope.activity.duration = 280; scope.activity.learning = true; scope.activity.prolems = [ {time:300,title:"测试1",type:1,corrects:["A"],options:[ {title:"A", content:"选项1"}, {title:"B", content:"选项2"}, {title:"C", content:"选项3"} ]}, {time:400,title:"测试2",type:2,corrects:["A","B"],options:[ {title:"A", content:"选项1"}, {title:"B", content:"选项2"}, {title:"C", content:"选项3"} ]} ]; */ if(scope.activity.prolems) scope.activity.prolems = scope.activity.prolems.reverse(); scope.prolemSubmit= function(){ switch(scope.currentProlem.type){ case 1: if(scope.currentProlem.value!=scope.currentProlem.corrects[0]){ alert("回答错误!"); return ; } break; case 2: var valueSize = 0; angular.forEach(scope.currentProlem.options,function(data,index,array){ if(scope.currentProlem.value[data.title]){ valueSize++; } }) if(valueSize!=scope.currentProlem.corrects.length){ valueSize=-1; }else{ angular.forEach(scope.currentProlem.corrects,function(data,index,array){ if(!scope.currentProlem.value[data]){ valueSize = -1; } }) } if(valueSize<0){ alert("回答错误!"); return ; } break; case 3: if(scope.currentProlem.value!=scope.currentProlem.corrects[0]){ alert("回答错误!"); return ; } break; } $("#prolem").modal("hide"); } window.duration = function(){ //$("#survey").html(i); var act = scope.activity; if(scope.ccId) if(act.learning){ if(scope.activity.prolems && scope.activity.prolems.length>0){ while(!scope.currentProlem){ if(scope.activity.prolems.length==0) break; var prolem = scope.activity.prolems.pop(); if(prolem.time>scope.activity.duration){ scope.currentProlem = prolem; if(scope.currentProlem.type==2){ scope.currentProlem.value = {}; } } } } if(scope.currentProlem){ if(ccplay.getPosition()>scope.currentProlem.time){ ccplay.pause(); scope.$digest(); $("#prolem").modal("show"); } } if(ccplay.getPosition()>scope.activity.duration){ scope.activity.duration = parseInt(ccplay.getPosition()); } setTimeout("duration()",postTime*1000); } } window.on_player_stop = function(){ var url = Base.stringFormat("{0}/learning/uact/{1}/{2}/{3}/{4}/{5}", Base.dataApiUri.learning,$stateParams.resourceId,$stateParams.sectionIndex,$stateParams.activityGroupIndex,$stateParams.activityIndex,scope.activity.completionCriteria.duration); $.post(url,{},function(data){ alert('播放完成'); }); } window.on_player_seek = function(from, to){ if(scope.activity.duration<to){ ccplay.seek(from); return false; } } window.on_play_start = function (){ if(scope.activity.duration>0) ccplay.seek(scope.activity.duration); setTimeout("duration()",postTime*1000); } var vid = activity.p2pId.split("||"); $.each(vid, function (i, d) { var ds = d.split("::"); if (ds.length == 1) {//???? scope.hasP2p = openP2P && true; scope.p2pId = ds[0]; } else {//cc??? if (ds[0] == "CC") { scope.hasCC = openCC && true; scope.ccId = ds[1]; } else if (ds[0] == "LETV") { scope.hasLetv = openLETV && true; var uvu = ds[1].split("--"); scope.letvUU = uvu[0]; scope.letvVU = uvu[1]; } } }); if(scope.activity.learning) window.on_cc_player_init = function (vid, objectId) { ccplay = getSWF(objectId); ccplay.setConfig({ on_player_stop:"on_player_stop", on_player_seek:"on_player_seek", on_player_start:"on_play_start", rightmenu_enable:0 }); } $("#prolem").on('hide.bs.modal',function(){ var url = Base.stringFormat("{0}/learning/uact/{1}/{2}/{3}/{4}/{5}", Base.dataApiUri.learning,$stateParams.resourceId,$stateParams.sectionIndex,$stateParams.activityGroupIndex,$stateParams.activityIndex,scope.currentProlem.time); $.post(url,{},function(data){ scope.currentProlem = undefined; ccplay.resume(); }); }); if (scope.hasP2p) { scope.resorceNum += 1; } if (scope.hasCC) { scope.resorceNum += 1; } if (scope.hasLetv) { scope.resorceNum += 1; } //p2p scope.playP2p = function () { /*$("#ccflashcontent").html(""); $("#letvflashcontent").html(""); scope.showCC = false; scope.showP2p = true; scope.showLetv = false; $("#p2pLocal").html("<img id=\"videoControl\" style=\"display: none\" src=\"http://127.0.0.1:18582/images/logo.gif\">"); $("#videoControl").load(function () { var fileName = "/videos/" + scope.p2pId + ".flv"; $.ajax({ type: "get", async: false, url: "http://127.0.0.1:18582/state.json?file=" + fileName, dataType: "jsonp", jsonp: "callback", jsonpCallback: "serverState", success: function (json) { if (json.state == 0) { PlayP2P_Local(); } else { PlayP2P_Server(scope.p2pId); } }, error: function () { PlayP2P_Server(scope.p2pId); } } ); }).error(function () { PlayP2P_Server(scope.p2pId); });*/ }; //cc scope.playCC = function () { $("#ccflashcontent").html(""); $("#letvflashcontent").html(""); scope.showCC = true; scope.showP2p = false; scope.showLetv = false; $("#ccflashcontent").html('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="960" height="600" id="cc_' + scope.ccId + '">' + '<param name="movie" value="http://p.bokecc.com/flash/single/1258A40FD2666E07_' + scope.ccId + '_false_D3DC3A3A0828EC6B_1/player.swf"/>' + '<param name="allowFullScreen" value="true"/>' + '<param name="allowScriptAccess" value="always"/>' + '<param value="transparent" name="wmode"/>' + '<embed src="http://p.bokecc.com/flash/single/1258A40FD2666E07_' + scope.ccId + '_false_D3DC3A3A0828EC6B_1/player.swf" width="960" height="600" name="cc_' + scope.ccId + '" allowFullScreen="true" wmode="transparent" allowScriptAccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"/></object>'); }; //Letv scope.playLetv = function () { /* $("#ccflashcontent").html(""); $("#letvflashcontent").html(""); scope.showCC = false; scope.showLetv = true; scope.showP2p = false; $("#letvflashcontent").html('<embed src="http://yuntv.letv.com/bcloud.swf" allowFullScreen="true" quality="high" width="960" height="600" align="middle" allowScriptAccess="always" flashvars="uu=' + scope.letvUU + '&vu=' + scope.letvVU + '&auto_play=1&gpcflag=1&width=960&height=600" type="application/x-shockwave-flash"></embed>'); */ }; //???? if (scope.hasCC) { scope.showCC = true;//??????????????div?????? scope.showP2p = false; scope.showLetv = false; var runItal = setInterval(function () { if ($("#ccflashcontent").length == 1) { scope.playCC(); clearInterval(runItal); } }, 300); } else if (scope.hasLetv) { scope.showCC = false; scope.showP2p = false; scope.showLetv = true;//??????????????div?????? var runItal = setInterval(function () { if ($("#letvflashcontent").length == 1) { scope.playLetv(); clearInterval(runItal); } }, 300); } else { scope.playP2p(); } }, function (error) { var data = error.data; //????????? scope.errorMessage = data.message; //?????????? scope.loading = false; }); } }; function PlayP2P_Server(id) { if (!!window.ActiveXObject || "ActiveXObject" in window) { //IE??????? PlayP2P_IE_Server(id); } else if (navigator.userAgent.indexOf('Firefox') >= 0) { //???????? PlayP2PFF_FF_Server(id); } else { //???? return LayoutService.getFunctionModuleTmplAddress('learning-other-video'); } } function PlayP2P_Local(id) { //????P2P???? //var id = '53a39f480008741aa8ad95cf7f0828e9'; var id = id; //p2p?????GUID create_cdstm_p2p_flash_player("flashcontent", 960, 600, "http://127.0.0.1:18582/videos/" + id + ".flv", "", ""); } function PlayP2P_IE_Server(id) { //????P2P???? var id = id; //p2p?????GUID FlV_PPS.SimpleSelectByURL("forcetv://stream/" + id + "?tip=fccs.qlteacher.com:9900&ptl=http&type=flv"); create_cdstm_p2p_flash_player("flashcontent", 960, 600, "http://127.0.0.1:9906/" + id + ".flv", "", ""); } function PlayP2PFF_FF_Server(id) { //????P2P???? var id = id; //p2p?????GUID // console.log(document.getElementById("flvplayer")); document.getElementById("flvplayer").SimpleSelectByURL("forcetv://stream/" + id + "?tip=fccs.qlteacher.com:9900&ptl=http&type=flv"); create_cdstm_p2p_flash_player("flashcontent", 960, 600, "http://127.0.0.1:9906/" + id + ".flv", "", ""); } /* ????????DIV????,??,??. ??????, ?????????,???????????,?????P2P,?????P2P??? related_url ,????????,?????????????????????? copy_url ,????????,????????????,??????copy_url */ function create_cdstm_p2p_flash_player(obj_div, width, height, play_url, related_url, copy_url) { var flashvars = {}; flashvars.filevalue = play_url; flashvars.getrelatedvalue = encodeURIComponent(related_url); flashvars.copyvalue = encodeURIComponent(copy_url); flashvars.clickrelatedvalue = ""; // flashvars.logo = ""; 2012-05-07 zhangfuzhu flashvars.start_by_time = 0; //alert( play_url ); var swfVersionStr = "10.0.0"; var xiSwfUrlStr = "/app/lib/flv0826/playerProductInstall.swf"; var params = {}; params.quality = "high"; params.bgcolor = "#ffffff"; params.allowscriptaccess = "sameDomain"; params.allowfullscreen = "true"; params.wmode = "window"; var attributes = {}; attributes.id = "MyCustomPlayer"; attributes.name = "MyCustomPlayer"; attributes.align = "middle"; swfobject.embedSWF("/app/lib/flv0826/MyCustomPlayer.swf", obj_div, width, height, swfVersionStr, xiSwfUrlStr, flashvars, params, attributes); swfobject.createCSS(obj_div, "display:block;text-align:left;"); } }]);
012f5f86a7da69f17665cf52c8e7f068ae68b5e3
[ "JavaScript" ]
3
JavaScript
gqikai/learnPlantom
82a48004e4c074e513907f339fabf796335a7bc2
5823bc859551c6406aa164379f3f8d2074101bdb
refs/heads/master
<file_sep># Ensuring Reliability with SLOs Welcome! We'll be running a docker-compose command, allowing us to spin up an entire environment. You'll be using the Datadog account created for you. Use the username and password credentials assigned to you at your seat. Follow along with Datadog open in another browser. About the workshop Uptime is a poor measure of reliability. Agile development’s fail-fast approach coupled with distributed applications and dynamic infrastructure requires us to have a better understanding of reliability. Service level objectives (SLOs) help you understand the true health of your systems and how your end users experience them. Poorly defined SLOs means you have little to no visibility into the successes and failures of those apps and their services. In this workshop you’ll learn how to define SLOs and monitor the right service level indicators to ensure reliability. Armed with this information, we'll introduce chaos into a sample application and learn how to respond effectively using error budgets.<file_sep># Exploring our services and user journeys Let’s take a quick tour of our application. You can tour the application by examining the content of the `docker-compose.yml` file. This application was originally developed for a Distributed Tracing workshop to showcase how Datadog APM integrates with multiple programming languages and technologies. Today we'll focus on 3 containers: * The agent: it is necessary to collect metrics and traces from the other containers * Frontend: a Python Flask application that receives calls and routes them to different backend services, the code lives in the `./frontend` folder. It also serves a React Single Page Application as a static file built from the `./single-page-frontend` folder. * Pumps: another Flask application that receives calls from the frontend related to the water pumps. The code lives in the `./pumps-api` folder. Both Flask applications are automatically instrumented by Datadog APM (see the `command` statements in `docker-compose.yaml`) which will generate metrics in the `trace.flask.` namespace. Hint: remember this for later. This Katacoda environment allows you to modify the Python code and see the results. Simply browse the code in the editor and edit it then type CTRL+c in the terminal to quit Docker Compose and start it again with the `docker-compose up` command. So let's think about reliability of this system. To start tracking SLIs we'll consider what our user journey should be. Go to the water pump web app and explore! Click on IoT Project in Katacoda to open the app. One of the main functions on this page is the ability to add a new water pump. Can you add one? Go to the app and add new pumps! ![Water Pump](../assets/water-pump-app.png) Can you identify SLIs for our user journey? <file_sep># Exploring available metrics for SLIs Let’s explore what we can have available in Datadog. There are a few ways to do this. You can explore and search for metrics in the notebooks, across your monitors, and dashboards or across your services instrumented with APM like what we will be doing here. To dig into the services, resources, and the available metrics, let’s search our traces: https://app.datadoghq.com/apm/search ![Trace Search](../assets/trace-search.png) We care about users being able to add pumps so let’s scope down to the `add_pump` resource by using the facets on the left side of the screen. This is core to our `frontend` service. *[Optional] If you'd like, you can click on any of these traces to show the transaction:* ![Trace View](../assets/trace-view.png) You can see that a `POST` to `/add_pump` in the frontend service (frontend/api.py) calls a `POST` request to `/devices` in the pumps-service (pumps-api/pumps.py). Let’s go to the frontend service dashboard. In the side nav click: **APM -> Services -> Frontend** We haven’t purposefully introduced any errors *yet*, since we just got started. So the services dashboard may look something like this: ![Frontend Dash](../assets/frontend-dash.png) But eventually will look something like this: ![Frontend Errors](../assets/frontend-errors.png) Remember before we mentioned that the APM metrics were instrumented for the `trace.flask.` namespace. So the metrics we'll focus on are called `trace.flask.request.hits` and `trace.flask.request.errors`. Let’s use this to create our first SLI. <file_sep>#!/bin/bash export POSTGRES_USER=postgres export POSTGRES_PASSWORD=<PASSWORD> cd /slo-workshop echo Welcome to the Ensuring Reliability with SLOs Training Workshop!<file_sep># Create a service level indicator (SLI) and service level objective (SLO) Navigate to create a new SLI and SLO. You can get there by clicking through to the sub-nav item under Monitors, **Monitors -> Service Level Objectives** or going directly to https://app.datadoghq.com/slo/new ![SLO Nav](../assets/slo-nav.png) And New SLO in the top right corner: ![New SLO](../assets/new-slo.png) ## Identify the SLI There are a couple of options for us: `Monitor Based` or `Event Based`. But we care about availability and error rate so we'll select `Event Based` under `Define The Source` for our SLI creation. Using event based we can track percentage of requests that are successful. **First step:** In the numerator field select `trace.flask.request.hits` scoped to the service and resource we care about: `service:frontend`, `resource_name:post_/add_pump`, `env:slo-workshop`. The numerator represents all of your “good” (successful) hits. ![Editor](../assets/sli-edit.png) **Second step:** Defining the denominator. For this service we need to add a query summing two metrics `trace.flask.request.hits` and `trace.flask.request.errors` to get the total of requests. To add a second query: click advanced, change the metric, `sum a + b` ![Advanced](../assets/advanced.png) Since there haven’t been any errors, you’ll probably need to edit the query directly by clicking `</>` and entering `trace.flask.request.errors`. ![Error metric](../assets/error-metric.png) Note: in this editor you’ll want to `sum by` to get the sum of all of your requests rather than an avg of them. ![Sum by](../assets/sum-by.png) ## Set the SLO Next we set our SLO target and time window we are measuring against. ![Time Window](../assets/time-window.png) Select 99% over 30 day time window. This means that we are setting an SLO to say that 99% of requests to the `add_pump` endpoint must be successful over 30 days. You can even use this as your title! *Optionally, you can add a description and tag your SLO.* Click save! ## View your data Check out your data on the SLO detail page! Go back to our water pump app and add generate requests by adding more pumps! Click on IoT Project in Katacoda to open the app. When you first check it out, it’ll likely say 100%. With the nature of the workshop, there aren’t any errors yet (and also a lower number of requests). But in our next step we will cause chaos and produce failure in the systems. <file_sep>#!/bin/bash mkdir /slo-workshop git clone https://github.com/DataDog/slo-workshop /slo-workshop cd /slo-workshop docker-compose pull<file_sep># Dash 2019 SLO Workshop <file_sep># Adding a monitor-based SLI (optional) Other ways to track latency as an SLI would be using a Datadog monitor for a monitor driven SLI approach. We can define this SLI as: *“99% of time, the p99 latency of adding a pump should be lower than 500ms”* Navigate to **Monitors -> New Monitors** and select type APM, https://app.datadoghq.com/monitors#create/apm. Under *“Select monitor scope”*, pick `Service:frontend`, `Resource: post_/add_pump.` Under *“Set alert conditions”* set the monitor to alert when the p99 latency is above 0.5s over the last 5 minutes. Then save the monitor. Now let’s create our SLO. Navigate to New Service Level Objective, https://app.datadoghq.com/slo/new. Select `Monitor Based` and select the monitor you just created from the dropdown. Then set a target of 99% over the past 7 day and save the new SLO. Go back to the water pump app and add a few more pumps. Observe the SLO, the error budget should be 100% Click on IoT Project in Katacoda to open the app. Now let’s edit the pumps service to introduce some latency and examine the results. In the terminal type CTRL+c to stop the docker-compose stack, then navigate to `pumps-service/pump.py`. Find the code that handles the creation of a new pump and add sleep for 1s with time.sleep(1). Then bring the stack back up with `docker-compose up`. Add a few more pumps and observe how it affects the error budget of the new SLO. Note: You may have noticed that we are using a gauge metric to represent the latency for this example: `trace.flask.request.duration.by.resource_service.99p` and we used a monitor to find out the percentage of the time that this gauge is under our threshold. While this works, it can be a bit hard to grasp. Whether you use monitors or latency as bucketed counters, you should select whatever works better for your requirements. <file_sep># Starting our microservices with Docker Compose This SLO workshop uses multiple docker images in order to build a microservices environment for local development. We can inspect the `docker-compose.yml` in the SLO workshop folder, and see the exact services we'll be running. Let's first bring everything up with the following command: `DD_API_KEY=<api key> docker-compose up` Access your API key by clicking: **Integrations -> APIs** You'll be able to interact with the web app running on port 5000 in the web browser here. Click on IoT Project in Katacoda to open the app. After clicking the link, hop into Datadog, and check to see if your services are there. It may take several minutes for the services to appear. ![Service Nav](../assets/services-nav.png) Eventually, you'll see the list of services like this: ![Service List](../assets/services-list.png) Remember, you can press CTRL+c and exit your running `docker-compose`. <file_sep># Modeling failure in our systems Let's start introducing errors by killing containers! Explore what happens to our error budget. In the real world, there’s a lot of traffic and there’s definitely going to be some errors. For now we are dealing with our small water pump app. Before we start killing containers, maybe check back to the app and add more pumps! Click on IoT Project in Katacoda to open the app. Open a new terminal window by clicking the + sign within Katacoda. There is an option called Open New Terminal. Once the terminal is open run the following command to kill the container running the pumps: `docker stop $(docker ps -aqf "name=sloworkshop_pumps")` As an alternative and if you are more familiar with docker, try removing a running service with a: `$ docker ps` `$ docker kill <containerid>` Kill the container running the pumps: ![Container IDs](../assets/container-ids.png) Go back to the SLO details page. What happens? ![SLI Detail Page](../assets/detail-page-errors.png) Let’s zoom into that bar graph for more detail: ![Bar Graph](../assets/graph-errors.png) Remember, if you kill the frontend, the rest of the downstream services will die. If you break something, switch back to your terminal running docker-compose. Remember, you can CTRL+c, followed by pressing up to rerun the last command and bring back up the entire suite of services. <file_sep># Latency SLIs using bucketed counters (optional) Note: There is no action in the Katacoda env for this step. This is for discussion. As we also care about the latency experienced by our users, we’ll now add a Latency SLI for our User Journey. There are several ways of implementing a Latency SLI. One way that we are going to discuss during this step is to increment a counter for each event (e.g a HTTP request) that completes under a certain time (the good events) and compare this value to the total number of events. It’s also helpful to increment multiple counters that represent “buckets” of time, for example: * All requests <= 10ms * All requests <= 50ms * All requests <= 500ms We call this technique “bucketed counters”. The algorithm can be summarized like this in pseudo-code: `Buckets = [10, 50, 500] # in milliseconds` `For each event (e.g request):` `startTime = Start a time timer` `do something with this event...` `endTime = Stop the timer` `timeTaken = endTime - startTime` `Foreach bucket in sort(buckets):` `If timeTaken <= bucket:` `incrementCounter(“metric.latency.count.under_{bucket}”, 1)` `incrementCounter(“metrics.latency.count.total”, 1)` To implement this you’ll need to emit custom metrics from the application using Dogstatd, https://docs.datadoghq.com/developers/dogstatsd/. You can then create a new Event Based SLO based on the two metrics. Note: There is no action in the Katacoda env for this step.<file_sep>Thank you for joining us for Dash 2019, and hope that you've enjoyed our SLO Workshop!
07b9b28255c17e55c6fe2ba31b47c33ef9747b8f
[ "Markdown", "Shell" ]
12
Markdown
meghanelizabeth/katacoda-scenarios
49fe1869b825802c1ac2c9622f56715003a41dcf
17c8597b0640ab6e14e86a930f0748ad9d3df930
refs/heads/master
<file_sep>'use strict'; var controllers = [ "vendors", "services", "resources" ]; function parse(request) { let parsedRequest = {}, urlArr = urlParser(request.url.split('?')[0]), queryString = request.url.split('?')[1], ctrlName = findController(urlArr); if (!ctrlName) { return parsedRequest; } parsedRequest.controllerName = ctrlName; parsedRequest.method = request.method; parsedRequest.params = paramsParser(urlArr); parsedRequest.params = processQueryString(queryString, parsedRequest.params); return parsedRequest; } function isController(str) { let isController = controllers.some((item) => { return item === str.toLowerCase(); }); return isController; } function urlParser(str) { if (str[0] === '/') { str = str.substring(1); } return str.split('/'); } function paramsParser(urlArr) { let params = {}; for (let i = 0; i < urlArr.length; i++) { if (urlArr[i + 1] === '') { continue; } params[urlArr[i] + 'Id'] = urlArr[i + 1]; i++; } return params; } function processQueryString(queryString, params) { if (!queryString) { return params; } let itemsArr = queryString.split('&'); itemsArr.forEach((item) => { let keyVal = item.split('='); params[keyVal[0]] = keyVal[1]; }); return params; } function findController(urlArr) { for (var i = urlArr.length - 1; i >= 0; i--) { if (isController(urlArr[i])) { return urlArr[i]; } } } exports.parse = parse;<file_sep># routeParser route parser module https://join.skype.com/oDeownlObifw
16a5bcf25f9b5a248b5ab7e708b96dfcc9632717
[ "JavaScript", "Markdown" ]
2
JavaScript
BorisKotlyarov/routeParser
62270adc7271bec163fc1332a770182123a4cfd4
86ffe2ce6a88f748a82d11a1880c81b18c211d2d
refs/heads/master
<repo_name>helenwang2014/financial-data-analysis<file_sep>/test.py # open files in a folder import csv as csv import numpy as np import os #open up a csc file in to a python object for filename in os.listdir('./HKEX/HKEX_2010'): csv_file_object = csv.reader(open('./HKEX/HKEX_2010/' + filename, 'rb')) data = [] for row in csv_file_object: data.append(row) data = np.array(data) print data[-1]
6aeefdb2b7ca5e2dc432528fad2387f6a4d7d2a2
[ "Python" ]
1
Python
helenwang2014/financial-data-analysis
0e0f6a0e5c93d8d6aed250662ba7724c00bf379f
1cc068c80cc9c2dd7d4839a8830363f9a2b15efe
refs/heads/master
<repo_name>joewired/react-native-ui-lib<file_sep>/generatedTypes/incubator/index.d.ts export { default as TabController } from './TabController'; export { default as TouchableOpacity } from './TouchableOpacity'; <file_sep>/generatedTypes/components/radioButton/RadioGroup.d.ts import React from 'react'; export declare type RadioGroupPropTypes = { /** * The initial value of the selected radio button */ initialValue?: string | number | boolean; /** * Invoked once when value changes, by selecting one of the radio buttons in the group */ onValueChange?: (value: string | number | boolean) => void; }; declare const _default: React.ComponentClass<RadioGroupPropTypes & { useCustomTheme?: boolean | undefined; }, any>; export default _default; <file_sep>/src/incubator/index.ts // @ts-ignore export {default as TabController} from './TabController'; export {default as TouchableOpacity} from './TouchableOpacity'; <file_sep>/generatedTypes/components/tabBar/TabBarItem.d.ts import React from 'react'; import { Animated, ViewStyle, TextStyle } from 'react-native'; import { BaseComponentInjectedProps } from '../../commons/new'; import { BadgeProps } from '../badge'; export declare type TabBarItemProps = BaseComponentInjectedProps & { /** * icon of the tab */ icon?: number; /** * icon tint color */ iconColor?: string; /** * icon selected tint color */ iconSelectedColor?: string; /** * label of the tab */ label?: string; /** * custom label style */ labelStyle?: TextStyle; /** * Badge component props to display next the item label */ badge?: BadgeProps; /** * maximum number of lines the label can break */ maxLines?: number; /** * custom selected tab label style */ selectedLabelStyle: TextStyle; /** * whether the tab is selected or not */ selected?: boolean; /** * whether the tab will have a divider on its right */ showDivider?: boolean; /** * A fixed width for the item */ width?: number; /** * ignore of the tab */ ignore?: boolean; /** * callback for when pressing a tab */ onPress?: (props: any) => void; /** * whether to change the text to uppercase */ uppercase?: boolean; /** * Apply background color on press for TouchableOpacity */ activeBackgroundColor?: string; indicatorStyle?: ViewStyle; style?: ViewStyle; testID?: string; }; export declare type State = { indicatorOpacity?: Animated.Value; }; declare const _default: React.ComponentClass<BaseComponentInjectedProps & { /** * icon of the tab */ icon?: number | undefined; /** * icon tint color */ iconColor?: string | undefined; /** * icon selected tint color */ iconSelectedColor?: string | undefined; /** * label of the tab */ label?: string | undefined; /** * custom label style */ labelStyle?: TextStyle | undefined; /** * Badge component props to display next the item label */ badge?: any; /** * maximum number of lines the label can break */ maxLines?: number | undefined; /** * custom selected tab label style */ selectedLabelStyle: TextStyle; /** * whether the tab is selected or not */ selected?: boolean | undefined; /** * whether the tab will have a divider on its right */ showDivider?: boolean | undefined; /** * A fixed width for the item */ width?: number | undefined; /** * ignore of the tab */ ignore?: boolean | undefined; /** * callback for when pressing a tab */ onPress?: ((props: any) => void) | undefined; /** * whether to change the text to uppercase */ uppercase?: boolean | undefined; /** * Apply background color on press for TouchableOpacity */ activeBackgroundColor?: string | undefined; indicatorStyle?: ViewStyle | undefined; style?: ViewStyle | undefined; testID?: string | undefined; } & { useCustomTheme?: boolean | undefined; }, any> & State; export default _default;
e1ddc0f62418b3126a987c2fad8b05b35335f0eb
[ "TypeScript" ]
4
TypeScript
joewired/react-native-ui-lib
e73e91a407f4f1a379e35d2d633fd7226924976e
8afa155d0a010a7b0f8291e9ad508f435f3a9c92
refs/heads/master
<file_sep>require './MathGame_class' player1 = MathGame.new player2 = MathGame.new player = player2 while player1.lives != 0 && player2.lives != 0 player == player2 ? player = player1 : player = player2 num1 = rand(20) num2 = rand(20) puts "Player #{player == player1 ? 1 : 2}: What does #{num1} plus #{num2} equal?" answer = gets.chomp if answer.to_i != (num1 + num2) player.lose_life puts 'WRONG' else puts 'CORRECT' end if player1.lives != 0 && player2.lives != 0 puts "P1: #{player1.lives}/3 vs P2: #{player2.lives}/3" puts '---- NEW TURN ----' else puts "Player #{player1.lives == 0 ? 2 : 1} wins with a score of #{player1.lives == 0 ? player2.lives : player1.lives}/3" puts '---- GAME OVER ----' end end
8711f7dc818998cea4a429b999d84352854fe7c6
[ "Ruby" ]
1
Ruby
moseskim25/TwO-O-Player
591e43dd529b9574ea0fb00d8156ab0d794cccb7
099799b2fbea347a5d2f81fe8e27bf65c2b1ddfc
refs/heads/master
<repo_name>qratosone/DataStructureZJU<file_sep>/HW07/HW07/ReadMe.txt ======================================================================== 控制台应用程序:HW07 项目概述 ======================================================================== 应用程序向导已为您创建了此 HW07 应用程序。 本文件概要介绍组成 HW07 应用程序的每个文件的内容。 HW07.vcxproj 这是使用应用程序向导生成的 VC++ 项目的主项目文件,其中包含生成该文件的 Visual C++ 的版本信息,以及有关使用应用程序向导选择的平台、配置和项目功能的信息。 HW07.vcxproj.filters 这是使用“应用程序向导”生成的 VC++ 项目筛选器文件。它包含有关项目文件与筛选器之间的关联信息。在 IDE 中,通过这种关联,在特定节点下以分组形式显示具有相似扩展名的文件。例如,“.cpp”文件与“源文件”筛选器关联。 HW07.cpp 这是主应用程序源文件。 ///////////////////////////////////////////////////////////////////////////// 其他标准文件: StdAfx.h, StdAfx.cpp 这些文件用于生成名为 HW07.pch 的预编译头 (PCH) 文件和名为 StdAfx.obj 的预编译类型文件。 ///////////////////////////////////////////////////////////////////////////// 其他注释: 应用程序向导使用“TODO:”注释来指示应添加或自定义的源代码部分。 ///////////////////////////////////////////////////////////////////////////// <file_sep>/HW11/HW11/HW11.cpp // HW11.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <string> #include<cmath> #define Max 1000000 using namespace std; class Node { public: string data; Node* next; int count; }; int nextPrime(int N) { int i, p = (N % 2) ? N + 2 : N + 1; while (p<=Max) { for (int i = (int)sqrt(p); i >2; i--) { if (!(p%i))break; } if (i==2) { break; } else { p += 2; } } return p; } class HashTable { private: int tableSize; Node* Heads; public: HashTable(int size) { tableSize = nextPrime(size); Heads = new Node[tableSize]; for (int i = 0; i < tableSize; i++) { Heads[i].data = ""; Heads[i].next = NULL; Heads[i].count = 0; } } ~HashTable() { delete[] Heads; } int Hash(int Key) { return Key%tableSize; } Node* find(string Key) { } }; int main() { return 0; } <file_sep>/HW04/HW04/HW04.cpp // HW04.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include<iostream> #include<vector> #include<queue> using namespace std; class TreeNode { public: int data; TreeNode* left; TreeNode* right; bool flag; TreeNode() { left = NULL; right = NULL; flag = false; } TreeNode(int v) { data = v; left = NULL; right = NULL; flag = false; } }; TreeNode* insert(TreeNode* T, int v) { if (!T) { T = new TreeNode(v); } else { if (T->data<v) { cout << T->data << endl; cout << "right " << v << endl; T->right = insert(T->right, v); } else { cout << T->data << endl; cout << "left " << v << endl; T->left = insert(T->left, v); } } return T; } TreeNode* buildTree(int M) { TreeNode* root; int v; cin >> v; root = new TreeNode(v); for (int i = 1; i < M; i++) { cin >> v; root = insert(root, v); } return root; } bool checkNode(TreeNode* T,int v){ if (T->flag) { if (T->data > v) { cout << T->data<<" " << endl; return checkNode(T->left, v); } else if(T->data<v) { cout <<T->data<<" "<<v << endl; return checkNode(T->right, v); } else { cout << "falseA " << T->data << " " << v << endl; return false; } } else { if (T->data == v) { T->flag = true; return true; } else { cout << "falseB " << T->data << " " << v << endl; return false; } } } bool judge(TreeNode* T, int N) { int input; bool flag = false; cin >> input; if (T->data!=input) { flag =true; } else { T->flag = true; } for (int i = 1; i <N ; i++) { cin >> input; if (!flag&&!checkNode(T,input)) { flag = true; } } return !flag; } int main() { int N, M; cin >> N; while (N) { cin >> M; TreeNode* root = buildTree(N); cout << "build tree " << N << " " << M << endl; for (int j = 0; j < M; j++) { if (judge(root, N)) { cout << "Yes" << endl; } else { cout << "No" << endl; } } delete root; cin >> N; } return 0; } <file_sep>/HW01/HW01/ReadMe.txt ======================================================================== 控制台应用程序:HW01 项目概述 ======================================================================== 应用程序向导已为您创建了此 HW01 应用程序。 本文件概要介绍组成 HW01 应用程序的每个文件的内容。 HW01.vcxproj 这是使用应用程序向导生成的 VC++ 项目的主项目文件,其中包含生成该文件的 Visual C++ 的版本信息,以及有关使用应用程序向导选择的平台、配置和项目功能的信息。 HW01.vcxproj.filters 这是使用“应用程序向导”生成的 VC++ 项目筛选器文件。它包含有关项目文件与筛选器之间的关联信息。在 IDE 中,通过这种关联,在特定节点下以分组形式显示具有相似扩展名的文件。例如,“.cpp”文件与“源文件”筛选器关联。 HW01.cpp 这是主应用程序源文件。 ///////////////////////////////////////////////////////////////////////////// 其他标准文件: StdAfx.h, StdAfx.cpp 这些文件用于生成名为 HW01.pch 的预编译头 (PCH) 文件和名为 StdAfx.obj 的预编译类型文件。 ///////////////////////////////////////////////////////////////////////////// 其他注释: 应用程序向导使用“TODO:”注释来指示应添加或自定义的源代码部分。 ///////////////////////////////////////////////////////////////////////////// <file_sep>/HW05/HW05/HW05.cpp // HW05.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <vector> using namespace std; class Heap { private: int *data; int size; public: Heap(int length) { size =1; data = new int[length+1]; data[0] = -10001; } ~Heap() { delete[] data; } void insert(int value) { data[size] = value; int current = size; int father = current / 2; while (data[current]<data[father]) { swap(data[current], data[father]); current = father; father = current / 2; } //cout << father << " " << current << endl; size++; } void output() { for (int i = 1; i <size; i++) { cout << data[i] << endl; } } void output_route(int start) { bool flag = false; int current = start; while (true) { if (!flag) { cout << data[current]; flag = true; } else { cout << " " << data[current]; } if (current == 1) { cout << endl; break; } current /= 2; } } }; int main() { int M,N; cin >> M>>N; Heap heap(M); int input; for (int i = 0; i < M; i++) { cin >> input; heap.insert(input); } for (int i = 0; i < N; i++) { cin >> input; heap.output_route(input); } return 0; } <file_sep>/HW06/HW6/HW6.cpp // HW6.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <cstring> #include <vector> #include <queue> #include <algorithm> using namespace std; class Graph { private: int n; bool *visited; vector<int> *edges; public: Graph(int N) { n = N; visited = new bool[N]; edges = new vector<int>[N]; memset(visited, 0, N); } ~Graph() { delete[] visited; delete[] edges; } void insert(int a, int b) { edges[a].push_back(b); edges[b].push_back(a); } void DFS(int n) { cout << n << " "; visited[n] = true; sort(edges[n].begin(), edges[n].end()); for (int vertex:edges[n]) { if (!visited[vertex]) { DFS(vertex); } } } void DFSprint(int n) { cout << "{ "; DFS(n); cout << "}" << endl; } void DFSsearch() { DFSprint(0); for (int i = 0; i <n ; i++) { if (!visited[i]) { DFSprint(i); } } } void BFSprint(int n) { cout << "{ "; BFS(n); cout << "}" << endl; } void BFSsearch() { BFSprint(0); for (int i = 0; i <n; i++) { if (!visited[i]) { BFSprint(i); } } } void visit_reset() { memset(visited, 0, n); } void BFS(int n) { queue<int>q; q.push(n); while (!q.empty()) { int vertex = q.front(); q.pop(); cout << vertex << " "; visited[vertex] = true; sort(edges[vertex].begin(), edges[vertex].end()); for (int v:edges[vertex]) { if (!visited[v]) { visited[v] = true; q.push(v); } } } } }; int main() { int N, M; cin >> N >> M; Graph graph(N); int x, y; for (int i = 0; i < M; i++) { cin >> x >> y; graph.insert(x, y); } graph.DFSsearch(); graph.visit_reset(); graph.BFSsearch(); return 0; } <file_sep>/HW03/HW03/Tree_Trav.cpp #include"stdafx.h" #include<iostream> #include<vector> #include<string> using namespace std; int N; class Node { public: int num; Node* left; Node* right; Node() { left = NULL; right = NULL; } }; int counter = 0; string op; int num; Node* preOrder() { Node* root=NULL; if (counter<2*N) { cin >> op; if (op.length()==4) { cin >> num; root = new Node(); root->num = num; counter++; } if (op.length()==3) { counter++; return NULL; } root->left = preOrder(); root->right = preOrder(); } return root; } vector<int>post; void postOrder(Node* root) { if (root!=NULL) { postOrder(root->left); postOrder(root->right); post.push_back(root->num); } } int main() { cin >> N; Node* root = preOrder(); postOrder(root); cout << post[0]; for (int i = 1; i < N; i++) { cout <<" " << post[i]; } cout << endl; return 0; }<file_sep>/StackOverflow/StackOverflow/StackOverflow.cpp // StackOverflow.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> using namespace std; void printN(int N) { if (N>0) { printN(N - 1); } cout << N << endl; } int main() { int N; cin >> N; printN(N); return 0; } <file_sep>/HW02/HW02/HW02.cpp // HW02.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include<iostream> using namespace std; class Node { public: int _val; int _exp; Node* next; Node* prev; Node() { _val = 0; _exp = 0; next = NULL; prev = NULL; } Node(int val, int exp) { _val = val; _exp = exp; next = NULL; prev = NULL; } bool isGreater(Node* another) { if (_exp>another->_exp) { return true; } else { return false; } } }; class LinkList { public: Node* head; LinkList() { head = NULL; } void insert(int val, int exp) { if (head==NULL) { head = new Node(val, exp);//head有值 } else { Node* p = head; while (p->next!=NULL) { p = p->next; } p->next = new Node(val, exp); p->next->prev = p; } } void insertAfter(int val, int exp) { Node* p = head; while (p!=NULL) { if (p->_exp>exp) { p = p->next; } else { if (p->_exp==exp) { p->_val += val; } else { Node* newNode = new Node(val, exp); newNode->prev = p->prev; p->prev->next = newNode; newNode->next = p; p->prev = newNode; } break; } } if (p==NULL) { p = new Node(val, exp); } } void traverse() { Node* p = head; while (p) { cout << p->_val << " " << p->_exp<<" " ; p = p->next; } cout << endl; } }; void LLplus(LinkList L1, LinkList L2,LinkList& result) { Node* p1 = L1.head; LinkList temp2; Node* p = L2.head; while (p != NULL) { temp2.insert(p->_val, p->_exp); p = p->next; } Node* p2 = temp2.head; while (p1!=NULL&&p2!=NULL) { if (p1->_exp == p2->_exp) { int val = p1->_val + p2->_val; int exp = p1->_exp; if (val!=0) { result.insert(val, exp); } p1 = p1->next; p2 = p2->next; } else { int val, exp; if (p1->isGreater(p2)) { val = p1->_val; exp = p1->_exp; result.insert(val, exp); p1 = p1->next; } else { val = p2->_val; exp = p2->_exp; result.insert(val, exp); p2 = p2->next; } } } while (p1!=NULL) { int val = p1->_val; int exp = p1->_exp; result.insert(val, exp); p1 = p1->next; } while (p2 != NULL) { int val = p2->_val; int exp = p2->_exp; result.insert(val, exp); p2 = p2->next; } if (result.head==NULL) { result.insert(0, 0); } } void LLmultiply(LinkList l1, LinkList l2, LinkList& result) { LinkList temp; LinkList temp2; Node* p1 = l1.head; Node* p2 = l2.head; //cout << "p1 " << p1->_val << " " << p1->_exp << endl; while (p2 != NULL) { // cout << "p2 " << p2->_val << " " << p2->_exp << endl; int val = p1->_val*p2->_val; int exp = p1->_exp + p2->_exp; temp.insert(val, exp); p2 = p2->next; } temp.traverse(); p1 = p1->next; p2 = l2.head; while (p1!=NULL) { while (p2 != NULL) { int val = p1->_val*p2->_val; int exp = p1->_exp + p2->_exp; temp.insertAfter(val, exp); temp.traverse(); p2 = p2->next; } p1 = p1->next; p2 = l2.head; } temp.traverse(); } int main() { LinkList L1; int N; cin >> N; int val, exp; for (int i = 0; i < N; i++) { cin >> val >> exp; L1.insert(val, exp); } LinkList L2; int M; cin >> M; for (int i = 0; i < M; i++) { cin >> val >> exp; L2.insert(val, exp); } LinkList resultPlus; LLplus(L1, L2, resultPlus); resultPlus.traverse(); LinkList resultMultiply; LLmultiply(L1, L2, resultMultiply); resultMultiply.traverse(); return 0; } <file_sep>/HW06/HW6/SavingJBsimple.cpp #include "stdafx.h" #include <cstdlib> #include <iostream> #include <vector> #include <stack> #include <cmath> using namespace std; class Node { public: int x; int y; bool visited; Node() { visited = false; } }; vector<Node>crocodile; int jump; int n; int new_x = 0, new_y = 0; double distance(int a, int b, int c, int d) { if (a<0) a = -a; if (b<0) b = -b; if (c<0) c = -c; if (d<0) d = -d; //现在 a b c d 都是正数 // double y=1.0*((a-c)*(a-c)+(d-b)*(d-b)); double y = hypot((a - c), (b - d)); //可以为 负 0 return y; } void bank(int i) { int x = crocodile[i].x, y = crocodile[i].y; if (distance(x, 0, 50, 0) <= jump) { cout << "Yes" << endl; exit(0); } else if (distance(0, y, 0, 50) <= jump) { cout << "Yes" << endl; exit(0); } } void jump_action(int i) { bank(i); stack<int>s; s.push(i); int current_x = crocodile[i].x; int current_y = crocodile[i].y; while (!s.empty()) { for (int j = 0; j < n; j++) { int next_x = crocodile[j].x; int next_y = crocodile[j].y; if (distance(current_x, current_y, next_x, next_y) <= jump&&crocodile[j].visited == false) { crocodile[j].visited = true; bank(j); s.push(j); i = j; current_x = crocodile[i].x; current_y = crocodile[i].y; j = 0; } } if (s.empty()) { return; } i = s.top(); s.pop(); current_x = crocodile[i].x; current_y = crocodile[i].y; } } int main() { cin >> n >> jump; if (jump>=50) { cout << "Yes" << endl; return 0; } Node input; stack<Node>s; for (int i = 0; i < n; i++) { cin >> input.x >> input.y; crocodile.push_back(input); } int x1 = 0, y1 = 0, x2, y2; for (int i = 0; i < n;i++) { x2 = crocodile[i].x; y2 = crocodile[i].y; if (distance(x1,y1,x2,y2)<=jump&&crocodile[i].visited==false) { crocodile[i].visited = true; jump_action(i); } } cout << "No" << endl; return 0; }<file_sep>/StackOverflow/StackOverflow/ReadMe.txt ======================================================================== 控制台应用程序:StackOverflow 项目概述 ======================================================================== 应用程序向导已为您创建了此 StackOverflow 应用程序。 本文件概要介绍组成 StackOverflow 应用程序的每个文件的内容。 StackOverflow.vcxproj 这是使用应用程序向导生成的 VC++ 项目的主项目文件,其中包含生成该文件的 Visual C++ 的版本信息,以及有关使用应用程序向导选择的平台、配置和项目功能的信息。 StackOverflow.vcxproj.filters 这是使用“应用程序向导”生成的 VC++ 项目筛选器文件。它包含有关项目文件与筛选器之间的关联信息。在 IDE 中,通过这种关联,在特定节点下以分组形式显示具有相似扩展名的文件。例如,“.cpp”文件与“源文件”筛选器关联。 StackOverflow.cpp 这是主应用程序源文件。 ///////////////////////////////////////////////////////////////////////////// 其他标准文件: StdAfx.h, StdAfx.cpp 这些文件用于生成名为 StackOverflow.pch 的预编译头 (PCH) 文件和名为 StdAfx.obj 的预编译类型文件。 ///////////////////////////////////////////////////////////////////////////// 其他注释: 应用程序向导使用“TODO:”注释来指示应添加或自定义的源代码部分。 ///////////////////////////////////////////////////////////////////////////// <file_sep>/HW02/HW02/Reversing Linked List.cpp #include"stdafx.h" #include <memory.h> #include <iostream> #include <vector> #include<algorithm> #include <string> #include <cstdio> using namespace std; int addr[100005]; class Node { public: int addr; int data; int next; Node(){} Node(int addr, int data, int next) { this->addr = addr; this->data = data; this->next = next; } }; int main() { int init, list; memset(addr, -1, sizeof(addr)); int n; cin >> init >> n >> list; vector<Node>vInput; int count = 0; for (int i = 0; i < n; i++) { Node temp; cin >> temp.addr >> temp.data >> temp.next; vInput.push_back(temp); addr[temp.addr] = count++;//记录当前节点在vector中的位置 } vector<Node>nodelist; int ptr = init; for (int i = 0; i < n; i++) { nodelist.push_back(vInput[addr[ptr]]); ptr = vInput[addr[ptr]].next; if (ptr==-1) { break; } } int times = nodelist.size() / list; for (int i = 0; i <times; i++) { reverse(nodelist.begin() + i*list, nodelist.begin() + i*list + list); } for (int i = 0; i < nodelist.size(); i++) { if(i == nodelist.size() - 1) { printf("%05d %d -1", nodelist[i].addr, nodelist[i].data); } else { printf("%05d %d %05d", nodelist[i].addr, nodelist[i].data, nodelist[i + 1].addr); } cout << endl; } return 0; }<file_sep>/HW03/HW03/List_Leaves.cpp #include"stdafx.h" #include<iostream> #include<string> #include <vector> #include<queue> using namespace std; class Node { public: int data; int left; int right; Node() { data = 0; left = -1; right = -1; } }; int main() { vector<Node>input; int N; cin >> N; int check[20] = { 0 }; char left, right; for (int i = 0; i < N; i++) { Node node; cin >> left >> right; if (left!='-') { int leftnum = left - '0'; node.left = leftnum; check[leftnum] = 1; } if (right!='-') { int rightnum = right - '0'; node.right = rightnum; check[rightnum] = 1; } input.push_back(node); } int root; for (int i = 0; i < N; i++) { if (check[i]==0) { root = i; } } // cout << root << endl; vector<int>output; queue<int>lev_trav; lev_trav.push(root); while (!lev_trav.empty()) { int get = lev_trav.front(); // cout << get << endl; if (input[get].left==-1&&input[get].right==-1) { // cout << "push"<<get << endl; output.push_back(get); } if (input[get].left!=-1) { lev_trav.push(input[get].left); } if (input[get].right!=-1) { lev_trav.push(input[get].right); } lev_trav.pop(); } for (int i = 0; i < output.size(); i++) { if (i==0) { cout << output[i]; } else { cout << " " << output[i]; } } cout << endl; return 0; }<file_sep>/HW09/HW09/HW09.cpp // HW09.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> using namespace std; class Vector { private: int size, length; int * data, *temp; void merge_sort(int l, int r) { if (l == r) {//如果左右边界相等,表示已完成排序,直接退出 return; } int mid = (l + r) / 2; //取中点 merge_sort(l, mid); //分别对左右两部分递归调用 merge_sort(mid + 1, r); int x = l, y = mid + 1, loc = l; //x表示左半部分指针,y表示右半部分指针,loc表示总的指针 while (x <= mid || y <= r) {//左右两侧至少有一侧没有跑完 if (x <= mid && (y>r || data[x] <= data[y])) {//对于条件:x没有跑完,而y已经跑完,或者左边的值不大于右边的值 temp[loc] = data[x];//把x填进最后排序完成的数组 x++; } else {//相反则把y填进去 temp[loc] = data[y]; y++; } loc++; } for (int i = l; i <= r; i++) { data[i] = temp[i];//覆盖原有数组 } } public: Vector(int input_size) { size = input_size; length = 0; data = new int[size]; temp = new int[size]; } ~Vector() { delete[] data; delete[] temp; } void push_back(int value) { data[length] = value; length++; } bool insert(int loc, int value) { if (loc < 0 || loc > length) { return false; } if (length >= size) { return false; } for (int i = length; i > loc; --i) { data[i] = data[i - 1]; } data[loc] = value; length++; return true; } void print() { for (int i = 0; i < length; ++i) { if (i > 0) { cout << " "; } cout << data[i]; } cout << endl; } void sort() { merge_sort(0, length - 1); } }; int main() { int N, temp; cin >> N; Vector v(N); for (int i = 0; i < N; i++) { cin >> temp; v.push_back(temp); } v.sort(); v.print(); return 0; } <file_sep>/HW03/HW03/HW03.cpp // HW03.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <cstdlib> #include <vector> #include <string> using namespace std; class TreeNode { public: char data; int left; int right; }; void treeValue(TreeNode& tree, int mark[]) { char data, left, right; cin >> data >> left >> right; tree.data = data; if (left != '-') { int leftnum = left - '0'; mark[leftnum] = 1; tree.left = leftnum; } else { tree.left = -1; } if (right!='-') { int rightnum = right - '0'; mark[rightnum] = 1; tree.right = rightnum; } else { tree.right = -1; } } bool Isomorphic(vector<TreeNode>T1,vector<TreeNode>T2,int r1, int r2) { if(r1==-1&&r2==-1){ return true; } if (r1 == -1 && r2 != -1 || r1 != -1 && r2 == -1) { return false; } if (T1[r1].data!=T2[r2].data) { return false; } if (T1[r1].left == -1 && T2[r2].left == -1) { return Isomorphic(T1, T2, T1[r1].right, T2[r2].right); } if ((T1[r1].left != -1) && (T2[r2].left != -1) && (T1[T1[r1].left]).data==(T2[T2[r2].left]).data) { return (Isomorphic(T1, T2, T1[r1].left, T2[r2].left) && Isomorphic(T1, T2, T1[r1].right, T2[r2].right)); } else { return (Isomorphic(T1, T2, T1[r1].left, T2[r2].right) && Isomorphic(T1, T2, T1[r1].right, T2[r2].left)); } } int main() { int N; cin >> N; vector<TreeNode>TreeA; vector<TreeNode>TreeB; int markA[20] = { 0 }; int markB[20] = { 0 }; TreeNode nodeA, nodeB; for (int i = 0; i < N; i++) { treeValue(nodeA, markA); TreeA.push_back(nodeA); } int rootA; for (int i = 0; i <N; i++) { if (markA[i] == 0) { rootA = i; break; } } // cout << rootA << endl; cin >> N; for (int i = 0; i < N; i++) { treeValue(nodeB, markB); TreeB.push_back(nodeB); } int rootB; for (int i = 0; i < N; i++) { if (markB[i] == 0) { rootB = i; // cout << i << endl; break; } } // cout << rootB << endl; bool judge = Isomorphic(TreeA, TreeB, rootA, rootB); if (judge) { cout << "YES" << endl; } else { cout << "NO" << endl; } return 0; } <file_sep>/HW03/HW03/HW3-2.cpp #include "stdafx.h" #include<iostream> using namespace std; <file_sep>/HW10/HW10/HW10.cpp // HW10.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> using namespace std; int main() { int count[51] = { 0 }; int N; cin >> N; int input; for (int i = 0; i <N; i++) { cin >> input; count[input]++; } for (int i = 0; i < 51; i++) { if (count[i]) { cout << i << ":" << count[i] << endl; } } return 0; } <file_sep>/HW11/HW11/Hashing.cpp #include "stdafx.h" #include <iostream> #include <cstring> using namespace std; bool isPrime(int x) { if (x == 1)return false; if (x == 2 || x == 3)return true; for (int i = 2; i*i <=x; i++) { if (x%i == 0)return false; } return true; } bool flag[10000]; int main() { int m, n, input;//mÊÇ´óС cin >> m >> n; while (!isPrime(m)) { m++; } while(n--) { cin >> input; bool inserted = false; for (int j = 0; j < m; j++) { int position = (input + j*j) % m; if (!flag[position]) { inserted = true; flag[position] = true; cout << position << (n ? " " :"\n"); break; } } if (!inserted) { cout<<"-"<< (n ? " " : "\n"); } } return 0; }<file_sep>/README.md # 网易云课堂《数据结构》(2016春)作业 http://mooc.study.163.com/course/ZJU-1000033001#/info 来自浙江大学陈越老师 解题记录在我的简书同步更新 http://www.jianshu.com/notebooks/3430743/latest<file_sep>/HW04/HW04/AVL_root.cpp #include "stdafx.h" #include <iostream> #include<algorithm> using namespace std; class Node { public: Node* left; Node* right; int data; int height; Node(int v):data(v),left(NULL),right(NULL),height(0){} }; int getHeight(Node* node){ if (node==NULL) { return -1; } return node->height; } bool isBalanced(Node* node) { int balanced = getHeight(node->left) - getHeight(node->right); return abs(balanced) < 2; } Node* rotate_LL(Node* node) { Node* temp = node->left; node->left = temp->right; temp->right = node; //更新两者的高度 node->height = max(getHeight(node->left), getHeight(node->right)) + 1; temp->height = max(getHeight(temp->left), getHeight(temp->right)) + 1; return temp; } Node* rotate_RR(Node* node) { Node* temp = node->right; node->right = temp->left; temp->left = node; node->height = max(getHeight(node->left), getHeight(node->right)) + 1; temp->height = max(getHeight(node->left), getHeight(node->right)) + 1; return temp; } Node* rotate_LR(Node* node) { Node* temp = node->left; node->left = rotate_RR(temp); return rotate_LL(node); } Node* rotate_RL(Node* node) { Node* temp = node->right; node->right = rotate_LL(temp); return rotate_RR(node); } Node* insert(Node* root, int value) { if (root==NULL) { root =new Node(value); } else { if (root->data<value)//R { root->right = insert(root->right, value); if (!isBalanced(root)) { if (root->right->data < value) { //RR root = rotate_RR(root); } else//RL { root = rotate_RL(root); } } } else { root->left = insert(root->left, value);//L if (!isBalanced(root)) { if (root->left->data>value)//LL { root = rotate_LL(root); } else { //LR root = rotate_LR(root); } } } } root->height = max(getHeight(root->left), getHeight(root->right)) + 1;//更新root的高度 return root; } void PrintTree(Node* root) { if (root != NULL) { cout << root->data << "--"; PrintTree(root->left); PrintTree(root->right); } } int main() { int N; cin >> N; Node* root = NULL; int input; for (int i = 0; i < N; i++) { cin >> input; root = insert(root, input); // PrintTree(root); } int output = root->data; cout << output << endl; return 0; }<file_sep>/HW07/HW07/HW07.cpp // HW07.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <cstring> #include <vector> #define INF 65536 using namespace std; class Graph { private: int n; vector<vector<int>> matrix; public: Graph(int N) { n = N; vector<vector<int>>_matrix(n, vector<int>(n, INF)); matrix = _matrix; } ~Graph() { } void build(int m) { int a, b, weight; for (int i = 0; i < m; i++) { cin >> a >> b >> weight; matrix[a - 1][b - 1] = weight; matrix[b - 1][a - 1] = weight; //注意数组下标从0开始计数 } } void Floyd() {//Floyd算法 for (int k= 0;k <n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (matrix[i][k]+matrix[k][j]<matrix[i][j]) { matrix[i][j] = matrix[i][k] + matrix[k][j]; //path[i][j]=k; 如有需要可以记录路径 } } } } } int findMaxDist(int vertex) { //找到顶点vertex到其他顶点最长的路径 int maxDist = 0; for (int i = 0; i < n; i++) { if (i!=vertex&&matrix[vertex][i]>maxDist) {//注意不要计算自己到自己的距离 maxDist = matrix[vertex][i]; } } return maxDist; } }; int main() { int N, M; cin >> N >> M; Graph graph(N); graph.build(M); graph.Floyd(); int animal = 0; int miniDist = INF; int check = graph.findMaxDist(3); for (int i = 0; i < N; i++) { auto dist = graph.findMaxDist(i); //类型自动推导fromCpp_11,我也来装个逼23333 if (dist>=INF) { cout << 0 << endl; return 0; //自动退出?非连通集? } if (miniDist>dist) //如果当前找到的距离最小则更新miniDist { animal = i + 1;//还是从0开始的问题 miniDist = dist; } } cout << animal << " " << miniDist << endl; return 0; } <file_sep>/HW02/HW02/pop sequence.cpp #include"stdafx.h" #include<iostream> #include <stack> #include <vector> using namespace std; int main() { int m, n, k; cin >> m >> n >> k; int num = 1; stack<int> s; int input; for (int i = 0; i <k; ++i) { bool flag = true; s.push(num); for (int j = 0; j <n; ++j) { cin >> input; do { // cout << "size " << s.size() << endl; if (s.empty() || s.top() != input) { num++; s.push(num); // cout << input << " push " << num << endl; // cout << "size " << s.size() << endl; } else { // cout << input << " pop " << s.top() << endl; s.pop(); // cout << "size " << s.size() << endl; break; } if (s.size()>m) { // cout << "size " << s.size() << endl; flag = false; } // cout << "size " << s.size() << endl; }while (!s.empty() && flag); } if (flag) { cout << "YES" << endl; } else { cout << "NO" << endl; } num = 1; while (!s.empty()) { s.pop(); } } return 0; }<file_sep>/HW06/HW6/SDS.cpp #include"stdafx.h" #include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <queue> using namespace std; class Graph { private: int n; bool* visited; vector<int>* edges; public: Graph(int num) { n = num; visited = new bool[n+1]; memset(visited, 0, n+1); edges = new vector<int>[n+1]; } ~Graph() { delete[] visited; delete[] edges; } void insert(int x, int y) { edges[x].push_back(y); edges[y].push_back(x); } int BFS(int vertex) { int count = 1; int *level = new int[n + 1]; level[vertex] = 0; visited[vertex] = true; queue<int>q; q.push(vertex); while (!q.empty()) { int top = q.front(); for (int adj_vertex : edges[top]) { if (!visited[adj_vertex]) { visited[adj_vertex] = true; level[adj_vertex] = level[top] + 1; count++; q.push(adj_vertex); } } if (level[top]+1==6) { break; } q.pop(); } delete[] level; return count; } int BFS2(int vertex) { int level = 0, last = vertex, tail;//last为最后访问的节点,初始为第一个节点 queue<int>q; //tail为这一层的尾节点 q.push(vertex); int count = 1; visited[vertex] = true; while (!q.empty()) { int top = q.front(); q.pop(); for (int adj_vertex : edges[top]) { if (!visited[adj_vertex]) { q.push(adj_vertex); count++; tail = adj_vertex; visited[adj_vertex] = true; } } if (top == last) { //top等于last即意味着这一层扫完了 last = tail;//用当前找到的最末端节点更新之 level++;//加一层 } if (level==6) { break; } } return count; } void SDS() { int count; for (int i =1; i <= n; i++) { count = BFS2(i); printf("%d: %.2f%%\n", i, 100.0 * count / n); memset(visited, 0, n + 1); } } }; int main() { int n, m; cin >> n >> m; Graph g(n); int x, y; for (int i = 0; i < m; i++) { cin >> x >> y; g.insert(x, y); } g.SDS(); return 0; }<file_sep>/HW01/HW01/cpp4-3.cpp #include "stdafx.h" #include <iostream> #include <cstdlib> using std::cin; using std::cout; using std::endl; void exitWhenInvalidScreen(int input) { if (input <= 0 || input>1000) { std::cout << "invalid screen size" << std::endl; exit(0); } } int abs(int input) { if (input<0) { input = -input; } return input; } class Screen { private: int _width; int _height; public: Screen(int width, int height) { exitWhenInvalidScreen(width); exitWhenInvalidScreen(height); _width = width; _height = height; std::cout << "screen" << std::endl; }; Screen() { std::cout << "screen" << std::endl; }; int getWidth() { return _width; }; int getHeight() { return _height; }; int setWidth(int width) { exitWhenInvalidScreen(width); _width = width; return width; }; //return width int setHeight(int height) { exitWhenInvalidScreen(height); _height = height; return height; }; }; class MyRectangle { private: Screen* screen_; int x1, y1, x2, y2; public: MyRectangle(int x1, int y1, int x2, int y2, Screen* screen) { this->x1 = x1; this->x2 = x2; this->y1 = y1; this->y2 = y2; screen_ = screen; }; MyRectangle() { this->x1 = 0; this->x2 = 0; this->y1 = 0; this->y2 = 0; }; void setCoordinations(int x1, int y1, int x2, int y2) { this->x1 = x1; this->x2 = x2; this->y1 = y1; this->y2 = y2; } void setScreen(Screen &screen) { screen_ = &screen; } void Draw() { int width = screen_->getWidth(); int height = screen_->getHeight(); if (x1>0 && x1<width&&y1>0 && y1<height&&x2>0 && x2<width&&y2>0 && y2<height) { int recwidth = x2 - x1; // recwidth = abs(recwidth); int recheight = y2 - y1; // recheight = abs(recheight); //cout << x1 << " " << y1 << " " << recwidth << " " << recheight << endl; if (x1<x2&&y1>y2) { cout << x1 << " " << y1 << " " << recwidth << " " << recheight << endl; } else { cout << "invalid myrectangle" << endl; } } else { cout << "invalid myrectangle" << endl; } } }; int main() { int width, height; cin >> width >> height; Screen screen(width, height); int leftX, leftY, rightX, rightY; cin >> leftX >> leftY >> rightX >> rightY; MyRectangle myRectangle1(leftX, leftY, rightX, rightY, &screen); MyRectangle* myRectangles = new MyRectangle[2]; myRectangles[1].setCoordinations(10, 300, 700, 500); myRectangles[1].setScreen(screen); myRectangle1.Draw(); for (int i = 0; i < 2; i++) { myRectangles[i].setScreen(screen); (myRectangles + i)->Draw(); } delete[] myRectangles; #ifdef DEBUG std::cin.get(); #endif return 0; }<file_sep>/HW05/HW05/FileTransfer.cpp #include "stdafx.h" #include <iostream> using namespace std; class Set { private: int size; int *father; public: Set(int length) { father = new int[length + 1]; for (int i = 1; i <=length; i++) { father[i] = i; } } ~Set() { delete[] father; } int find_set(int node) { if (father[node]!=node) { return find_set(father[node]); } return node; } bool merge(int node1, int node2) { int mark1 = find_set(node1); int mark2 = find_set(node2); if (mark1!=mark2) { father[mark1] = mark2; return true; } return false; } }; int main() { int N; cin >> N; Set set(N); char op; int x, y; while (true) { cin >> op; if (op == 'S') { break; } if (op=='I') { cin >> x >> y; if (set.merge(x, y)) { N--; } } if (op=='C') { cin >> x >> y; if (set.find_set(x)==set.find_set(y)) { cout << "yes" << endl; } else { cout << "no" << endl; } } } if (N!=1) { cout << "There are "<<N<<" components." << endl; } else { cout << "The network is connected." << endl; } return 0; }<file_sep>/HW04/HW04/CBST.cpp #include "stdafx.h" #include<iostream> #include<algorithm> #include<vector> using namespace std; int node[1001] ; vector<int>input; int counter; void build(int root) { if (root>input.size()) { return; } int lchild = root * 2; int rchild = root * 2 + 1; build(lchild); node[root] = input[counter]; counter++; build(rchild); } int main() { int N; cin >> N; int input_num; for (int i = 0; i < N; i++) { cin >> input_num; input.push_back(input_num); } sort(input.begin(), input.end()); counter = 0; build(1); for (int i = 1; i <=N; i++) { if (i == 1) { cout << node[i]; } else { cout << " " << node[i]; } } cout << endl; return 0; } <file_sep>/HW01/HW01/HW01.cpp // HW01.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include<iostream> using namespace std; int getMaxSeq(int*a,int n,int &i_start,int &i_end) { int currentSum = 0; int MaxSum = 0; i_start = 0; i_end = 0; int i_temp = 0; for (int i = 0; i < n; i++) { currentSum += a[i]; if (currentSum>MaxSum) { MaxSum = currentSum; i_end = i; i_start = i_temp; } else if (currentSum < 0) { currentSum = 0; i_temp = i + 1; } } return MaxSum; } int getMaxSeq2(int*a, int n, int &i_start, int &i_end) { int current_sum = 0; int max_sum = -1; i_start = 0; i_end = 0; for (int i = 0; i < n; i++) { current_sum = 0; for (int j = i; j < n; j++) { current_sum += a[j]; if (current_sum>max_sum) { max_sum = current_sum; i_start = i; i_end = j; } } } return max_sum; } int main() { int n; cin >> n; int*a = new int[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } int i_start, i_end; int max = getMaxSeq2(a, n,i_start,i_end); if (max < 0) { cout << 0 <<" "<< a[0] <<" "<< a[n - 1] << endl; } else { cout << max <<" "<< a[i_start]<<" "<<a[i_end]<<endl; } return 0; }
01dc8cad13873b5d6c2428cea14444d6384ea820
[ "Markdown", "Text", "C++" ]
27
Text
qratosone/DataStructureZJU
28b05f4438d9bafefbd06c3723fa24c279c4aec3
3780bee4d8431981f3f7cf772dc462d11e6f0e46
refs/heads/master
<file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Dept_company extends Model { public $timestamps = false; private $table = 'dept_company'; private $primaryKey = 'dept_company_id'; protected $fillable = [ 'fk_department_id', 'fk_company_id' ]; public function companies() { return $this->belongsToMany('App\Company', 'fk_company_id', 'dept_company_id'); } public function departments() { return $this->belongsToMany('App\Department', 'fk_department_id', 'dept_company_id'); } } <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateDeptCompanyTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('dept_company', function(Blueprint $table) { $table->integer('dept_company_id', true); $table->integer('fk_departement_id')->index('fk_department_id'); $table->integer('fk_company_id')->index('fk_company_id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('dept_company'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; use App\Employee; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; class UsersController extends Controller { public function createUser(Request $request) { $validate = Validator::make($data, [ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], 'password' => ['required', 'string', 'min:6', 'confirmed'], ]); if ($validate) { $user = User::create([ 'name' => $request->name, 'user_type' => $request->user_type, 'email' => $request->email, 'password' => <PASSWORD>($request->password), ]); if($data['user_type'] == 1) { Employee::create([ 'fk_user_id' => $user->id ]); } } return back(); } public function userDashboard() { $users = User::get(); return view('usersDashboard')->with('users', $users); } public function viewUser($id) { $user = User::find($id); return view('viewUser')->with('user', $user); } public function updateUser(Request $request, $id) { $user = User::find($id); $employee = Employee::where('fk_user_id', $user->id)->first(); $user->name = $request->name; $user->email = $request->email; $user->save(); $employee->address = $request->address; $employee->save(); return back()->with('user', $user); } public function deleteUser($id) { $user = User::find($id); $user->delete(); return back(); } } <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateEmployeeTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('employee', function(Blueprint $table) { $table->integer('employee_id', true); $table->integer('fk_user_id')->index('id'); $table->integer('fk_company_id')->index('fk_company_id'); $table->integer('address'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('employee'); } } <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class AddForeignKeysToDeptCompanyTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('dept_company', function(Blueprint $table) { $table->foreign('fk_company_id', 'dept_company_ibfk_1')->references('company_id')->on('company')->onUpdate('RESTRICT')->onDelete('RESTRICT'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('dept_company', function(Blueprint $table) { $table->dropForeign('dept_company_ibfk_1'); }); } } <file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); Route::group(['middleware' => 'auth'], function () { Route::get('/userDashboard', 'UsersController@userDashboard'); Route::get('/userDashboard/{id}', 'UsersController@viewUser'); Route::delete('/userDashboardD/{id}', 'UsersController@deleteUser'); Route::put('/userDashboard/update/{id}', 'UsersController@updateUser'); });
674670bfc41d5b292dc9d14edd2fb2273ba3af1e
[ "PHP" ]
6
PHP
gaaaabf/EmpManagement
5a08bd9ec3a961d0f535a655b81aae910dda7f32
2328519c49fbc917fe7f84456eda802fff03d381
refs/heads/master
<repo_name>Nollyt3/SQLiteTutorial_NolanTurin<file_sep>/app/src/main/java/tutorialkart/com/UserModel.kt package tutorialkart.com class UserModel (val userid: String, val name: String, val age: String)<file_sep>/settings.gradle rootProject.name='SQLiteTutorial_NolanTurin' include ':app'
00394b35d2fc829c33abee418efe5cf4eb1e855c
[ "Kotlin", "Gradle" ]
2
Kotlin
Nollyt3/SQLiteTutorial_NolanTurin
b84e2e3e9b9bb3e3ab48c99ce234511aa488a9d1
b41ed0cc9b587cc42a58b6db9abf5b89e3cb8d19
refs/heads/master
<file_sep>function KeylookupCtrl($scope) { //get data from backend and bind to view //$http.get("/api/url").success(function(data) { // $scope.data = data; //}); $scope.data = [ {key_code: "Cmd-Click", application: "Finder", description: "Open Sidebar item in a new window"}, {key_code: "Cmd-1", application: "Finder", description: "Switch Finder views (Icon)"}, {key_code: "Cmd-2", application: "Finder", description: "Switch Finder views (List)"}, {key_code: "Cmd-3", application: "Finder", description: "Switch Finder views (Column)"}, {key_code: "Cmd-4", application: "Finder", description: "Switch Finder views (Cover Flow)"}, {key_code: "Cmd-Shift-A", application: "Findier", description: "Open the Applications folder"}, {key_code: "Cmd-Tab", application: "App Switcher", description: "to switch to last used app."}, {key_code: "Opt-Left", application: "Working with Text", description: "Go to beginning of current or previous word"}, {key_code: "Ctrl-A", application: "Emacs", description: "go to start of line (move cursor to start of line) "}, {key_code: "Ctrl-E", application: "Emacs", description: "go to end of line (move cursor to end of line) "}, {key_code: "Ctrl-P", application: "Emacs", description: "go up one line "}, {key_code: "Ctrl-N", application: "Emacs", description: "go down one line "}, {key_code: "Ctrl-B", application: "Emacs", description: "go back a character (move cursor left) "}, {key_code: "Ctrl-F", application: "Emacs", description: "go forward a character (move cursor right) "}, {key_code: "Ctrl-D", application: "Emacs", description: "delete the character to the right of the cursor "}, {key_code: "Ctrl-H", application: "Emacs", description: "delete the character to the left of the cursor "}, {key_code: "Ctrl-K", application: "Emacs", description: "delete the selection or to the end of the line (acts like cutting the text) "}, {key_code: "Ctrl-Y", application: "Emacs", description: "yank back the killed text (acts like pasting) "}, {key_code: "Ctrl-V", application: "Emacs", description: "scroll down "}, {key_code: "Ctrl-L", application: "Emacs", description: "center the current line in the window "}, {key_code: "Ctrl-O", application: "Emacs", description: "insert line break after the cursor without moving the cursor "}, {key_code: "Ctrl-T", application: "Emacs", description: "transpose letters (swaps letters on left and right of cursor) "}, {key_code: "Shift-Tab", application: "Any", description: "Navigate through controls in a reverse direction"} ]; //bind downdown list $scope.key_names = ["Tab", "Return", "Enter", "Eject", "Escape", "Page Up", "Page Down", "Home", "End", "Up", "Down", "Left", "Right", "Delete Left", "Delete Right", "Click", "Space"]; //default values $scope.key = {command: false, ctrl: false, shift: false, name: ""}; $scope.results = $scope.data; //event handlers $scope.apply_filter = function() { var key_code = (($scope.key.command ? "Cmd-" : "") + ($scope.key.option ? "Opt-" : "") + ($scope.key.ctrl ? "Ctrl-" : "") + ($scope.key.shift ? "Shift-" : "") + $scope.key.name).toLowerCase(); var filter_function; if (key_code == "") { $scope.results = $scope.data; } else { if ($scope.key.name == "") { filter_function = function(obj) { return obj.key_code.toLowerCase().indexOf(key_code) == 0; }; } else { filter_function = function(obj) { return obj.key_code.toLowerCase() == key_code; }; } $scope.results = _.filter($scope.data, filter_function); } $scope.search = ""; }; $scope.reset = function() { $scope.key = {command: false, ctrl: false, shift: false, name: ""}; $scope.search = ""; $scope.apply_filter(); }; } <file_sep>Mac OS keyboard shortcuts lookup app =========== A simple angular.js app to illustrate the use of * ng-controller * ng-repeat * ng-model * ng-change * ng-click * ng-bind * $scope Note that the data can be served using a RESTful backend. This app also uses twitter bootstrap and underscore.js. The whole app was finished within a day.
600a26c1971b04f66746fda3532c64a2fe9e5007
[ "JavaScript", "Markdown" ]
2
JavaScript
kakarukeys/keylookup
44986c5db67a80295e647f1ecc56478cf2ee4aa3
c17d7fed03704d30caab42fb0884c4f65fe13c52
refs/heads/master
<repo_name>bmj1630/My-Own-Twitter<file_sep>/server.py from flask import Flask, render_template, request, redirect, session, flash import re from mysqlconnection import connectToMySQL app = Flask(__name__) app.secret_key = "keep it secret" from flask_bcrypt import Bcrypt bcrypt = Bcrypt(app) EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') @app.route("/") def index(): return render_template("/index.html") @app.route("/create_user", methods=["POST"]) def create_user_in_db(): is_valid = True if len(request.form['fname']) < 2: is_valid = False flash("Enter a first name") if len(request.form['lname']) < 2: is_valid = False flash("Enter a last name") if len(request.form['email']) < 1: is_valid = False flash("Enter an email address") if len(request.form['password']) < 8: is_valid = False flash("Enter a password of at least 5 characters") if request.form['password'] != request.form['confirm_pw']: is_valid = False flash("Password must match confirmation") if not EMAIL_REGEX.match(request.form["email"]): is_valid = False flash("Email format incorrect") if is_valid: fn = request.form["fname"] ln = request.form["lname"] em = request.form["email"] pw = request.form["password"] cpw = request.form["confirm_pw"] pw_hash = bcrypt.generate_password_hash(request.form['password']) mysql = connectToMySQL("pyexam") query = "INSERT INTO users (first_name, last_name, email, password, created_at, updated_at) VALUES (%(fn)s, %(ln)s, %(em)s, %(password_hash)s, NOW(), NOW())" data = { "fn": fn, "ln": ln, "em": em, "password_hash": <PASSWORD> } mysql.query_db(query,data) flash("User entry successful!") return redirect("/") @app.route("/login", methods=["POST"]) def user_login(): mysql = connectToMySQL("pyexam") query = "SELECT * FROM users WHERE email = %(em)s;" data = { "em" : request.form["email"] } result = mysql.query_db(query,data) if result: if bcrypt.check_password_hash(result[0]["password"], request.form["password"]): session["user_id"] = result[0]["id"] return redirect("thoughts_wall") flash("You could not be logged in") return redirect("/") @app.route("/logout") def log_user_out(): session.clear() return redirect("/") @app.route("/thought_create", methods=["POST"]) def create_a_thought(): is_valid = True if len(request.form['thought']) > 256: is_valid = False flash("Thoughts cannot be longer than 255 characters.") if len(request.form['thought']) < 1: is_valid = False flash("Thoughts cannot be shorter than 5 character.") if is_valid: mysql = connectToMySQL("pyexam") query = "INSERT INTO thoughts (author, message, created_at, updated_at) VALUES (%(au)s, %(me)s, NOW(), NOW())" data = { 'au': session["user_id"], 'me': request.form["thought"] } user = mysql.query_db(query, data) return redirect("/thoughts_wall") @app.route("/thoughts_wall") def successful_login(): mysql = connectToMySQL("pyexam") query = "SELECT * FROM users WHERE id = %(id)s" data = { "id": session['user_id'] } result = mysql.query_db(query, data) mysql = connectToMySQL("pyexam") query = "SELECT users.id AS user_id, thoughts.message, thoughts.id AS thought_id, users.first_name, users.last_name FROM thoughts LEFT JOIN users ON thoughts.author = users.id ORDER BY thoughts.created_at DESC;" thoughts = mysql.query_db(query) mysql = connectToMySQL("pyexam") query = "SELECT thought_id, COUNT(thought_id) AS liked FROM users_has_thoughts GROUP BY thought_id;" like_count = mysql.query_db(query) mysql = connectToMySQL("pyexam") query = "SELECT * FROM users_has_thoughts WHERE user_id = %(id)s;" data = { "id": session["user_id"] } is_liked = mysql.query_db(query, data) liked_messages = [] for liked in is_liked: liked_messages.append(liked["thought_id"]) return render_template("/thoughts_wall.html", user_info=result[0], thoughts=thoughts, like_count=like_count, liked_messages=liked_messages) @app.route("/like/<th_id>/") def like_a_message(th_id): mysql = connectToMySQL("pyexam") query = "INSERT INTO users_has_thoughts(user_id, thought_id, created_at, updated_at) VALUES (%(uid)s, %(thid)s, NOW(), NOW())" data = { "uid": session["user_id"], "thid": th_id } mysql.query_db(query, data) return redirect("/thoughts_wall") @app.route("/details/<th_id>/") def message_details(th_id): mysql = connectToMySQL("pyexam") query = "SELECT users_has_thoughts.user_id, users.first_name, users.last_name, users_has_thoughts.thought_id FROM users_has_thoughts JOIN users ON users_has_thoughts.user_id = users.id WHERE users_has_thoughts.thought_id = %(thid)s;" data = { "thid": th_id } users_who_liked = mysql.query_db(query, data) mysql = connectToMySQL("pyexam") query = "SELECT users.id AS user_id, thoughts.message, thoughts.created_at, thoughts.id AS thought_id, users.first_name, users.last_name FROM thoughts LEFT JOIN users ON thoughts.author = users.id WHERE thoughts.id = %(thid)s;" data = { "thid": th_id } message = mysql.query_db(query, data) return render_template("/details.html", users_who_liked=users_who_liked, message=message[0]) @app.route("/unlike/<th_id>/") def unlike_message(th_id): mysql = connectToMySQL("pyexam") query = "DELETE FROM users_has_thoughts WHERE user_id = %(uid)s AND thought_id = %(thid)s" data = { "uid": session["user_id"], "thid": th_id } mysql.query_db(query, data) return redirect("/thoughts_wall") @app.route("/dashboard") def return_to_dashboard(): return redirect("/thoughts_wall") @app.route("/delete_thought/<th_id>/") def delete_a_thought(th_id): query = "DELETE FROM users_has_thoughts WHERE thought_id = %(thid)s" data = { 'thid': th_id } mysql = connectToMySQL('pyexam') mysql.query_db(query, data) query = "DELETE FROM thoughts WHERE id = %(thid)s" mysql = connectToMySQL('pyexam') mysql.query_db(query, data) return redirect("/thoughts_wall") if __name__ == "__main__": app.run(debug=True)<file_sep>/Matt's Python.sql -- MySQL Workbench Forward Engineering SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'; -- ----------------------------------------------------- -- Schema mydb -- ----------------------------------------------------- -- ----------------------------------------------------- -- Schema pyexam -- ----------------------------------------------------- -- ----------------------------------------------------- -- Schema pyexam -- ----------------------------------------------------- CREATE SCHEMA IF NOT EXISTS `pyexam` DEFAULT CHARACTER SET utf8 ; USE `pyexam` ; -- ----------------------------------------------------- -- Table `pyexam`.`users` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `pyexam`.`users` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `first_name` VARCHAR(255) NULL DEFAULT NULL, `last_name` VARCHAR(255) NULL DEFAULT NULL, `email` VARCHAR(255) NULL DEFAULT NULL, `password` VARCHAR(255) NULL DEFAULT NULL, `created_at` DATETIME NULL DEFAULT NULL, `updated_at` DATETIME NULL DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE = InnoDB AUTO_INCREMENT = 3 DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `pyexam`.`thoughts` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `pyexam`.`thoughts` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `author` INT(11) NOT NULL, `message` VARCHAR(255) NULL DEFAULT NULL, `created_at` DATETIME NULL DEFAULT NULL, `updated_at` DATETIME NULL DEFAULT NULL, PRIMARY KEY (`id`), INDEX `fk_thoughts_users_idx` (`author` ASC) VISIBLE, CONSTRAINT `fk_thoughts_users` FOREIGN KEY (`author`) REFERENCES `pyexam`.`users` (`id`)) ENGINE = InnoDB AUTO_INCREMENT = 6 DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `pyexam`.`users_has_thoughts` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `pyexam`.`users_has_thoughts` ( `user_id` INT(11) NOT NULL, `thought_id` INT(11) NOT NULL, `created_at` DATETIME NULL DEFAULT NULL, `updated_at` DATETIME NULL DEFAULT NULL, PRIMARY KEY (`user_id`, `thought_id`), INDEX `fk_users_has_thoughts_thoughts1_idx` (`thought_id` ASC) VISIBLE, INDEX `fk_users_has_thoughts_users1_idx` (`user_id` ASC) VISIBLE, CONSTRAINT `fk_users_has_thoughts_thoughts1` FOREIGN KEY (`thought_id`) REFERENCES `pyexam`.`thoughts` (`id`), CONSTRAINT `fk_users_has_thoughts_users1` FOREIGN KEY (`user_id`) REFERENCES `pyexam`.`users` (`id`)) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
4e0adb12f5dd50270f1da40e74c3cbcf04b9f777
[ "SQL", "Python" ]
2
Python
bmj1630/My-Own-Twitter
21f099b4ade4a35a60e0c3fafc47a935903ab8cd
76a93e143b87adbe5fd86fffaaf00cc8be4dab77
refs/heads/master
<repo_name>leemour/node_koa<file_sep>/01/request_counter.js const {Server} = require('http') const {counter} = require('counter') const server = new Server(counter) server.listen(8000) <file_sep>/index.js require('request_counter') <file_sep>/01/counter.js let i = 0 exports.counter = (req, res) => { i++ res.end(i.toString()) }
134241f13991500d089ed0d3092b3d528fbc1a04
[ "JavaScript" ]
3
JavaScript
leemour/node_koa
b2a386412f6bf184a292599fca488e3003250ab0
5efb16ef61e2d47a9d7b721a3284566264459205
refs/heads/master
<repo_name>kmsbin/pi_backend<file_sep>/main.go package main import ( "log" "net/http" "time" ) func main() { log.Print("server rodando") http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { log.Print("Bateu na rota '/'") w.Write([]byte(time.Now().Format("15:04:05 02-01-2006"))) }) log.Fatal(http.ListenAndServe(":8080", nil)) }
c48fdab4803c7bbd3acfcf14bab68dc278a833be
[ "Go" ]
1
Go
kmsbin/pi_backend
fb2f8d557c4973ec2a4fe5b6773abb0ab2a3b305
7064d0f912e3a7759f22130cbc26b939d5ae1e87
refs/heads/master
<repo_name>hamdulmoqeet/Fully_convolutional_networks<file_sep>/training.py from __future__ import print_function import tensorflow as tf import numpy as np import datetime import skimage import skimage.io import skimage.transform import os import scipy as scp import scipy.misc import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import tensorflow as tf import os import time import numpy as np from IPython.display import clear_output import sys import fcn32_vgg import utils ckpt_dir = "/home/sik4hi/ckpt_dir" LOGS_PATH = '/home/sik4hi/tensorflow_logs' WEIGHT_PATH = '.npy' TRAINSET_PATH = '/mnt/data1/city/csv_files/cityscapes_train.csv' os.environ["CUDA_VISIBLE_DEVICES"] = "" IMAGE_SIZE = 224 NUM_OF_CLASSESS = 19 BATCH_SIZE = 1 IMAGE_HEIGHT = 1024 IMAGE_WIDTH = 2048 NUM_CHANNELS = 3 csv_path = tf.train.string_input_producer([TRAINSET_PATH], shuffle=True) textReader = tf.TextLineReader() _, csv_content = textReader.read(csv_path) im_name, im_label = tf.decode_csv(csv_content, record_defaults=[[""], [""]]) im_content = tf.read_file(im_name) train_image = tf.image.decode_png(im_content, channels=3) train_image.set_shape([IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS]) la_content = tf.read_file(im_label) label_image = tf.image.decode_png(la_content, channels=1) label_image.set_shape([IMAGE_HEIGHT, IMAGE_WIDTH, 1]) label_image=tf.squeeze(label_image, squeeze_dims=[2]) label_image = tf.one_hot(label_image,19) train_image = tf.cast(train_image, tf.float32) / 255. image = tf.Print(train_image, [tf.shape(label_image)]) train_image_batch, train_label_batch = tf.train.shuffle_batch([train_image, label_image], batch_size=BATCH_SIZE, capacity=3 + 3 * BATCH_SIZE, min_after_dequeue=3) with tf.device('/cpu:0'): sess = tf.Session() images_tf = tf.placeholder(tf.float32, [None, 1024, 2048, 3]) labels_tf = tf.placeholder(tf.float32,[None, 1024, 2048, 19]) vgg_fcn = fcn32_vgg.FCN32VGG('./vgg16.npy') with tf.name_scope("content_vgg"): vgg_fcn.build(images_tf, train=True, num_classes=19, random_init_fc8=True, debug=False) #head=[] cross_entropy = -tf.reduce_sum( labels_tf * tf.log(vgg_fcn.softmax), reduction_indices=[1]) cross_entropy_mean = tf.reduce_mean(cross_entropy, name='xentropy_mean') #loss_tf = tf.reduce_mean((tf.nn.sparse_softmax_cross_entropy_with_logits(vgg_fcn.upscore, # tf.squeeze(labels_tf, squeeze_dims=[3]), # name="entropy"))) train_op = tf.train.MomentumOptimizer(0.01, 0.9).minimize(cross_entropy_mean) print('Finished building Network.') init_op = tf.group(tf.initialize_all_variables(), tf.initialize_local_variables()) sess.run(init_op) # print(csv_path) # For populating queues with batches, very important! # coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess) for i in range(1): train_imbatch, train_labatch = sess.run([train_image_batch, train_label_batch]) print("batch made") _, train_loss = sess.run([train_op, cross_entropy_mean], feed_dict={images_tf: train_imbatch, labels_tf: train_labatch}) #train_loss= sess.run(vgg_fcn.upscore, # feed_dict={ images_tf: train_imbatch}) #res=sess.run(image) #plt.imshow(train_labatch[0]) #plt.show() print ("Training Loss:", train_loss) #print(len(train_labatch[0])) #print((train_labatch[0][0])) #print(train_labatch[0][j][k]) #print(train_1labatch[0][j][k]) #print(train_imbatch[0]) print("training finished")
e1a22e83ba973e0533079f688658e456f15b3757
[ "Python" ]
1
Python
hamdulmoqeet/Fully_convolutional_networks
6a9cfa82bea7a8304c0b5b467d2617ae96fa8332
a56864136ec852fe8ae72bc1f38fa6cf17f21d02
refs/heads/master
<repo_name>tuantranf/node-rakuten<file_sep>/README.md # node-rakuten A simple rakuten ws api module. Refererd to https://github.com/rakuten-ws <file_sep>/lib/request.js 'use strict'; var _ = require('lodash'); var request = require('superagent'); var _config = {}; exports.setup = function(config) { _config = _.clone(config); }; var execute = function(method, path, params, callback) { var url = _config.endpoint.url + path; var req = request[method](url); // application config if (_config.app) { params.query = params.query || {}; _.extend(params.query, { applicationId: _config.app.application_id, affiliateId: _config.app.affiliate_id, format: 'json' }); } // query parameters if (params.query) { req.query(params.query); } // timeout (ms) if (_config.timeout) { req.timeout(_config.timeout); } if (params.data) { req.send(params.data); } req.end(function(err, res) { if (err) { return callback(err); } if (res.status < 200 || res.status >= 300) { var error = new Error(res.body.error); return callback(error); } callback(null, res.body); }); }; exports.execute = execute; exports.get = function(path, params, callback) { execute('get', path, params, callback); }; exports.post = function(path, params, callback) { execute('post', path, params, callback); }; exports.put = function(path, params, callback) { execute('put', path, params, callback); }; exports.del = function(path, params, callback) { execute('del', path, params, callback); }; <file_sep>/test/config.js 'use strict'; module.exports = { app: { application_id: 'your application id', affiliate_id: 'test' }, max_retries: 5, timeout: 60000, endpoint: { url: 'https://app.rakuten.co.jp/services/api' } }; <file_sep>/lib/client.js 'use strict'; /** * Rakuten Client * */ function RakutenClient(config) { require('./request').setup(config); this.api = require('./api'); } module.exports = RakutenClient; <file_sep>/lib/api/ichiba.js 'use strict'; /** * @fileOverview Ichiba API * @name text.js */ var request = require('../request'); exports.item = { /** * Search item * @param {[type]} data [description] * @param {Function} callback [description] * @return {[type]} [description] */ search: function(data, callback) { request.get('/IchibaItem/Search/20140222', data, callback); }, /** * Get item ranking * @param {[type]} data [description] * @param {Function} callback [description] * @return {[type]} [description] */ ranking: function(data, callback) { request.get('/IchibaItem/Ranking/20120927', data, callback); } }; exports.product = { /** * Search item * @param {[type]} data [description] * @param {Function} callback [description] * @return {[type]} [description] */ search: function(data, callback) { request.get('/Product/Search/20140305', data, callback); } }; <file_sep>/lib/api/index.js "use strict"; var fs = require('fs'); var path = require('path'); var _ = require('lodash'); _.forEach(fs.readdirSync(__dirname), function(name) { if ((name !== 'index.js') && (path.extname(name) === '.js')) { var basename = path.basename(name, '.js'); exports[basename] = require('./' + basename); } });
44a37a38ee354ac87afeac9f385c803c44944a35
[ "Markdown", "JavaScript" ]
6
Markdown
tuantranf/node-rakuten
3a456597967f9c8c2804011b11f5bec2949a2951
4e345bc063ae348b7f379dada3806aea1e61041a
refs/heads/master
<repo_name>yzzwzc/dataanalyze<file_sep>/DataAnalyze/src/com/topsec/dataanalyze/datasource/DataSource.java package com.topsec.dataanalyze.datasource; import java.util.List; import com.topsec.dataanalyze.entity.DataEntity;; /* * 获取数据的接口,用来实现从不同的数据源获取需要的数据 * * 暂定一个获取接口,如果有特殊需要,根据需要添加对应的接口 * */ public interface DataSource { /* * 根据制定条件获取数据 * */ public String getData(String condition); public List<DataEntity> getData(String Table, String Message); public List<DataEntity> getDataFromList(String Table, String Message); } <file_sep>/DataAnalyze/src/com/topsec/dataanalyze/entity/SyslogDataEntity.java package com.topsec.dataanalyze.entity; public class SyslogDataEntity extends DataEntity { public String clientip; public String user; public String sender; public String timestamp; public String result; public String getResult() { return result; } public void setResult(String result) { this.result = result; } public String getClientip() { return clientip; } public void setClientip(String clientip) { this.clientip = clientip; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public Boolean timeequals(Object obj){ if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SyslogDataEntity other = (SyslogDataEntity) obj; if ((timestamp == null) || (other.timestamp == null)) { return false; } return timestamp.substring(0,timestamp.length() - 2).equals(other.timestamp.substring(0,other.timestamp.length() - 2)); } public int compareTo(Object obj) { if (this == obj) return 0; if (obj == null) return 1; SyslogDataEntity other = (SyslogDataEntity) obj; if (timestamp == null || other.timestamp == null) return -1; return timestamp.compareTo(other.timestamp); } @Override public String toString() { return "SyslogDataEntity [clientip=" + clientip + ", user=" + user + ", sender=" + sender + ", timestamp=" + timestamp + ", result=" + result + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((clientip == null) ? 0 : clientip.hashCode()); result = prime * result + ((this.result == null) ? 0 : this.result.hashCode()); result = prime * result + ((sender == null) ? 0 : sender.hashCode()); result = prime * result + ((timestamp == null) ? 0 : timestamp.hashCode()); result = prime * result + ((user == null) ? 0 : user.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SyslogDataEntity other = (SyslogDataEntity) obj; if (clientip == null) { if (other.clientip != null) return false; } else if (!clientip.equals(other.clientip)) return false; if (result == null) { if (other.result != null) return false; } else if (!result.equals(other.result)) return false; if (sender == null) { if (other.sender != null) return false; } else if (!sender.equals(other.sender)) return false; if (timestamp == null) { if (other.timestamp != null) return false; } else if (!timestamp.equals(other.timestamp)) return false; if (user == null) { if (other.user != null) return false; } else if (!user.equals(other.user)) return false; return true; } } <file_sep>/DataAnalyze/src/com/topsec/dataanalyze/datasource/impl/NabhlogDataSource.java package com.topsec.dataanalyze.datasource.impl; import java.util.ArrayList; import java.util.List; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.topsec.dataanalyze.datasource.DataSource; import com.topsec.dataanalyze.datasource.GlobalData; import com.topsec.dataanalyze.entity.DataEntity; import com.topsec.dataanalyze.entity.NabhlogDataEntity; public class NabhlogDataSource implements DataSource { String serverAdd = "http://192.168.127.12/async/eslog/"; @Override public String getData(String condition) { // TODO Auto-generated method stub return null; } public List<DataEntity> getDataFromList(String Table, String Message){ List<NabhlogDataEntity> nabhlogEntity = GlobalData.NabhlogList; List<DataEntity> returnEntity = new ArrayList<DataEntity>(); for (int i = 0; i < nabhlogEntity.size(); i++){ try { if ((nabhlogEntity.get(i)).getClass().getField(Table).get(nabhlogEntity.get(i)).equals(Message)){ if(!returnEntity.contains(nabhlogEntity.get(i))){ returnEntity.add(nabhlogEntity.get(i)); } } } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return returnEntity; } @Override public List<DataEntity> getData(String Table, String Message) { // TODO Auto-generated method stub List<NabhlogDataEntity> nabhEntity = new ArrayList<NabhlogDataEntity>(); List<DataEntity> returnEntity = new ArrayList<DataEntity>(); int startsize = 0; String searchString; String sr; int pageSize = 1000; while (true) { searchString = "auth_name=superman&auth_pwd=<PASSWORD>&querystring=oem_name:topsec AND topsec_logtype:nabhlog AND " + Table + ":" + Message + "&size=" + pageSize + "&sortby=received_at&sortorder=desc&start=" + startsize + "&field=master&field=loginuser&field=time&field=srcip&field=dstip&field=action&field=nabh&field=sessionid"; System.out.println(searchString); sr = http.sendPost(serverAdd, searchString); if (sr.equals("[]") == true){ break; } startsize += pageSize; List<NabhlogDataEntity> list = JSON.parseObject(sr, new TypeReference<List<NabhlogDataEntity>>() {}); nabhEntity.addAll(list); } for (int i = 0; i < nabhEntity.size(); i++){ if(!returnEntity.contains(nabhEntity.get(i))){ returnEntity.add(nabhEntity.get(i)); } } return returnEntity; } } <file_sep>/DataAnalyze/src/com/topsec/dataanalyze/entity/BypassEntity.java package com.topsec.dataanalyze.entity; /* * 4A日志的实体类,用来记录输出日志的结构 * */ public class BypassEntity { private String abnormalBehaviorWarning; private String abnormalBehaviorSub; private String behaviorSourceIp; private String primaryAccount; private String address4A; private String proxyAddress; private String targetIp; private String actionType; private String minorAccount; private String severity; private String actionTime; private String sequence; public String getAbnormalBehaviorWarning() { return abnormalBehaviorWarning; } public void setAbnormalBehaviorWarning(String abnormalBehaviorWarning) { this.abnormalBehaviorWarning = abnormalBehaviorWarning; } public String getAbnormalBehaviorSub() { return abnormalBehaviorSub; } public void setAbnormalBehaviorSub(String abnormalBehaviorSub) { this.abnormalBehaviorSub = abnormalBehaviorSub; } public String getBehaviorSourceIp() { return behaviorSourceIp; } public void setBehaviorSourceIp(String behaviorSourceIp) { this.behaviorSourceIp = behaviorSourceIp; } public String getPrimaryAccount() { return primaryAccount; } public void setPrimaryAccount(String primaryAccount) { this.primaryAccount = primaryAccount; } public String getAddress4A() { return address4A; } public void setAddress4A(String address4a) { address4A = address4a; } public String getProxyAddress() { return proxyAddress; } public void setProxyAddress(String proxyAddress) { this.proxyAddress = proxyAddress; } public String getTargetIp() { return targetIp; } public void setTargetIp(String targetIp) { this.targetIp = targetIp; } public String getActionType() { return actionType; } public void setActionType(String actionType) { this.actionType = actionType; } public String getMinorAccount() { return minorAccount; } public void setMinorAccount(String minorAccount) { this.minorAccount = minorAccount; } public String getSeverity() { return severity; } public void setSeverity(String severity) { this.severity = severity; } public String getActionTime() { return actionTime; } public void setActionTime(String string) { this.actionTime = string; } public String getSequence() { return sequence; } public void setSequence(String sequence) { this.sequence = sequence; } @Override public String toString() { return "Log4AEntity [abnormalBehaviorWarning=" + abnormalBehaviorWarning + ", abnormalBehaviorSub=" + abnormalBehaviorSub + ", behaviorSourceIp=" + behaviorSourceIp + ", primaryAccount=" + primaryAccount + ", address4A=" + address4A + ", proxyAddress=" + proxyAddress + ", targetIp=" + targetIp + ", actionType=" + actionType + ", minorAccount=" + minorAccount + ", severity=" + severity + ", actionTime=" + actionTime + ", sequence=" + sequence + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((abnormalBehaviorSub == null) ? 0 : abnormalBehaviorSub .hashCode()); result = prime * result + ((abnormalBehaviorWarning == null) ? 0 : abnormalBehaviorWarning .hashCode()); result = prime * result + ((actionTime == null) ? 0 : actionTime.hashCode()); result = prime * result + ((actionType == null) ? 0 : actionType.hashCode()); result = prime * result + ((address4A == null) ? 0 : address4A.hashCode()); result = prime * result + ((behaviorSourceIp == null) ? 0 : behaviorSourceIp.hashCode()); result = prime * result + ((minorAccount == null) ? 0 : minorAccount.hashCode()); result = prime * result + ((primaryAccount == null) ? 0 : primaryAccount.hashCode()); result = prime * result + ((proxyAddress == null) ? 0 : proxyAddress.hashCode()); result = prime * result + ((sequence == null) ? 0 : sequence.hashCode()); result = prime * result + ((severity == null) ? 0 : severity.hashCode()); result = prime * result + ((targetIp == null) ? 0 : targetIp.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BypassEntity other = (BypassEntity) obj; if (abnormalBehaviorSub == null) { if (other.abnormalBehaviorSub != null) return false; } else if (!abnormalBehaviorSub.equals(other.abnormalBehaviorSub)) return false; if (abnormalBehaviorWarning == null) { if (other.abnormalBehaviorWarning != null) return false; } else if (!abnormalBehaviorWarning.equals(other.abnormalBehaviorWarning)) return false; if (actionTime == null) { if (other.actionTime != null) return false; } else if (!actionTime.equals(other.actionTime)) return false; if (actionType == null) { if (other.actionType != null) return false; } else if (!actionType.equals(other.actionType)) return false; if (address4A == null) { if (other.address4A != null) return false; } else if (!address4A.equals(other.address4A)) return false; if (behaviorSourceIp == null) { if (other.behaviorSourceIp != null) return false; } else if (!behaviorSourceIp.equals(other.behaviorSourceIp)) return false; if (minorAccount == null) { if (other.minorAccount != null) return false; } else if (!minorAccount.equals(other.minorAccount)) return false; if (primaryAccount == null) { if (other.primaryAccount != null) return false; } else if (!primaryAccount.equals(other.primaryAccount)) return false; if (proxyAddress == null) { if (other.proxyAddress != null) return false; } else if (!proxyAddress.equals(other.proxyAddress)) return false; if (sequence == null) { if (other.sequence != null) return false; } else if (!sequence.equals(other.sequence)) return false; if (severity == null) { if (other.severity != null) return false; } else if (!severity.equals(other.severity)) return false; if (targetIp == null) { if (other.targetIp != null) return false; } else if (!targetIp.equals(other.targetIp)) return false; return true; } } <file_sep>/DataAnalyze/src/com/topsec/dataanalyze/entity/Login4ALogDataEntity.java package com.topsec.dataanalyze.entity; public class Login4ALogDataEntity extends DataEntity{ public String master; public String loginuser; public String srcip; public String dstip; public String time; public String action; public String sessionid; public String getSessionid() { return sessionid; } public void setSessionid(String sessionid) { this.sessionid = sessionid; } public String getMaster() { return master; } public void setMaster(String username) { master = username; } public String getLoginuser() { return loginuser; } public void setLoginuser(String loginName) { loginuser = loginName; } public String getSrcip() { return srcip; } public void setSrcip(String clientip) { srcip = clientip; } public String getDstip() { return dstip; } public void setDstip(String serverip) { dstip = serverip; } public String getTime() { return time; } public void setTime(String time1) { time = time1; } public String getAction() { return action; } public void setAction(String loginResult) { action = loginResult; } @Override public String toString() { return "NABHDataEntity [master=" + master + ", loginuser=" + loginuser + ", srcip=" + srcip + ", dstip=" + dstip + ", time=" + time + ", action=" + action + ", sessionid=" + sessionid + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((action == null) ? 0 : action.hashCode()); result = prime * result + ((dstip == null) ? 0 : dstip.hashCode()); result = prime * result + ((loginuser == null) ? 0 : loginuser.hashCode()); result = prime * result + ((master == null) ? 0 : master.hashCode()); result = prime * result + ((sessionid == null) ? 0 : sessionid.hashCode()); result = prime * result + ((srcip == null) ? 0 : srcip.hashCode()); result = prime * result + ((time == null) ? 0 : time.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Login4ALogDataEntity other = (Login4ALogDataEntity) obj; if (action == null) { if (other.action != null) return false; } else if (!action.equals(other.action)) return false; if (dstip == null) { if (other.dstip != null) return false; } else if (!dstip.equals(other.dstip)) return false; if (loginuser == null) { if (other.loginuser != null) return false; } else if (!loginuser.equals(other.loginuser)) return false; if (master == null) { if (other.master != null) return false; } else if (!master.equals(other.master)) return false; if (sessionid == null) { if (other.sessionid != null) return false; } else if (!sessionid.equals(other.sessionid)) return false; if (srcip == null) { if (other.srcip != null) return false; } else if (!srcip.equals(other.srcip)) return false; if (time == null) { if (other.time != null) return false; } else if (!time.equals(other.time)) return false; return true; } } <file_sep>/DataAnalyze/src/com/topsec/dataanalyze/Log4ADataAnalyze.java package com.topsec.dataanalyze; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.topsec.dataanalyze.datasource.DataSource; import com.topsec.dataanalyze.datasource.impl.CenterZoneAssetsDataSource; import com.topsec.dataanalyze.datasource.impl.NABHAssetsDataSource; import com.topsec.dataanalyze.datasource.impl.Login4ADataSource; import com.topsec.dataanalyze.datasource.impl.NabhlogDataSource; import com.topsec.dataanalyze.datasource.impl.SyslogDataSource; import com.topsec.dataanalyze.entity.DataEntity; import com.topsec.dataanalyze.entity.BypassEntity; import com.topsec.dataanalyze.entity.Login4ALogDataEntity; import com.topsec.dataanalyze.entity.NabhlogDataEntity; import com.topsec.dataanalyze.entity.SyslogDataEntity; public class Log4ADataAnalyze implements DataAnalyze { //定义数据源 DataSource DS_ZoneAssets=new CenterZoneAssetsDataSource();/*核心域资产数据源*/ DataSource DS_NABHAssets=new NABHAssetsDataSource();/*4A资产数据源*/ DataSource DS_Login4A=new Login4ADataSource();/*堡垒机数据源*/ DataSource DS_Syslog=new SyslogDataSource();/*Syslog数据源*/ DataSource DS_Anbhlog=new NabhlogDataSource();/*Syslog数据源*/ //定义数据源保存实体结构 List<BypassEntity> LogList=new ArrayList<BypassEntity>(); /* * 构造函数存放需要初始化的内容 * */ public void Log4ADataAnalyze(){ Analyze4ABypass(); } @Override public List<BypassEntity> getData() { // TODO Auto-generated method stub return LogList; } private List<SyslogDataEntity> MergeLogList(List<SyslogDataEntity> origLogList){ List<SyslogDataEntity> returnList = new ArrayList<SyslogDataEntity>(); int hitTimes = 0; int j = 0; for (int i = 0; i < origLogList.size(); i++){ hitTimes = 0; for (j = i + 1; j < origLogList.size(); j++){ if ((origLogList.get(i)).timeequals(origLogList.get(j))){ hitTimes++; } else { break; } } if (hitTimes >= 8){ returnList.add((SyslogDataEntity)origLogList.get(i)); i = j; } } return returnList; } private void anylazeNabhFromSyslog(List<SyslogDataEntity> sysLogList, boolean isFailedPass){ for (int q = 0; q < sysLogList.size(); q++) { SyslogDataEntity SyslogInfo; SyslogInfo = (SyslogDataEntity)sysLogList.get(q); String sourceIp = SyslogInfo.getClientip(); if (null != DS_NABHAssets.getDataFromList("devIP", sourceIp)){ continue; } /* 在4A堡垒机日志中,查找刚才提取出来的IP,如果能匹配目的IP,则认为是命中一条,库名:"4Alog",字段名:"serverip"。*/ List<DataEntity> NABHList = DS_Login4A.getDataFromList("dstip", sourceIp); /* 常规绕行 */ if (0 == NABHList.size()){ BypassEntity EntityInfo = new BypassEntity(); EntityInfo.setAbnormalBehaviorWarning("绕行4A"); if (isFailedPass == true){ EntityInfo.setAbnormalBehaviorSub("绕行后高频访问"); } else { EntityInfo.setAbnormalBehaviorSub("常规绕行4A行为"); } EntityInfo.setBehaviorSourceIp(SyslogInfo.getSender()); EntityInfo.setPrimaryAccount(SyslogInfo.getUser()); EntityInfo.setAddress4A(""); EntityInfo.setProxyAddress(SyslogInfo.getSender()); EntityInfo.setTargetIp(SyslogInfo.getClientip()); EntityInfo.setActionType("登陆"); EntityInfo.setMinorAccount(SyslogInfo.getUser()); EntityInfo.setSeverity("严重"); EntityInfo.setActionTime(SyslogInfo.getTimestamp()); if(!this.LogList.contains(EntityInfo)){ this.LogList.add(EntityInfo); } } else { /* 常规绕行 */ for (int i = 0; i < NABHList.size(); i++){ Login4ALogDataEntity NABHInfo = (Login4ALogDataEntity)NABHList.get(i); BypassEntity EntityInfo = new BypassEntity(); EntityInfo.setAbnormalBehaviorWarning("绕行4A"); if (isFailedPass == true){ EntityInfo.setAbnormalBehaviorSub("绕行后高频访问"); } else { EntityInfo.setAbnormalBehaviorSub("非常规绕行4A行为"); } EntityInfo.setBehaviorSourceIp(NABHInfo.getSrcip()); EntityInfo.setPrimaryAccount(NABHInfo.getMaster()); List<DataEntity> NABHlogList = DS_Anbhlog.getDataFromList("sessionid", NABHInfo.getSessionid()); if (NABHlogList.size() != 0){ EntityInfo.setAddress4A(((NabhlogDataEntity)(NABHlogList.get(0))).getNabh()); } else { EntityInfo.setAddress4A("未记录"); } EntityInfo.setProxyAddress(NABHInfo.getDstip()); EntityInfo.setTargetIp(SyslogInfo.getSender()); EntityInfo.setActionType("登陆"); EntityInfo.setMinorAccount(NABHInfo.getLoginuser()); EntityInfo.setSeverity("严重"); EntityInfo.setActionTime(NABHInfo.getTime()); if(!this.LogList.contains(EntityInfo)){ this.LogList.add(EntityInfo); } } } } } private void Analyze4ABypass(){ List<DataEntity> LogList = DS_Syslog.getDataFromList("result", "Accepted password"); List<SyslogDataEntity> acceptSyslogList = new ArrayList<SyslogDataEntity>(); for (int j = 0; j < LogList.size(); j++){ acceptSyslogList.add((SyslogDataEntity)LogList.get(j)); } anylazeNabhFromSyslog(acceptSyslogList, false); List<DataEntity> FailedLogList = DS_Syslog.getDataFromList("result", "Failed password"); List<SyslogDataEntity> newFailedLogList = new ArrayList<SyslogDataEntity>(); for (int i = 0; i < FailedLogList.size(); i++){ newFailedLogList.add((SyslogDataEntity)FailedLogList.get(i)); } Collections.sort(newFailedLogList, new Comparator<SyslogDataEntity>() { @Override public int compare(SyslogDataEntity o1, SyslogDataEntity o2) { // TODO Auto-generated method stub return o1.compareTo(o2); } }); anylazeNabhFromSyslog(MergeLogList(newFailedLogList), true); } } <file_sep>/DataAnalyze/src/com/topsec/dataanalyze/datasource/impl/SyslogDataSource.java package com.topsec.dataanalyze.datasource.impl; import java.util.ArrayList; import java.util.List; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.topsec.dataanalyze.datasource.DataSource; import com.topsec.dataanalyze.datasource.GlobalData; import com.topsec.dataanalyze.entity.DataEntity; import com.topsec.dataanalyze.entity.SyslogDataEntity; public class SyslogDataSource implements DataSource { String serverAdd = "http://172.16.58.3/async/eslog/"; /* * 先在syslog日志中查询关键字,库名:"hostlog",字段名:"message",关键字:"Accepted password for " * 此处数据可以来自任意实体文件或者服务; * */ @Override public String getData(String condition) { // TODO Auto-generated method stub return null; } public List<DataEntity> getDataFromList(String Table, String Message){ List<SyslogDataEntity> syslogEntity = GlobalData.SyslogList; List<DataEntity> returnEntity = new ArrayList<DataEntity>(); for (int i = 0; i < syslogEntity.size(); i++){ try { if ((syslogEntity.get(i)).getClass().getField(Table).get(syslogEntity.get(i)).equals(Message)){ if(!returnEntity.contains(syslogEntity.get(i))){ returnEntity.add(syslogEntity.get(i)); } } } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return returnEntity; } public List<DataEntity> getData(String Table, String Message) { // TODO Auto-generated method stub List<SyslogDataEntity> syslogEntity = new ArrayList<SyslogDataEntity>(); List<DataEntity> returnEntity = new ArrayList<DataEntity>(); int startsize = 0; String searchString; String sr; int pageSize = 1000; while (true) { searchString = "auth_name=superman&auth_pwd=<PASSWORD>&querystring=oem_name:topsec AND " + Table + ":" + Message + "&size=" + pageSize + "&sortby=received_at&sortorder=desc&start=" + startsize + "&field=clientip&field=sender&field=user&field=timestamp"; sr = http.sendPost(serverAdd, searchString); if (sr.equals("[]") == true){ break; } startsize += pageSize; System.out.println(sr); List<SyslogDataEntity> list = JSON.parseObject(sr, new TypeReference<List<SyslogDataEntity>>() {}); syslogEntity.addAll(list); } for (int i = 0; i < syslogEntity.size(); i++){ if(!returnEntity.contains(syslogEntity.get(i))){ returnEntity.add(syslogEntity.get(i)); } } return returnEntity; } } <file_sep>/DataAnalyze/src/com/topsec/dataanalyze/DataAnalyze.java package com.topsec.dataanalyze; import java.util.List; import com.topsec.dataanalyze.entity.BypassEntity; public interface DataAnalyze { List<BypassEntity> getData(); }
730d40e107274c43321c8362eccd5f1c0b675b48
[ "Java" ]
8
Java
yzzwzc/dataanalyze
6a63d96940a1fd852d961af598b8ccb68f10406b
3a47910a5752d20a3af64cb2a8af0d5fe9b39659
refs/heads/main
<file_sep>import React, {useEffect} from "react"; import "./Home.css"; const Home = () => { const onPointerMove = (event) => { if (!window.matchMedia("(hover: hover)").matches) return; // move background only when hovering exists const shiftMax = 2.9; // Not 3 to leave some buffer room let normalizedCoords = {x: event.clientX / window.innerWidth, y: event.clientY / window.innerHeight}; let newCoords = {x: (1-normalizedCoords.x*2)*shiftMax, y: (1-normalizedCoords.y*2)*shiftMax}; let backgroundElem = document.getElementById("BackgroundImage"); if (backgroundElem == null) return; // catch edge case of trying to get element after page changes backgroundElem.style.setProperty("--shiftx" , newCoords.x + "vmin"); backgroundElem.style.setProperty("--shifty" , newCoords.y + "vmin"); }; useEffect(() => { window.addEventListener("mousemove", onPointerMove); return () => {window.removeEventListener("mousemove", onPointerMove)}; }); return ( <div id="BackgroundContainer" > <div id="BackgroundImage" /> </div> ); }; export default Home;<file_sep>import React from "react"; import {Link} from "react-router-dom"; import "./Navbar.scss"; import "../pointable.css"; const NavOp = props => ( <div className="NavOp" show-nav={props.showNav} is-large={props.isLarge}> <Link to={props.path} className="NavOpText pointable scales" is-large={props.isLarge} onClick={props.navClick}> {props.text} </Link> </div> ); export default NavOp;<file_sep>import React from "react"; import "./Logo.scss"; import "../../pointable.css"; const Logo = (props) => { return ( <div className="LogoContainer" > <div className="Logo pointable scales" onClick={props.logoClick} is-large={props.isLarge}> <span>dansl.dev</span> <span id="carat" show-nav={props.showNav}>^</span> </div> {props.children} </div> ); }; export default Logo;<file_sep>import React from "react"; import "./Skills.css"; const SkillBubbles = (props) => { return ( <div>Skill Bubbles</div> ); }; export default SkillBubbles;<file_sep>import React from "react"; import "./Navbar.scss"; import NavOp from "./NavOp" const NavOps = props => { const opComp = props.options.map( (item, idx) => (<NavOp key={idx} navClick={props.navClick} text={item} path={props.paths[idx]} showNav={props.showNav} isLarge={props.isLarge}/> ) ); return ( <div className="NavOps" is-large={props.isLarge}> {opComp} </div> ); }; export default NavOps;<file_sep>import React from "react"; import {Switch, Route, Redirect} from "react-router-dom"; import './App.css'; import Navbar from "./Navbar/Navbar"; // Page components import Home from "./Home/Home"; import About from "./About/About"; import Projects from "./Projects/Projects"; import Skills from "./Skills/Skills"; import Music from "./Music/Music"; import AV from "./AV/AV"; const App = () => { // optionLabels and optionPaths biject // also modify $menu-items in Navbar-anim.scss if array length changes // Normal Navbar order const optionLabels = ["About", "Skills", "Projects", "Music", "A/V"]; const optionPaths = ["/about", "/skills", "/projects", "/music", "/av"]; return ( <div id="App" className="content-font"> <Switch> <Route path="/" exact> <Navbar key="nav-large" optionLabels={optionLabels} optionPaths={optionPaths} isLarge={1} /> </Route> <Route> <Navbar key="nav-normal" optionLabels={optionLabels} optionPaths={optionPaths} isLarge={0} /> </Route> </Switch> <Switch> <Route path={optionPaths[0]} component={About} exact /> <Route path={optionPaths[0]}> <Redirect to={optionPaths[0]} /> </Route> <Route path={optionPaths[1]} component={Skills} exact /> <Route path={optionPaths[1]}> <Redirect to={optionPaths[1]} /> </Route> <Route path={optionPaths[2]} component={Projects} exact /> <Route path={optionPaths[2]}> <Redirect to={optionPaths[2]} /> </Route> <Route path={optionPaths[3]} component={Music} exact /> <Route path={optionPaths[3]}> <Redirect to={optionPaths[3]} /> </Route> <Route path={optionPaths[4]} component={AV} exact /> <Route path={optionPaths[4]}> <Redirect to={optionPaths[4]} /> </Route> <Route path="/" component={Home} exact /> <Route> <Redirect to="/" /> </Route> </Switch> </div> ); } export default App; <file_sep>import React from "react"; import "./About.css"; import "../pointable.css"; import AboutEntry from "./AboutEntry"; import bio from "../Text Content/bio.json"; const About = () => { let textEntries = bio.text; let captions = bio.captions; let aboutEntries = textEntries.map((item, idx) => ( <AboutEntry key={"entry-" + item} idx={idx} text={item} caption={captions?.[idx]} /> )); return ( <div id="about-main"> {aboutEntries} </div> ); }; export default About;<file_sep>import React, {useEffect, useState} from "react"; import SkillNav from "./SkillNav"; import SkillBubbles from "./SkillBubbles"; import SkillStats from "./SkillStats"; import "./Skills.css"; const Skills = () => { const resizeWidth = () => { let thresholdWidth = 720; let minRatio = 0.5; let windowWidth = window.innerWidth; let skillsComp = document.getElementById("skills-main"); let newWidth = (windowWidth*minRatio >= thresholdWidth) ? windowWidth*minRatio : (windowWidth <= thresholdWidth) ? windowWidth : thresholdWidth; skillsComp.style.setProperty("width", "" + newWidth); }; useEffect(() => { resizeWidth(); }, []); useEffect(() => { window.addEventListener("resize", resizeWidth); return () => (window.removeEventListener("resize", resizeWidth)); }); const totalNum = 8; const [skillNum, setSkillNum] = useState(0); const changeSkill = (shift) => { setSkillNum((prevNum) => { return (prevNum + totalNum + shift) % totalNum; }); }; return ( <div id="skills-main-container"> <div id="skills-main"> <SkillNav shift={changeSkill}/> <SkillBubbles skill={skillNum} /> <SkillStats skill={skillNum}/> </div> </div> ); }; export default Skills;<file_sep>import React, {useState, useEffect} from "react"; import "./Header.css"; import "./Navbar.scss"; import Logo from "./Logo/Logo"; import NavOps from "./NavOps"; import HomeButton from "./HomeButton"; const Navbar = (props) => { const [showNav, setShowNav] = useState(0); // On scroll event management const onScroll = () => { }; useEffect(() => { window.addEventListener("scroll", onScroll); return () => (window.removeEventListener("scroll", onScroll)); }); const navReveal = () => { setShowNav(prevVal => 1-prevVal); console.log("clicked"); }; return ( <div id="Header" className="title-font"> <div id="screenblur" show-nav={showNav} is-large={props.isLarge}/> <div id="HeaderPadding" is-large={props.isLarge} /> <div id="Navbar" is-large={props.isLarge}> <Logo logoClick={navReveal} isLarge={props.isLarge} showNav={showNav}> <NavOps navClick={navReveal} options={props.optionLabels} paths={props.optionPaths} showNav={showNav} isLarge={props.isLarge} /> </Logo> </div> <HomeButton isLarge={props.isLarge}/> </div> ); }; export default Navbar;<file_sep>import React from "react"; const Music = () => { return <h1>Hello World from Music!</h1>; }; export default Music;<file_sep>import React from "react"; const AV = () => { return <h1>Hello World from A/V!</h1>; }; export default AV;
81b9eaf9bdb0cc488f4868cc9552a5ce4818355c
[ "JavaScript" ]
11
JavaScript
btsp6/personal-website
ab9ce5cbb46fe728c3e9878a413b116e41788442
50f68cfbcbd5f4244fc1b871c13465b47a20469d
refs/heads/master
<repo_name>peterfisher/compiler-peer-group<file_sep>/zeampl/ast/range.py class Location(object): def __init__(self, file: str, line: int, column: int): self._file = file self._line = line self._column = column @property def file(self): return self._file @property def line(self) -> int: return self._line @property def column(self) -> int: return self._column def __str__(self): return self._file + ':' + str(self._line) + ':' + str(self._column) def __repr__(self): x = [self._file, self._line, self._column] return 'Location(' + ','.join([repr(y) for y in x]) + ')' def __hash__(self): return self._line * 97 + self._column def __eq__(self, other): if isinstance(other, Location): return other._line == self._line and other._column == self._column and other._file == self._file else: return False class Range(object): def __init__(self, file, start_line, start_column, end_line, end_column): self._file = file self._start_line = start_line self._start_column = start_column self._end_line = end_line self._end_column = end_column @property def start(self): return Location(self._file, self._start_line, self._start_column) @property def end(self): return Location(self._file, self._end_line, self._end_column) def __str__(self): s = str(self.start) s += '-' if self._end_line != self._start_line: s += str(self._end_line) + ':' s += str(self._end_column) return s def __repr__(self): x = [self._file, self._start_line, self._start_column, self._end_line, self._end_column] return 'Range(' + ','.join([repr(y) for y in x]) + ')' def __hash__(self): return self._start_line * 97 + self._start_column def __eq__(self, other): if isinstance(other, Range): return self._start_line == other._start_line and self._start_column == other._start_column \ and self._end_line == other._end_line and self._end_column == other._end_column \ and self._file == other._file else: return False <file_sep>/btyler/lexer/README.md ## silly streaming lexer ### `cat test.lang | perl lex.pl` <file_sep>/pfisher/parser.swift /* Predictive Parser for LL(1) Grammer */ import Foundation class LLParserOne { var firstSet: [Grammar : [Grammar]] var followSet: [Grammar : [Grammar]] var parsingTable: [NonTerminal: [Terminal: NonTerminal?]] init() { self.firstSet = LLParserOne.getFirstSetforLanguage(productions) self.followSet = LLParserOne.getFollowSetforLanguage(allNonTerminals, firstSet: firstSet) self.parsingTable = LLParserOne.createParsingTableForSets(firstSet, followSet: followSet) } func printParsingTable() { print("PARSING TABLE") for (production, inputTable) in self.parsingTable { for terminal in allTerminals { if inputTable[terminal]! != nil { let productionName = inputTable[terminal]!!.name print("Production: \(production.name); Input Symbol: \(terminal.value), allows production: \(productionName)") } else { print("Production: \(production.name); Input Symbol: \(terminal.value), allows production: ERROR") } } } } class func createParsingTableForSets(firstSet: [Grammar : [Grammar]], followSet: [Grammar : [Grammar]]) -> [NonTerminal: [Terminal:NonTerminal?]] { var parsingTable = [NonTerminal: [Terminal: NonTerminal?]]() //Intialize empty parsing table for production in productions { parsingTable[production] = [Terminal: NonTerminal]() for terminal in allTerminals { parsingTable[production]!.updateValue(nil, forKey: terminal) } } for production in productions { let firstProductionNonTerminal = production.valueList![0] let productionFirstTerminals: [Terminal]? = (firstSet[production]?.filter { $0 is Terminal }) as? [Terminal] let productionFollowTerminals: [Terminal] = (followSet[production]?.filter {$0 is Terminal } as! [Terminal]) // For each terminal a in FIRST(A), add A -> α to M[A,a] if productionFirstTerminals != nil { for terminalSymbol in productionFirstTerminals! { parsingTable[production]![terminalSymbol] = production } } //If ε is in FIRST(α), then for each terminal b in FOLLOW(A), add A -> α to M[A,b]. If ε is in FIRST(α) and $ is in FOLLOW(A), add A -> α to M[A,$]. if firstSet[firstProductionNonTerminal]!.contains(endMarkerTerminal) { // If ε is in FIRST(α) // then for each terminal b in FOLLOW(A) for terminal in productionFollowTerminals { // add A -> α to M[A,b] parsingTable[production]![terminal] = production } } // If ε is in FIRST(α) and $ is in FOLLOW(A) if firstSet[firstProductionNonTerminal] == nil || followSet[firstProductionNonTerminal] == nil { continue } if firstSet[firstProductionNonTerminal]!.contains(endMarkerTerminal) && followSet[firstProductionNonTerminal]!.contains(endMarkerTerminal) { // add A -> α to M[A,$]. parsingTable[production]![endMarkerTerminal] = production } } return parsingTable } private class func getFollowSetforLanguage(nonTerminals: [Grammar], firstSet _firstSet: [Grammar: [Grammar]]) -> [Grammar: [Grammar]] { var _followSet = [Grammar: [Grammar]]() // Initialize follow set with given nontemrinals for nonTerminal in nonTerminals { _followSet[nonTerminal] = [Grammar]() } for nonTemrinal in nonTerminals { _followSet[nonTemrinal]!.append(endMarkerTerminal) let lastSymbol = nonTemrinal.valueList!.last! if lastSymbol is NonTerminal && nonTemrinal.valueList!.endIndex >= 2 { var lastSymbolFirstSet = _firstSet[lastSymbol]! if lastSymbolFirstSet.contains(endMarkerTerminal) { let secondToLastSymbol = nonTemrinal.valueList![nonTemrinal.valueList!.endIndex - 1] _followSet[secondToLastSymbol]!.append(endMarkerTerminal) lastSymbolFirstSet.removeAtIndex(lastSymbolFirstSet.indexOf(endMarkerTerminal)!) _followSet[nonTemrinal]!.appendContentsOf(lastSymbolFirstSet) } else { _followSet[nonTemrinal]!.appendContentsOf(lastSymbolFirstSet) } } } for production in nonTerminals { let lastSymbol = production.valueList!.last if lastSymbol is NonTerminal && lastSymbol!.valueList!.contains(endMarkerTerminal) { let productionFollowSet = _followSet[production]! let secondToLastSymbol = production.valueList![production.valueList!.endIndex - 1] _followSet[secondToLastSymbol]!.appendContentsOf(productionFollowSet) } } return _followSet } private class func getFirstSetforLanguage(productions: [Grammar]) -> [Grammar: [Grammar]] { // Define FIRST(α),where α is any string of grammar symbols, to be the set of terminals that begin strings derived from α. var _firstSet = [Grammar: [Grammar]]() for production in productions { for symbol in production.valueList! { _firstSet[symbol] = LLParserOne.findAllStartTerminalsForSymbol(symbol) } } return _firstSet } private class func findAllStartTerminalsForSymbol(symbol: Grammar) -> [Terminal] { var firstTerminals = [Terminal]() if symbol is Terminal { firstTerminals.append(symbol as! Terminal) } else if symbol is NonTerminal { firstTerminals.append(LLParserOne.findFirstTerminalsForNonterminal(symbol)) } else if symbol is SymbolList { firstTerminals.appendContentsOf(LLParserOne.findAllStartTerminalsForSymbol(symbol)) } return firstTerminals } private class func findFirstTerminalsForNonterminal(symbol: Grammar) -> Terminal { if symbol is Terminal { return symbol as! Terminal } var leftDerivation = symbol.valueList![0] if leftDerivation is NonTerminal { leftDerivation = LLParserOne.findFirstTerminalsForNonterminal(leftDerivation) } return leftDerivation as! Terminal } } <file_sep>/zeampl/parser/parser.py from antlr4 import InputStream from antlr4.CommonTokenStream import CommonTokenStream from .generated import ZeamplLexer, ZeamplParser from .ZeamplASTBuilder import ZeamplASTBuilder import ast from typing import Optional def parse(s, method): input = InputStream(s) lex = ZeamplLexer(input) tok_stream = CommonTokenStream(lex) p = ZeamplParser(tok_stream) ctx = method(p) builder = ZeamplASTBuilder(tok_stream) return ctx.accept(builder) def parse_literal(s: str) -> Optional[ast.Literal]: return parse(s, ZeamplParser.literal) def parse_expression(s: str) -> Optional[ast.Expression]: return parse(s, ZeamplParser.expr) <file_sep>/zeampl/parser/__init__.py from .parser import parse_literal, parse_expression from .string_utils import unescape_string __all__ = [ 'unescape_string', 'parse_literal', 'parse_expression', ] <file_sep>/zeampl/parser/generated/ZeamplParser.py # Generated from /Users/npohilets/compiler-peer-group/zeampl/parser/Zeampl.g4 by ANTLR 4.5.3 # encoding: utf-8 from antlr4 import * from io import StringIO def serializedATN(): with StringIO() as buf: buf.write("\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\3<") buf.write("\u0156\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7") buf.write("\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r\4\16") buf.write("\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4\23\t\23") buf.write("\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30\4\31") buf.write("\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36\t\36") buf.write("\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4$\t$\4%\t%\3\2\7") buf.write("\2L\n\2\f\2\16\2O\13\2\3\3\3\3\3\3\3\3\5\3U\n\3\3\4\3") buf.write("\4\3\4\3\4\3\4\5\4\\\n\4\3\4\3\4\3\5\3\5\3\5\5\5c\n\5") buf.write("\3\5\3\5\5\5g\n\5\3\5\3\5\5\5k\n\5\3\5\3\5\3\6\3\6\3\6") buf.write("\7\6r\n\6\f\6\16\6u\13\6\3\7\3\7\3\7\3\b\3\b\3\b\3\b\3") buf.write("\b\3\b\3\t\3\t\3\t\3\t\7\t\u0084\n\t\f\t\16\t\u0087\13") buf.write("\t\3\t\3\t\3\n\3\n\3\n\5\n\u008e\n\n\3\13\3\13\3\f\3\f") buf.write("\3\f\3\f\3\r\3\r\3\r\3\r\3\r\3\r\7\r\u009c\n\r\f\r\16") buf.write("\r\u009f\13\r\5\r\u00a1\n\r\5\r\u00a3\n\r\3\r\3\r\3\16") buf.write("\3\16\3\16\3\16\3\16\3\16\3\16\3\16\5\16\u00af\n\16\3") buf.write("\17\3\17\7\17\u00b3\n\17\f\17\16\17\u00b6\13\17\3\17\3") buf.write("\17\3\20\3\20\3\20\3\20\5\20\u00be\n\20\3\20\3\20\3\21") buf.write("\3\21\3\22\3\22\3\22\3\22\3\22\3\22\3\22\7\22\u00cb\n") buf.write("\22\f\22\16\22\u00ce\13\22\3\22\3\22\5\22\u00d2\n\22\3") buf.write("\23\3\23\3\23\3\23\3\24\3\24\3\24\3\24\3\24\3\24\3\25") buf.write("\3\25\5\25\u00e0\n\25\3\25\3\25\3\26\3\26\3\26\3\27\3") buf.write("\27\3\27\3\30\3\30\3\30\3\30\3\30\5\30\u00ef\n\30\3\30") buf.write("\3\30\3\30\3\30\3\30\3\30\3\30\3\30\3\30\3\30\3\30\3\30") buf.write("\7\30\u00fd\n\30\f\30\16\30\u0100\13\30\3\31\3\31\3\32") buf.write("\3\32\3\33\3\33\3\34\3\34\3\35\3\35\3\35\3\35\3\35\3\35") buf.write("\3\35\3\35\3\35\3\35\3\35\7\35\u0115\n\35\f\35\16\35\u0118") buf.write("\13\35\3\35\3\35\7\35\u011c\n\35\f\35\16\35\u011f\13\35") buf.write("\3\36\3\36\3\36\3\36\3\36\3\36\5\36\u0127\n\36\3\37\3") buf.write("\37\3 \3 \3 \3 \3 \5 \u0130\n \3!\3!\3\"\3\"\3#\3#\3$") buf.write("\3$\3$\3$\3$\3$\7$\u013e\n$\f$\16$\u0141\13$\5$\u0143") buf.write("\n$\5$\u0145\n$\3$\3$\3%\3%\3%\3%\7%\u014d\n%\f%\16%\u0150") buf.write("\13%\5%\u0152\n%\3%\3%\3%\2\4.8&\2\4\6\b\n\f\16\20\22") buf.write("\24\26\30\32\34\36 \"$&(*,.\60\62\64\668:<>@BDFH\2\7\4") buf.write("\2\4\4\22\34\3\2&+\3\2,/\3\2\60\65\4\2,-\66\66\u015e\2") buf.write("M\3\2\2\2\4T\3\2\2\2\6V\3\2\2\2\bb\3\2\2\2\nn\3\2\2\2") buf.write("\fv\3\2\2\2\16y\3\2\2\2\20\177\3\2\2\2\22\u008d\3\2\2") buf.write("\2\24\u008f\3\2\2\2\26\u0091\3\2\2\2\30\u0095\3\2\2\2") buf.write("\32\u00ae\3\2\2\2\34\u00b0\3\2\2\2\36\u00b9\3\2\2\2 \u00c1") buf.write("\3\2\2\2\"\u00c3\3\2\2\2$\u00d3\3\2\2\2&\u00d7\3\2\2\2") buf.write("(\u00dd\3\2\2\2*\u00e3\3\2\2\2,\u00e6\3\2\2\2.\u00ee\3") buf.write("\2\2\2\60\u0101\3\2\2\2\62\u0103\3\2\2\2\64\u0105\3\2") buf.write("\2\2\66\u0107\3\2\2\28\u0109\3\2\2\2:\u0126\3\2\2\2<\u0128") buf.write("\3\2\2\2>\u012f\3\2\2\2@\u0131\3\2\2\2B\u0133\3\2\2\2") buf.write("D\u0135\3\2\2\2F\u0137\3\2\2\2H\u0148\3\2\2\2JL\5\4\3") buf.write("\2KJ\3\2\2\2LO\3\2\2\2MK\3\2\2\2MN\3\2\2\2N\3\3\2\2\2") buf.write("OM\3\2\2\2PU\5\6\4\2QU\5\b\5\2RU\5\16\b\2SU\5\20\t\2T") buf.write("P\3\2\2\2TQ\3\2\2\2TR\3\2\2\2TS\3\2\2\2U\5\3\2\2\2VW\7") buf.write("\3\2\2WX\79\2\2X[\5\22\n\2YZ\7\4\2\2Z\\\5.\30\2[Y\3\2") buf.write("\2\2[\\\3\2\2\2\\]\3\2\2\2]^\7\5\2\2^\7\3\2\2\2_`\7\6") buf.write("\2\2`c\79\2\2ac\7\7\2\2b_\3\2\2\2ba\3\2\2\2cd\3\2\2\2") buf.write("df\7\b\2\2eg\5\n\6\2fe\3\2\2\2fg\3\2\2\2gh\3\2\2\2hj\7") buf.write("\t\2\2ik\5\22\n\2ji\3\2\2\2jk\3\2\2\2kl\3\2\2\2lm\5\34") buf.write("\17\2m\t\3\2\2\2ns\5\f\7\2op\7\n\2\2pr\5\f\7\2qo\3\2\2") buf.write("\2ru\3\2\2\2sq\3\2\2\2st\3\2\2\2t\13\3\2\2\2us\3\2\2\2") buf.write("vw\7\13\2\2wx\5\22\n\2x\r\3\2\2\2yz\7\f\2\2z{\79\2\2{") buf.write("|\7\4\2\2|}\5\22\n\2}~\7\5\2\2~\17\3\2\2\2\177\u0080\7") buf.write("\r\2\2\u0080\u0081\79\2\2\u0081\u0085\7\16\2\2\u0082\u0084") buf.write("\5\4\3\2\u0083\u0082\3\2\2\2\u0084\u0087\3\2\2\2\u0085") buf.write("\u0083\3\2\2\2\u0085\u0086\3\2\2\2\u0086\u0088\3\2\2\2") buf.write("\u0087\u0085\3\2\2\2\u0088\u0089\7\17\2\2\u0089\21\3\2") buf.write("\2\2\u008a\u008e\5\24\13\2\u008b\u008e\5\26\f\2\u008c") buf.write("\u008e\5\30\r\2\u008d\u008a\3\2\2\2\u008d\u008b\3\2\2") buf.write("\2\u008d\u008c\3\2\2\2\u008e\23\3\2\2\2\u008f\u0090\7") buf.write("9\2\2\u0090\25\3\2\2\2\u0091\u0092\7\20\2\2\u0092\u0093") buf.write("\5\22\n\2\u0093\u0094\7\21\2\2\u0094\27\3\2\2\2\u0095") buf.write("\u00a2\7\b\2\2\u0096\u0097\5\22\n\2\u0097\u00a0\7\n\2") buf.write("\2\u0098\u009d\5\22\n\2\u0099\u009a\7\n\2\2\u009a\u009c") buf.write("\5\22\n\2\u009b\u0099\3\2\2\2\u009c\u009f\3\2\2\2\u009d") buf.write("\u009b\3\2\2\2\u009d\u009e\3\2\2\2\u009e\u00a1\3\2\2\2") buf.write("\u009f\u009d\3\2\2\2\u00a0\u0098\3\2\2\2\u00a0\u00a1\3") buf.write("\2\2\2\u00a1\u00a3\3\2\2\2\u00a2\u0096\3\2\2\2\u00a2\u00a3") buf.write("\3\2\2\2\u00a3\u00a4\3\2\2\2\u00a4\u00a5\7\t\2\2\u00a5") buf.write("\31\3\2\2\2\u00a6\u00af\5\34\17\2\u00a7\u00af\5\36\20") buf.write("\2\u00a8\u00af\5\"\22\2\u00a9\u00af\5$\23\2\u00aa\u00af") buf.write("\5&\24\2\u00ab\u00af\5(\25\2\u00ac\u00af\5*\26\2\u00ad") buf.write("\u00af\5,\27\2\u00ae\u00a6\3\2\2\2\u00ae\u00a7\3\2\2\2") buf.write("\u00ae\u00a8\3\2\2\2\u00ae\u00a9\3\2\2\2\u00ae\u00aa\3") buf.write("\2\2\2\u00ae\u00ab\3\2\2\2\u00ae\u00ac\3\2\2\2\u00ae\u00ad") buf.write("\3\2\2\2\u00af\33\3\2\2\2\u00b0\u00b4\7\16\2\2\u00b1\u00b3") buf.write("\5\32\16\2\u00b2\u00b1\3\2\2\2\u00b3\u00b6\3\2\2\2\u00b4") buf.write("\u00b2\3\2\2\2\u00b4\u00b5\3\2\2\2\u00b5\u00b7\3\2\2\2") buf.write("\u00b6\u00b4\3\2\2\2\u00b7\u00b8\7\17\2\2\u00b8\35\3\2") buf.write("\2\2\u00b9\u00bd\5.\30\2\u00ba\u00bb\5 \21\2\u00bb\u00bc") buf.write("\5.\30\2\u00bc\u00be\3\2\2\2\u00bd\u00ba\3\2\2\2\u00bd") buf.write("\u00be\3\2\2\2\u00be\u00bf\3\2\2\2\u00bf\u00c0\7\5\2\2") buf.write("\u00c0\37\3\2\2\2\u00c1\u00c2\t\2\2\2\u00c2!\3\2\2\2\u00c3") buf.write("\u00c4\7\35\2\2\u00c4\u00c5\5.\30\2\u00c5\u00cc\5\34\17") buf.write("\2\u00c6\u00c7\7\36\2\2\u00c7\u00c8\5.\30\2\u00c8\u00c9") buf.write("\5\34\17\2\u00c9\u00cb\3\2\2\2\u00ca\u00c6\3\2\2\2\u00cb") buf.write("\u00ce\3\2\2\2\u00cc\u00ca\3\2\2\2\u00cc\u00cd\3\2\2\2") buf.write("\u00cd\u00d1\3\2\2\2\u00ce\u00cc\3\2\2\2\u00cf\u00d0\7") buf.write("\37\2\2\u00d0\u00d2\5\34\17\2\u00d1\u00cf\3\2\2\2\u00d1") buf.write("\u00d2\3\2\2\2\u00d2#\3\2\2\2\u00d3\u00d4\7 \2\2\u00d4") buf.write("\u00d5\5.\30\2\u00d5\u00d6\5\34\17\2\u00d6%\3\2\2\2\u00d7") buf.write("\u00d8\7!\2\2\u00d8\u00d9\79\2\2\u00d9\u00da\7\"\2\2\u00da") buf.write("\u00db\5.\30\2\u00db\u00dc\5\34\17\2\u00dc\'\3\2\2\2\u00dd") buf.write("\u00df\7#\2\2\u00de\u00e0\5.\30\2\u00df\u00de\3\2\2\2") buf.write("\u00df\u00e0\3\2\2\2\u00e0\u00e1\3\2\2\2\u00e1\u00e2\7") buf.write("\5\2\2\u00e2)\3\2\2\2\u00e3\u00e4\7$\2\2\u00e4\u00e5\7") buf.write("\5\2\2\u00e5+\3\2\2\2\u00e6\u00e7\7%\2\2\u00e7\u00e8\7") buf.write("\5\2\2\u00e8-\3\2\2\2\u00e9\u00ea\b\30\1\2\u00ea\u00ef") buf.write("\58\35\2\u00eb\u00ec\5\66\34\2\u00ec\u00ed\5.\30\6\u00ed") buf.write("\u00ef\3\2\2\2\u00ee\u00e9\3\2\2\2\u00ee\u00eb\3\2\2\2") buf.write("\u00ef\u00fe\3\2\2\2\u00f0\u00f1\f\5\2\2\u00f1\u00f2\5") buf.write("\64\33\2\u00f2\u00f3\5.\30\6\u00f3\u00fd\3\2\2\2\u00f4") buf.write("\u00f5\f\4\2\2\u00f5\u00f6\5\62\32\2\u00f6\u00f7\5.\30") buf.write("\5\u00f7\u00fd\3\2\2\2\u00f8\u00f9\f\3\2\2\u00f9\u00fa") buf.write("\5\60\31\2\u00fa\u00fb\5.\30\4\u00fb\u00fd\3\2\2\2\u00fc") buf.write("\u00f0\3\2\2\2\u00fc\u00f4\3\2\2\2\u00fc\u00f8\3\2\2\2") buf.write("\u00fd\u0100\3\2\2\2\u00fe\u00fc\3\2\2\2\u00fe\u00ff\3") buf.write("\2\2\2\u00ff/\3\2\2\2\u0100\u00fe\3\2\2\2\u0101\u0102") buf.write("\t\3\2\2\u0102\61\3\2\2\2\u0103\u0104\t\4\2\2\u0104\63") buf.write("\3\2\2\2\u0105\u0106\t\5\2\2\u0106\65\3\2\2\2\u0107\u0108") buf.write("\t\6\2\2\u0108\67\3\2\2\2\u0109\u010a\b\35\1\2\u010a\u010b") buf.write("\5:\36\2\u010b\u011d\3\2\2\2\u010c\u010d\f\4\2\2\u010d") buf.write("\u010e\7\67\2\2\u010e\u011c\79\2\2\u010f\u0110\f\3\2\2") buf.write("\u0110\u0111\7\b\2\2\u0111\u0116\5.\30\2\u0112\u0113\7") buf.write("\n\2\2\u0113\u0115\5.\30\2\u0114\u0112\3\2\2\2\u0115\u0118") buf.write("\3\2\2\2\u0116\u0114\3\2\2\2\u0116\u0117\3\2\2\2\u0117") buf.write("\u0119\3\2\2\2\u0118\u0116\3\2\2\2\u0119\u011a\7\t\2\2") buf.write("\u011a\u011c\3\2\2\2\u011b\u010c\3\2\2\2\u011b\u010f\3") buf.write("\2\2\2\u011c\u011f\3\2\2\2\u011d\u011b\3\2\2\2\u011d\u011e") buf.write("\3\2\2\2\u011e9\3\2\2\2\u011f\u011d\3\2\2\2\u0120\u0127") buf.write("\5<\37\2\u0121\u0127\5> \2\u0122\u0123\7\b\2\2\u0123\u0124") buf.write("\5.\30\2\u0124\u0125\7\t\2\2\u0125\u0127\3\2\2\2\u0126") buf.write("\u0120\3\2\2\2\u0126\u0121\3\2\2\2\u0126\u0122\3\2\2\2") buf.write("\u0127;\3\2\2\2\u0128\u0129\79\2\2\u0129=\3\2\2\2\u012a") buf.write("\u0130\5@!\2\u012b\u0130\5B\"\2\u012c\u0130\5D#\2\u012d") buf.write("\u0130\5F$\2\u012e\u0130\5H%\2\u012f\u012a\3\2\2\2\u012f") buf.write("\u012b\3\2\2\2\u012f\u012c\3\2\2\2\u012f\u012d\3\2\2\2") buf.write("\u012f\u012e\3\2\2\2\u0130?\3\2\2\2\u0131\u0132\7:\2\2") buf.write("\u0132A\3\2\2\2\u0133\u0134\78\2\2\u0134C\3\2\2\2\u0135") buf.write("\u0136\7;\2\2\u0136E\3\2\2\2\u0137\u0144\7\b\2\2\u0138") buf.write("\u0139\5.\30\2\u0139\u0142\7\n\2\2\u013a\u013f\5.\30\2") buf.write("\u013b\u013c\7\n\2\2\u013c\u013e\5.\30\2\u013d\u013b\3") buf.write("\2\2\2\u013e\u0141\3\2\2\2\u013f\u013d\3\2\2\2\u013f\u0140") buf.write("\3\2\2\2\u0140\u0143\3\2\2\2\u0141\u013f\3\2\2\2\u0142") buf.write("\u013a\3\2\2\2\u0142\u0143\3\2\2\2\u0143\u0145\3\2\2\2") buf.write("\u0144\u0138\3\2\2\2\u0144\u0145\3\2\2\2\u0145\u0146\3") buf.write("\2\2\2\u0146\u0147\7\t\2\2\u0147G\3\2\2\2\u0148\u0151") buf.write("\7\20\2\2\u0149\u014e\5.\30\2\u014a\u014b\7\n\2\2\u014b") buf.write("\u014d\5.\30\2\u014c\u014a\3\2\2\2\u014d\u0150\3\2\2\2") buf.write("\u014e\u014c\3\2\2\2\u014e\u014f\3\2\2\2\u014f\u0152\3") buf.write("\2\2\2\u0150\u014e\3\2\2\2\u0151\u0149\3\2\2\2\u0151\u0152") buf.write("\3\2\2\2\u0152\u0153\3\2\2\2\u0153\u0154\7\21\2\2\u0154") buf.write("I\3\2\2\2!MT[bfjs\u0085\u008d\u009d\u00a0\u00a2\u00ae") buf.write("\u00b4\u00bd\u00cc\u00d1\u00df\u00ee\u00fc\u00fe\u0116") buf.write("\u011b\u011d\u0126\u012f\u013f\u0142\u0144\u014e\u0151") return buf.getvalue() class ZeamplParser ( Parser ): grammarFileName = "Zeampl.g4" atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] sharedContextCache = PredictionContextCache() literalNames = [ "<INVALID>", "'var'", "'='", "';'", "'func'", "'init'", "'('", "')'", "','", "'ID'", "'type'", "'class'", "'{'", "'}'", "'['", "']'", "'+='", "'-='", "'~='", "'*='", "'/='", "'%='", "'&='", "'|='", "'^='", "'<<='", "'>>='", "'if'", "'elif'", "'else'", "'while'", "'for'", "'in'", "'return'", "'break'", "'continue'", "'=='", "'!='", "'<'", "'>'", "'>='", "'<='", "'+'", "'-'", "'|'", "'^'", "'*'", "'/'", "'%'", "'&'", "'<<'", "'>>'", "'!'", "'.'" ] symbolicNames = [ "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "BOOL", "ID", "INT", "STRING", "WS" ] RULE_module = 0 RULE_decl = 1 RULE_varDecl = 2 RULE_funcDecl = 3 RULE_argList = 4 RULE_arg = 5 RULE_typeDecl = 6 RULE_classDecl = 7 RULE_typeExpr = 8 RULE_idType = 9 RULE_listType = 10 RULE_tupleType = 11 RULE_statement = 12 RULE_block = 13 RULE_exprStmt = 14 RULE_assign_op = 15 RULE_ifStmt = 16 RULE_whileStmt = 17 RULE_forStmt = 18 RULE_returnStmt = 19 RULE_breakStmt = 20 RULE_continueStmt = 21 RULE_expr = 22 RULE_expr5op = 23 RULE_expr4op = 24 RULE_expr3op = 25 RULE_expr2op = 26 RULE_expr1 = 27 RULE_expr0 = 28 RULE_identifierExpression = 29 RULE_literal = 30 RULE_intLiteral = 31 RULE_boolLiteral = 32 RULE_stringLiteral = 33 RULE_tupleLiteral = 34 RULE_listLiteral = 35 ruleNames = [ "module", "decl", "varDecl", "funcDecl", "argList", "arg", "typeDecl", "classDecl", "typeExpr", "idType", "listType", "tupleType", "statement", "block", "exprStmt", "assign_op", "ifStmt", "whileStmt", "forStmt", "returnStmt", "breakStmt", "continueStmt", "expr", "expr5op", "expr4op", "expr3op", "expr2op", "expr1", "expr0", "identifierExpression", "literal", "intLiteral", "boolLiteral", "stringLiteral", "tupleLiteral", "listLiteral" ] EOF = Token.EOF T__0=1 T__1=2 T__2=3 T__3=4 T__4=5 T__5=6 T__6=7 T__7=8 T__8=9 T__9=10 T__10=11 T__11=12 T__12=13 T__13=14 T__14=15 T__15=16 T__16=17 T__17=18 T__18=19 T__19=20 T__20=21 T__21=22 T__22=23 T__23=24 T__24=25 T__25=26 T__26=27 T__27=28 T__28=29 T__29=30 T__30=31 T__31=32 T__32=33 T__33=34 T__34=35 T__35=36 T__36=37 T__37=38 T__38=39 T__39=40 T__40=41 T__41=42 T__42=43 T__43=44 T__44=45 T__45=46 T__46=47 T__47=48 T__48=49 T__49=50 T__50=51 T__51=52 T__52=53 BOOL=54 ID=55 INT=56 STRING=57 WS=58 def __init__(self, input:TokenStream): super().__init__(input) self.checkVersion("4.5.3") self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache) self._predicates = None class ModuleContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def decl(self, i:int=None): if i is None: return self.getTypedRuleContexts(ZeamplParser.DeclContext) else: return self.getTypedRuleContext(ZeamplParser.DeclContext,i) def getRuleIndex(self): return ZeamplParser.RULE_module def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitModule" ): return visitor.visitModule(self) else: return visitor.visitChildren(self) def module(self): localctx = ZeamplParser.ModuleContext(self, self._ctx, self.state) self.enterRule(localctx, 0, self.RULE_module) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 75 self._errHandler.sync(self) _la = self._input.LA(1) while (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << ZeamplParser.T__0) | (1 << ZeamplParser.T__3) | (1 << ZeamplParser.T__4) | (1 << ZeamplParser.T__9) | (1 << ZeamplParser.T__10))) != 0): self.state = 72 self.decl() self.state = 77 self._errHandler.sync(self) _la = self._input.LA(1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class DeclContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def varDecl(self): return self.getTypedRuleContext(ZeamplParser.VarDeclContext,0) def funcDecl(self): return self.getTypedRuleContext(ZeamplParser.FuncDeclContext,0) def typeDecl(self): return self.getTypedRuleContext(ZeamplParser.TypeDeclContext,0) def classDecl(self): return self.getTypedRuleContext(ZeamplParser.ClassDeclContext,0) def getRuleIndex(self): return ZeamplParser.RULE_decl def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitDecl" ): return visitor.visitDecl(self) else: return visitor.visitChildren(self) def decl(self): localctx = ZeamplParser.DeclContext(self, self._ctx, self.state) self.enterRule(localctx, 2, self.RULE_decl) try: self.state = 82 token = self._input.LA(1) if token in [ZeamplParser.T__0]: self.enterOuterAlt(localctx, 1) self.state = 78 self.varDecl() elif token in [ZeamplParser.T__3, ZeamplParser.T__4]: self.enterOuterAlt(localctx, 2) self.state = 79 self.funcDecl() elif token in [ZeamplParser.T__9]: self.enterOuterAlt(localctx, 3) self.state = 80 self.typeDecl() elif token in [ZeamplParser.T__10]: self.enterOuterAlt(localctx, 4) self.state = 81 self.classDecl() else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class VarDeclContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def ID(self): return self.getToken(ZeamplParser.ID, 0) def typeExpr(self): return self.getTypedRuleContext(ZeamplParser.TypeExprContext,0) def expr(self): return self.getTypedRuleContext(ZeamplParser.ExprContext,0) def getRuleIndex(self): return ZeamplParser.RULE_varDecl def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitVarDecl" ): return visitor.visitVarDecl(self) else: return visitor.visitChildren(self) def varDecl(self): localctx = ZeamplParser.VarDeclContext(self, self._ctx, self.state) self.enterRule(localctx, 4, self.RULE_varDecl) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 84 self.match(ZeamplParser.T__0) self.state = 85 self.match(ZeamplParser.ID) self.state = 86 self.typeExpr() self.state = 89 _la = self._input.LA(1) if _la==ZeamplParser.T__1: self.state = 87 self.match(ZeamplParser.T__1) self.state = 88 self.expr(0) self.state = 91 self.match(ZeamplParser.T__2) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class FuncDeclContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def block(self): return self.getTypedRuleContext(ZeamplParser.BlockContext,0) def ID(self): return self.getToken(ZeamplParser.ID, 0) def argList(self): return self.getTypedRuleContext(ZeamplParser.ArgListContext,0) def typeExpr(self): return self.getTypedRuleContext(ZeamplParser.TypeExprContext,0) def getRuleIndex(self): return ZeamplParser.RULE_funcDecl def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitFuncDecl" ): return visitor.visitFuncDecl(self) else: return visitor.visitChildren(self) def funcDecl(self): localctx = ZeamplParser.FuncDeclContext(self, self._ctx, self.state) self.enterRule(localctx, 6, self.RULE_funcDecl) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 96 token = self._input.LA(1) if token in [ZeamplParser.T__3]: self.state = 93 self.match(ZeamplParser.T__3) self.state = 94 self.match(ZeamplParser.ID) elif token in [ZeamplParser.T__4]: self.state = 95 self.match(ZeamplParser.T__4) else: raise NoViableAltException(self) self.state = 98 self.match(ZeamplParser.T__5) self.state = 100 _la = self._input.LA(1) if _la==ZeamplParser.T__8: self.state = 99 self.argList() self.state = 102 self.match(ZeamplParser.T__6) self.state = 104 _la = self._input.LA(1) if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << ZeamplParser.T__5) | (1 << ZeamplParser.T__13) | (1 << ZeamplParser.ID))) != 0): self.state = 103 self.typeExpr() self.state = 106 self.block() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ArgListContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def arg(self, i:int=None): if i is None: return self.getTypedRuleContexts(ZeamplParser.ArgContext) else: return self.getTypedRuleContext(ZeamplParser.ArgContext,i) def getRuleIndex(self): return ZeamplParser.RULE_argList def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitArgList" ): return visitor.visitArgList(self) else: return visitor.visitChildren(self) def argList(self): localctx = ZeamplParser.ArgListContext(self, self._ctx, self.state) self.enterRule(localctx, 8, self.RULE_argList) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 108 self.arg() self.state = 113 self._errHandler.sync(self) _la = self._input.LA(1) while _la==ZeamplParser.T__7: self.state = 109 self.match(ZeamplParser.T__7) self.state = 110 self.arg() self.state = 115 self._errHandler.sync(self) _la = self._input.LA(1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ArgContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def typeExpr(self): return self.getTypedRuleContext(ZeamplParser.TypeExprContext,0) def getRuleIndex(self): return ZeamplParser.RULE_arg def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitArg" ): return visitor.visitArg(self) else: return visitor.visitChildren(self) def arg(self): localctx = ZeamplParser.ArgContext(self, self._ctx, self.state) self.enterRule(localctx, 10, self.RULE_arg) try: self.enterOuterAlt(localctx, 1) self.state = 116 self.match(ZeamplParser.T__8) self.state = 117 self.typeExpr() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class TypeDeclContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def ID(self): return self.getToken(ZeamplParser.ID, 0) def typeExpr(self): return self.getTypedRuleContext(ZeamplParser.TypeExprContext,0) def getRuleIndex(self): return ZeamplParser.RULE_typeDecl def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitTypeDecl" ): return visitor.visitTypeDecl(self) else: return visitor.visitChildren(self) def typeDecl(self): localctx = ZeamplParser.TypeDeclContext(self, self._ctx, self.state) self.enterRule(localctx, 12, self.RULE_typeDecl) try: self.enterOuterAlt(localctx, 1) self.state = 119 self.match(ZeamplParser.T__9) self.state = 120 self.match(ZeamplParser.ID) self.state = 121 self.match(ZeamplParser.T__1) self.state = 122 self.typeExpr() self.state = 123 self.match(ZeamplParser.T__2) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ClassDeclContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def ID(self): return self.getToken(ZeamplParser.ID, 0) def decl(self, i:int=None): if i is None: return self.getTypedRuleContexts(ZeamplParser.DeclContext) else: return self.getTypedRuleContext(ZeamplParser.DeclContext,i) def getRuleIndex(self): return ZeamplParser.RULE_classDecl def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitClassDecl" ): return visitor.visitClassDecl(self) else: return visitor.visitChildren(self) def classDecl(self): localctx = ZeamplParser.ClassDeclContext(self, self._ctx, self.state) self.enterRule(localctx, 14, self.RULE_classDecl) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 125 self.match(ZeamplParser.T__10) self.state = 126 self.match(ZeamplParser.ID) self.state = 127 self.match(ZeamplParser.T__11) self.state = 131 self._errHandler.sync(self) _la = self._input.LA(1) while (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << ZeamplParser.T__0) | (1 << ZeamplParser.T__3) | (1 << ZeamplParser.T__4) | (1 << ZeamplParser.T__9) | (1 << ZeamplParser.T__10))) != 0): self.state = 128 self.decl() self.state = 133 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 134 self.match(ZeamplParser.T__12) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class TypeExprContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def idType(self): return self.getTypedRuleContext(ZeamplParser.IdTypeContext,0) def listType(self): return self.getTypedRuleContext(ZeamplParser.ListTypeContext,0) def tupleType(self): return self.getTypedRuleContext(ZeamplParser.TupleTypeContext,0) def getRuleIndex(self): return ZeamplParser.RULE_typeExpr def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitTypeExpr" ): return visitor.visitTypeExpr(self) else: return visitor.visitChildren(self) def typeExpr(self): localctx = ZeamplParser.TypeExprContext(self, self._ctx, self.state) self.enterRule(localctx, 16, self.RULE_typeExpr) try: self.state = 139 token = self._input.LA(1) if token in [ZeamplParser.ID]: self.enterOuterAlt(localctx, 1) self.state = 136 self.idType() elif token in [ZeamplParser.T__13]: self.enterOuterAlt(localctx, 2) self.state = 137 self.listType() elif token in [ZeamplParser.T__5]: self.enterOuterAlt(localctx, 3) self.state = 138 self.tupleType() else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class IdTypeContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def ID(self): return self.getToken(ZeamplParser.ID, 0) def getRuleIndex(self): return ZeamplParser.RULE_idType def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitIdType" ): return visitor.visitIdType(self) else: return visitor.visitChildren(self) def idType(self): localctx = ZeamplParser.IdTypeContext(self, self._ctx, self.state) self.enterRule(localctx, 18, self.RULE_idType) try: self.enterOuterAlt(localctx, 1) self.state = 141 self.match(ZeamplParser.ID) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ListTypeContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def typeExpr(self): return self.getTypedRuleContext(ZeamplParser.TypeExprContext,0) def getRuleIndex(self): return ZeamplParser.RULE_listType def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitListType" ): return visitor.visitListType(self) else: return visitor.visitChildren(self) def listType(self): localctx = ZeamplParser.ListTypeContext(self, self._ctx, self.state) self.enterRule(localctx, 20, self.RULE_listType) try: self.enterOuterAlt(localctx, 1) self.state = 143 self.match(ZeamplParser.T__13) self.state = 144 self.typeExpr() self.state = 145 self.match(ZeamplParser.T__14) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class TupleTypeContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def typeExpr(self, i:int=None): if i is None: return self.getTypedRuleContexts(ZeamplParser.TypeExprContext) else: return self.getTypedRuleContext(ZeamplParser.TypeExprContext,i) def getRuleIndex(self): return ZeamplParser.RULE_tupleType def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitTupleType" ): return visitor.visitTupleType(self) else: return visitor.visitChildren(self) def tupleType(self): localctx = ZeamplParser.TupleTypeContext(self, self._ctx, self.state) self.enterRule(localctx, 22, self.RULE_tupleType) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 147 self.match(ZeamplParser.T__5) self.state = 160 _la = self._input.LA(1) if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << ZeamplParser.T__5) | (1 << ZeamplParser.T__13) | (1 << ZeamplParser.ID))) != 0): self.state = 148 self.typeExpr() self.state = 149 self.match(ZeamplParser.T__7) self.state = 158 _la = self._input.LA(1) if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << ZeamplParser.T__5) | (1 << ZeamplParser.T__13) | (1 << ZeamplParser.ID))) != 0): self.state = 150 self.typeExpr() self.state = 155 self._errHandler.sync(self) _la = self._input.LA(1) while _la==ZeamplParser.T__7: self.state = 151 self.match(ZeamplParser.T__7) self.state = 152 self.typeExpr() self.state = 157 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 162 self.match(ZeamplParser.T__6) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class StatementContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def block(self): return self.getTypedRuleContext(ZeamplParser.BlockContext,0) def exprStmt(self): return self.getTypedRuleContext(ZeamplParser.ExprStmtContext,0) def ifStmt(self): return self.getTypedRuleContext(ZeamplParser.IfStmtContext,0) def whileStmt(self): return self.getTypedRuleContext(ZeamplParser.WhileStmtContext,0) def forStmt(self): return self.getTypedRuleContext(ZeamplParser.ForStmtContext,0) def returnStmt(self): return self.getTypedRuleContext(ZeamplParser.ReturnStmtContext,0) def breakStmt(self): return self.getTypedRuleContext(ZeamplParser.BreakStmtContext,0) def continueStmt(self): return self.getTypedRuleContext(ZeamplParser.ContinueStmtContext,0) def getRuleIndex(self): return ZeamplParser.RULE_statement def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitStatement" ): return visitor.visitStatement(self) else: return visitor.visitChildren(self) def statement(self): localctx = ZeamplParser.StatementContext(self, self._ctx, self.state) self.enterRule(localctx, 24, self.RULE_statement) try: self.state = 172 token = self._input.LA(1) if token in [ZeamplParser.T__11]: self.enterOuterAlt(localctx, 1) self.state = 164 self.block() elif token in [ZeamplParser.T__5, ZeamplParser.T__13, ZeamplParser.T__41, ZeamplParser.T__42, ZeamplParser.T__51, ZeamplParser.BOOL, ZeamplParser.ID, ZeamplParser.INT, ZeamplParser.STRING]: self.enterOuterAlt(localctx, 2) self.state = 165 self.exprStmt() elif token in [ZeamplParser.T__26]: self.enterOuterAlt(localctx, 3) self.state = 166 self.ifStmt() elif token in [ZeamplParser.T__29]: self.enterOuterAlt(localctx, 4) self.state = 167 self.whileStmt() elif token in [ZeamplParser.T__30]: self.enterOuterAlt(localctx, 5) self.state = 168 self.forStmt() elif token in [ZeamplParser.T__32]: self.enterOuterAlt(localctx, 6) self.state = 169 self.returnStmt() elif token in [ZeamplParser.T__33]: self.enterOuterAlt(localctx, 7) self.state = 170 self.breakStmt() elif token in [ZeamplParser.T__34]: self.enterOuterAlt(localctx, 8) self.state = 171 self.continueStmt() else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class BlockContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def statement(self, i:int=None): if i is None: return self.getTypedRuleContexts(ZeamplParser.StatementContext) else: return self.getTypedRuleContext(ZeamplParser.StatementContext,i) def getRuleIndex(self): return ZeamplParser.RULE_block def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitBlock" ): return visitor.visitBlock(self) else: return visitor.visitChildren(self) def block(self): localctx = ZeamplParser.BlockContext(self, self._ctx, self.state) self.enterRule(localctx, 26, self.RULE_block) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 174 self.match(ZeamplParser.T__11) self.state = 178 self._errHandler.sync(self) _la = self._input.LA(1) while (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << ZeamplParser.T__5) | (1 << ZeamplParser.T__11) | (1 << ZeamplParser.T__13) | (1 << ZeamplParser.T__26) | (1 << ZeamplParser.T__29) | (1 << ZeamplParser.T__30) | (1 << ZeamplParser.T__32) | (1 << ZeamplParser.T__33) | (1 << ZeamplParser.T__34) | (1 << ZeamplParser.T__41) | (1 << ZeamplParser.T__42) | (1 << ZeamplParser.T__51) | (1 << ZeamplParser.BOOL) | (1 << ZeamplParser.ID) | (1 << ZeamplParser.INT) | (1 << ZeamplParser.STRING))) != 0): self.state = 175 self.statement() self.state = 180 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 181 self.match(ZeamplParser.T__12) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ExprStmtContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(ZeamplParser.ExprContext) else: return self.getTypedRuleContext(ZeamplParser.ExprContext,i) def assign_op(self): return self.getTypedRuleContext(ZeamplParser.Assign_opContext,0) def getRuleIndex(self): return ZeamplParser.RULE_exprStmt def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitExprStmt" ): return visitor.visitExprStmt(self) else: return visitor.visitChildren(self) def exprStmt(self): localctx = ZeamplParser.ExprStmtContext(self, self._ctx, self.state) self.enterRule(localctx, 28, self.RULE_exprStmt) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 183 self.expr(0) self.state = 187 _la = self._input.LA(1) if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << ZeamplParser.T__1) | (1 << ZeamplParser.T__15) | (1 << ZeamplParser.T__16) | (1 << ZeamplParser.T__17) | (1 << ZeamplParser.T__18) | (1 << ZeamplParser.T__19) | (1 << ZeamplParser.T__20) | (1 << ZeamplParser.T__21) | (1 << ZeamplParser.T__22) | (1 << ZeamplParser.T__23) | (1 << ZeamplParser.T__24) | (1 << ZeamplParser.T__25))) != 0): self.state = 184 self.assign_op() self.state = 185 self.expr(0) self.state = 189 self.match(ZeamplParser.T__2) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Assign_opContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return ZeamplParser.RULE_assign_op def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitAssign_op" ): return visitor.visitAssign_op(self) else: return visitor.visitChildren(self) def assign_op(self): localctx = ZeamplParser.Assign_opContext(self, self._ctx, self.state) self.enterRule(localctx, 30, self.RULE_assign_op) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 191 _la = self._input.LA(1) if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << ZeamplParser.T__1) | (1 << ZeamplParser.T__15) | (1 << ZeamplParser.T__16) | (1 << ZeamplParser.T__17) | (1 << ZeamplParser.T__18) | (1 << ZeamplParser.T__19) | (1 << ZeamplParser.T__20) | (1 << ZeamplParser.T__21) | (1 << ZeamplParser.T__22) | (1 << ZeamplParser.T__23) | (1 << ZeamplParser.T__24) | (1 << ZeamplParser.T__25))) != 0)): self._errHandler.recoverInline(self) else: self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class IfStmtContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(ZeamplParser.ExprContext) else: return self.getTypedRuleContext(ZeamplParser.ExprContext,i) def block(self, i:int=None): if i is None: return self.getTypedRuleContexts(ZeamplParser.BlockContext) else: return self.getTypedRuleContext(ZeamplParser.BlockContext,i) def getRuleIndex(self): return ZeamplParser.RULE_ifStmt def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitIfStmt" ): return visitor.visitIfStmt(self) else: return visitor.visitChildren(self) def ifStmt(self): localctx = ZeamplParser.IfStmtContext(self, self._ctx, self.state) self.enterRule(localctx, 32, self.RULE_ifStmt) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 193 self.match(ZeamplParser.T__26) self.state = 194 self.expr(0) self.state = 195 self.block() self.state = 202 self._errHandler.sync(self) _la = self._input.LA(1) while _la==ZeamplParser.T__27: self.state = 196 self.match(ZeamplParser.T__27) self.state = 197 self.expr(0) self.state = 198 self.block() self.state = 204 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 207 _la = self._input.LA(1) if _la==ZeamplParser.T__28: self.state = 205 self.match(ZeamplParser.T__28) self.state = 206 self.block() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class WhileStmtContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def expr(self): return self.getTypedRuleContext(ZeamplParser.ExprContext,0) def block(self): return self.getTypedRuleContext(ZeamplParser.BlockContext,0) def getRuleIndex(self): return ZeamplParser.RULE_whileStmt def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitWhileStmt" ): return visitor.visitWhileStmt(self) else: return visitor.visitChildren(self) def whileStmt(self): localctx = ZeamplParser.WhileStmtContext(self, self._ctx, self.state) self.enterRule(localctx, 34, self.RULE_whileStmt) try: self.enterOuterAlt(localctx, 1) self.state = 209 self.match(ZeamplParser.T__29) self.state = 210 self.expr(0) self.state = 211 self.block() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ForStmtContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def ID(self): return self.getToken(ZeamplParser.ID, 0) def expr(self): return self.getTypedRuleContext(ZeamplParser.ExprContext,0) def block(self): return self.getTypedRuleContext(ZeamplParser.BlockContext,0) def getRuleIndex(self): return ZeamplParser.RULE_forStmt def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitForStmt" ): return visitor.visitForStmt(self) else: return visitor.visitChildren(self) def forStmt(self): localctx = ZeamplParser.ForStmtContext(self, self._ctx, self.state) self.enterRule(localctx, 36, self.RULE_forStmt) try: self.enterOuterAlt(localctx, 1) self.state = 213 self.match(ZeamplParser.T__30) self.state = 214 self.match(ZeamplParser.ID) self.state = 215 self.match(ZeamplParser.T__31) self.state = 216 self.expr(0) self.state = 217 self.block() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ReturnStmtContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def expr(self): return self.getTypedRuleContext(ZeamplParser.ExprContext,0) def getRuleIndex(self): return ZeamplParser.RULE_returnStmt def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitReturnStmt" ): return visitor.visitReturnStmt(self) else: return visitor.visitChildren(self) def returnStmt(self): localctx = ZeamplParser.ReturnStmtContext(self, self._ctx, self.state) self.enterRule(localctx, 38, self.RULE_returnStmt) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 219 self.match(ZeamplParser.T__32) self.state = 221 _la = self._input.LA(1) if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << ZeamplParser.T__5) | (1 << ZeamplParser.T__13) | (1 << ZeamplParser.T__41) | (1 << ZeamplParser.T__42) | (1 << ZeamplParser.T__51) | (1 << ZeamplParser.BOOL) | (1 << ZeamplParser.ID) | (1 << ZeamplParser.INT) | (1 << ZeamplParser.STRING))) != 0): self.state = 220 self.expr(0) self.state = 223 self.match(ZeamplParser.T__2) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class BreakStmtContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return ZeamplParser.RULE_breakStmt def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitBreakStmt" ): return visitor.visitBreakStmt(self) else: return visitor.visitChildren(self) def breakStmt(self): localctx = ZeamplParser.BreakStmtContext(self, self._ctx, self.state) self.enterRule(localctx, 40, self.RULE_breakStmt) try: self.enterOuterAlt(localctx, 1) self.state = 225 self.match(ZeamplParser.T__33) self.state = 226 self.match(ZeamplParser.T__2) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ContinueStmtContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return ZeamplParser.RULE_continueStmt def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitContinueStmt" ): return visitor.visitContinueStmt(self) else: return visitor.visitChildren(self) def continueStmt(self): localctx = ZeamplParser.ContinueStmtContext(self, self._ctx, self.state) self.enterRule(localctx, 42, self.RULE_continueStmt) try: self.enterOuterAlt(localctx, 1) self.state = 228 self.match(ZeamplParser.T__34) self.state = 229 self.match(ZeamplParser.T__2) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ExprContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return ZeamplParser.RULE_expr def copyFrom(self, ctx:ParserRuleContext): super().copyFrom(ctx) class AtomContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a ZeamplParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def expr1(self): return self.getTypedRuleContext(ZeamplParser.Expr1Context,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitAtom" ): return visitor.visitAtom(self) else: return visitor.visitChildren(self) class PrefixOpContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a ZeamplParser.ExprContext super().__init__(parser) self.op = None # Expr2opContext self.x = None # ExprContext self.copyFrom(ctx) def expr2op(self): return self.getTypedRuleContext(ZeamplParser.Expr2opContext,0) def expr(self): return self.getTypedRuleContext(ZeamplParser.ExprContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitPrefixOp" ): return visitor.visitPrefixOp(self) else: return visitor.visitChildren(self) class BinaryOpContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a ZeamplParser.ExprContext super().__init__(parser) self.lhs = None # ExprContext self.op = None # Expr3opContext self.rhs = None # ExprContext self.copyFrom(ctx) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(ZeamplParser.ExprContext) else: return self.getTypedRuleContext(ZeamplParser.ExprContext,i) def expr3op(self): return self.getTypedRuleContext(ZeamplParser.Expr3opContext,0) def expr4op(self): return self.getTypedRuleContext(ZeamplParser.Expr4opContext,0) def expr5op(self): return self.getTypedRuleContext(ZeamplParser.Expr5opContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitBinaryOp" ): return visitor.visitBinaryOp(self) else: return visitor.visitChildren(self) def expr(self, _p:int=0): _parentctx = self._ctx _parentState = self.state localctx = ZeamplParser.ExprContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 44 self.enterRecursionRule(localctx, 44, self.RULE_expr, _p) try: self.enterOuterAlt(localctx, 1) self.state = 236 token = self._input.LA(1) if token in [ZeamplParser.T__5, ZeamplParser.T__13, ZeamplParser.BOOL, ZeamplParser.ID, ZeamplParser.INT, ZeamplParser.STRING]: localctx = ZeamplParser.AtomContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 232 self.expr1(0) elif token in [ZeamplParser.T__41, ZeamplParser.T__42, ZeamplParser.T__51]: localctx = ZeamplParser.PrefixOpContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 233 localctx.op = self.expr2op() self.state = 234 localctx.x = self.expr(4) else: raise NoViableAltException(self) self._ctx.stop = self._input.LT(-1) self.state = 252 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,20,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx self.state = 250 self._errHandler.sync(self); la_ = self._interp.adaptivePredict(self._input,19,self._ctx) if la_ == 1: localctx = ZeamplParser.BinaryOpContext(self, ZeamplParser.ExprContext(self, _parentctx, _parentState)) localctx.lhs = _prevctx self.pushNewRecursionContext(localctx, _startState, self.RULE_expr) self.state = 238 if not self.precpred(self._ctx, 3): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 3)") self.state = 239 localctx.op = self.expr3op() self.state = 240 localctx.rhs = self.expr(4) pass elif la_ == 2: localctx = ZeamplParser.BinaryOpContext(self, ZeamplParser.ExprContext(self, _parentctx, _parentState)) localctx.lhs = _prevctx self.pushNewRecursionContext(localctx, _startState, self.RULE_expr) self.state = 242 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 243 localctx.op = self.expr4op() self.state = 244 localctx.rhs = self.expr(3) pass elif la_ == 3: localctx = ZeamplParser.BinaryOpContext(self, ZeamplParser.ExprContext(self, _parentctx, _parentState)) localctx.lhs = _prevctx self.pushNewRecursionContext(localctx, _startState, self.RULE_expr) self.state = 246 if not self.precpred(self._ctx, 1): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 1)") self.state = 247 localctx.op = self.expr5op() self.state = 248 localctx.rhs = self.expr(2) pass self.state = 254 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,20,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class Expr5opContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return ZeamplParser.RULE_expr5op def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitExpr5op" ): return visitor.visitExpr5op(self) else: return visitor.visitChildren(self) def expr5op(self): localctx = ZeamplParser.Expr5opContext(self, self._ctx, self.state) self.enterRule(localctx, 46, self.RULE_expr5op) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 255 _la = self._input.LA(1) if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << ZeamplParser.T__35) | (1 << ZeamplParser.T__36) | (1 << ZeamplParser.T__37) | (1 << ZeamplParser.T__38) | (1 << ZeamplParser.T__39) | (1 << ZeamplParser.T__40))) != 0)): self._errHandler.recoverInline(self) else: self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Expr4opContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return ZeamplParser.RULE_expr4op def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitExpr4op" ): return visitor.visitExpr4op(self) else: return visitor.visitChildren(self) def expr4op(self): localctx = ZeamplParser.Expr4opContext(self, self._ctx, self.state) self.enterRule(localctx, 48, self.RULE_expr4op) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 257 _la = self._input.LA(1) if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << ZeamplParser.T__41) | (1 << ZeamplParser.T__42) | (1 << ZeamplParser.T__43) | (1 << ZeamplParser.T__44))) != 0)): self._errHandler.recoverInline(self) else: self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Expr3opContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return ZeamplParser.RULE_expr3op def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitExpr3op" ): return visitor.visitExpr3op(self) else: return visitor.visitChildren(self) def expr3op(self): localctx = ZeamplParser.Expr3opContext(self, self._ctx, self.state) self.enterRule(localctx, 50, self.RULE_expr3op) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 259 _la = self._input.LA(1) if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << ZeamplParser.T__45) | (1 << ZeamplParser.T__46) | (1 << ZeamplParser.T__47) | (1 << ZeamplParser.T__48) | (1 << ZeamplParser.T__49) | (1 << ZeamplParser.T__50))) != 0)): self._errHandler.recoverInline(self) else: self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Expr2opContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return ZeamplParser.RULE_expr2op def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitExpr2op" ): return visitor.visitExpr2op(self) else: return visitor.visitChildren(self) def expr2op(self): localctx = ZeamplParser.Expr2opContext(self, self._ctx, self.state) self.enterRule(localctx, 52, self.RULE_expr2op) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 261 _la = self._input.LA(1) if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << ZeamplParser.T__41) | (1 << ZeamplParser.T__42) | (1 << ZeamplParser.T__51))) != 0)): self._errHandler.recoverInline(self) else: self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Expr1Context(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return ZeamplParser.RULE_expr1 def copyFrom(self, ctx:ParserRuleContext): super().copyFrom(ctx) class CallContext(Expr1Context): def __init__(self, parser, ctx:ParserRuleContext): # actually a ZeamplParser.Expr1Context super().__init__(parser) self._expr = None # ExprContext self.args = list() # of ExprContexts self.copyFrom(ctx) def expr1(self): return self.getTypedRuleContext(ZeamplParser.Expr1Context,0) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(ZeamplParser.ExprContext) else: return self.getTypedRuleContext(ZeamplParser.ExprContext,i) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitCall" ): return visitor.visitCall(self) else: return visitor.visitChildren(self) class MemberAccessContext(Expr1Context): def __init__(self, parser, ctx:ParserRuleContext): # actually a ZeamplParser.Expr1Context super().__init__(parser) self.copyFrom(ctx) def expr1(self): return self.getTypedRuleContext(ZeamplParser.Expr1Context,0) def ID(self): return self.getToken(ZeamplParser.ID, 0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitMemberAccess" ): return visitor.visitMemberAccess(self) else: return visitor.visitChildren(self) class Atom0Context(Expr1Context): def __init__(self, parser, ctx:ParserRuleContext): # actually a ZeamplParser.Expr1Context super().__init__(parser) self.copyFrom(ctx) def expr0(self): return self.getTypedRuleContext(ZeamplParser.Expr0Context,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitAtom0" ): return visitor.visitAtom0(self) else: return visitor.visitChildren(self) def expr1(self, _p:int=0): _parentctx = self._ctx _parentState = self.state localctx = ZeamplParser.Expr1Context(self, self._ctx, _parentState) _prevctx = localctx _startState = 54 self.enterRecursionRule(localctx, 54, self.RULE_expr1, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) localctx = ZeamplParser.Atom0Context(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 264 self.expr0() self._ctx.stop = self._input.LT(-1) self.state = 283 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,23,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx self.state = 281 self._errHandler.sync(self); la_ = self._interp.adaptivePredict(self._input,22,self._ctx) if la_ == 1: localctx = ZeamplParser.MemberAccessContext(self, ZeamplParser.Expr1Context(self, _parentctx, _parentState)) self.pushNewRecursionContext(localctx, _startState, self.RULE_expr1) self.state = 266 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 267 self.match(ZeamplParser.T__52) self.state = 268 self.match(ZeamplParser.ID) pass elif la_ == 2: localctx = ZeamplParser.CallContext(self, ZeamplParser.Expr1Context(self, _parentctx, _parentState)) self.pushNewRecursionContext(localctx, _startState, self.RULE_expr1) self.state = 269 if not self.precpred(self._ctx, 1): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 1)") self.state = 270 self.match(ZeamplParser.T__5) self.state = 271 localctx._expr = self.expr(0) localctx.args.append(localctx._expr) self.state = 276 self._errHandler.sync(self) _la = self._input.LA(1) while _la==ZeamplParser.T__7: self.state = 272 self.match(ZeamplParser.T__7) self.state = 273 localctx._expr = self.expr(0) localctx.args.append(localctx._expr) self.state = 278 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 279 self.match(ZeamplParser.T__6) pass self.state = 285 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,23,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class Expr0Context(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def identifierExpression(self): return self.getTypedRuleContext(ZeamplParser.IdentifierExpressionContext,0) def literal(self): return self.getTypedRuleContext(ZeamplParser.LiteralContext,0) def expr(self): return self.getTypedRuleContext(ZeamplParser.ExprContext,0) def getRuleIndex(self): return ZeamplParser.RULE_expr0 def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitExpr0" ): return visitor.visitExpr0(self) else: return visitor.visitChildren(self) def expr0(self): localctx = ZeamplParser.Expr0Context(self, self._ctx, self.state) self.enterRule(localctx, 56, self.RULE_expr0) try: self.state = 292 self._errHandler.sync(self); la_ = self._interp.adaptivePredict(self._input,24,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 286 self.identifierExpression() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 287 self.literal() pass elif la_ == 3: self.enterOuterAlt(localctx, 3) self.state = 288 self.match(ZeamplParser.T__5) self.state = 289 self.expr(0) self.state = 290 self.match(ZeamplParser.T__6) pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class IdentifierExpressionContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def ID(self): return self.getToken(ZeamplParser.ID, 0) def getRuleIndex(self): return ZeamplParser.RULE_identifierExpression def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitIdentifierExpression" ): return visitor.visitIdentifierExpression(self) else: return visitor.visitChildren(self) def identifierExpression(self): localctx = ZeamplParser.IdentifierExpressionContext(self, self._ctx, self.state) self.enterRule(localctx, 58, self.RULE_identifierExpression) try: self.enterOuterAlt(localctx, 1) self.state = 294 self.match(ZeamplParser.ID) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class LiteralContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def intLiteral(self): return self.getTypedRuleContext(ZeamplParser.IntLiteralContext,0) def boolLiteral(self): return self.getTypedRuleContext(ZeamplParser.BoolLiteralContext,0) def stringLiteral(self): return self.getTypedRuleContext(ZeamplParser.StringLiteralContext,0) def tupleLiteral(self): return self.getTypedRuleContext(ZeamplParser.TupleLiteralContext,0) def listLiteral(self): return self.getTypedRuleContext(ZeamplParser.ListLiteralContext,0) def getRuleIndex(self): return ZeamplParser.RULE_literal def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitLiteral" ): return visitor.visitLiteral(self) else: return visitor.visitChildren(self) def literal(self): localctx = ZeamplParser.LiteralContext(self, self._ctx, self.state) self.enterRule(localctx, 60, self.RULE_literal) try: self.state = 301 token = self._input.LA(1) if token in [ZeamplParser.INT]: self.enterOuterAlt(localctx, 1) self.state = 296 self.intLiteral() elif token in [ZeamplParser.BOOL]: self.enterOuterAlt(localctx, 2) self.state = 297 self.boolLiteral() elif token in [ZeamplParser.STRING]: self.enterOuterAlt(localctx, 3) self.state = 298 self.stringLiteral() elif token in [ZeamplParser.T__5]: self.enterOuterAlt(localctx, 4) self.state = 299 self.tupleLiteral() elif token in [ZeamplParser.T__13]: self.enterOuterAlt(localctx, 5) self.state = 300 self.listLiteral() else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class IntLiteralContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def INT(self): return self.getToken(ZeamplParser.INT, 0) def getRuleIndex(self): return ZeamplParser.RULE_intLiteral def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitIntLiteral" ): return visitor.visitIntLiteral(self) else: return visitor.visitChildren(self) def intLiteral(self): localctx = ZeamplParser.IntLiteralContext(self, self._ctx, self.state) self.enterRule(localctx, 62, self.RULE_intLiteral) try: self.enterOuterAlt(localctx, 1) self.state = 303 self.match(ZeamplParser.INT) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class BoolLiteralContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def BOOL(self): return self.getToken(ZeamplParser.BOOL, 0) def getRuleIndex(self): return ZeamplParser.RULE_boolLiteral def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitBoolLiteral" ): return visitor.visitBoolLiteral(self) else: return visitor.visitChildren(self) def boolLiteral(self): localctx = ZeamplParser.BoolLiteralContext(self, self._ctx, self.state) self.enterRule(localctx, 64, self.RULE_boolLiteral) try: self.enterOuterAlt(localctx, 1) self.state = 305 self.match(ZeamplParser.BOOL) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class StringLiteralContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def STRING(self): return self.getToken(ZeamplParser.STRING, 0) def getRuleIndex(self): return ZeamplParser.RULE_stringLiteral def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitStringLiteral" ): return visitor.visitStringLiteral(self) else: return visitor.visitChildren(self) def stringLiteral(self): localctx = ZeamplParser.StringLiteralContext(self, self._ctx, self.state) self.enterRule(localctx, 66, self.RULE_stringLiteral) try: self.enterOuterAlt(localctx, 1) self.state = 307 self.match(ZeamplParser.STRING) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class TupleLiteralContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser self._expr = None # ExprContext self.x = list() # of ExprContexts def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(ZeamplParser.ExprContext) else: return self.getTypedRuleContext(ZeamplParser.ExprContext,i) def getRuleIndex(self): return ZeamplParser.RULE_tupleLiteral def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitTupleLiteral" ): return visitor.visitTupleLiteral(self) else: return visitor.visitChildren(self) def tupleLiteral(self): localctx = ZeamplParser.TupleLiteralContext(self, self._ctx, self.state) self.enterRule(localctx, 68, self.RULE_tupleLiteral) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 309 self.match(ZeamplParser.T__5) self.state = 322 _la = self._input.LA(1) if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << ZeamplParser.T__5) | (1 << ZeamplParser.T__13) | (1 << ZeamplParser.T__41) | (1 << ZeamplParser.T__42) | (1 << ZeamplParser.T__51) | (1 << ZeamplParser.BOOL) | (1 << ZeamplParser.ID) | (1 << ZeamplParser.INT) | (1 << ZeamplParser.STRING))) != 0): self.state = 310 localctx._expr = self.expr(0) localctx.x.append(localctx._expr) self.state = 311 self.match(ZeamplParser.T__7) self.state = 320 _la = self._input.LA(1) if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << ZeamplParser.T__5) | (1 << ZeamplParser.T__13) | (1 << ZeamplParser.T__41) | (1 << ZeamplParser.T__42) | (1 << ZeamplParser.T__51) | (1 << ZeamplParser.BOOL) | (1 << ZeamplParser.ID) | (1 << ZeamplParser.INT) | (1 << ZeamplParser.STRING))) != 0): self.state = 312 localctx._expr = self.expr(0) localctx.x.append(localctx._expr) self.state = 317 self._errHandler.sync(self) _la = self._input.LA(1) while _la==ZeamplParser.T__7: self.state = 313 self.match(ZeamplParser.T__7) self.state = 314 localctx._expr = self.expr(0) localctx.x.append(localctx._expr) self.state = 319 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 324 self.match(ZeamplParser.T__6) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ListLiteralContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser self._expr = None # ExprContext self.x = list() # of ExprContexts def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(ZeamplParser.ExprContext) else: return self.getTypedRuleContext(ZeamplParser.ExprContext,i) def getRuleIndex(self): return ZeamplParser.RULE_listLiteral def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitListLiteral" ): return visitor.visitListLiteral(self) else: return visitor.visitChildren(self) def listLiteral(self): localctx = ZeamplParser.ListLiteralContext(self, self._ctx, self.state) self.enterRule(localctx, 70, self.RULE_listLiteral) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 326 self.match(ZeamplParser.T__13) self.state = 335 _la = self._input.LA(1) if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << ZeamplParser.T__5) | (1 << ZeamplParser.T__13) | (1 << ZeamplParser.T__41) | (1 << ZeamplParser.T__42) | (1 << ZeamplParser.T__51) | (1 << ZeamplParser.BOOL) | (1 << ZeamplParser.ID) | (1 << ZeamplParser.INT) | (1 << ZeamplParser.STRING))) != 0): self.state = 327 localctx._expr = self.expr(0) localctx.x.append(localctx._expr) self.state = 332 self._errHandler.sync(self) _la = self._input.LA(1) while _la==ZeamplParser.T__7: self.state = 328 self.match(ZeamplParser.T__7) self.state = 329 localctx._expr = self.expr(0) localctx.x.append(localctx._expr) self.state = 334 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 337 self.match(ZeamplParser.T__14) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx def sempred(self, localctx:RuleContext, ruleIndex:int, predIndex:int): if self._predicates == None: self._predicates = dict() self._predicates[22] = self.expr_sempred self._predicates[27] = self.expr1_sempred pred = self._predicates.get(ruleIndex, None) if pred is None: raise Exception("No predicate with index:" + str(ruleIndex)) else: return pred(localctx, predIndex) def expr_sempred(self, localctx:ExprContext, predIndex:int): if predIndex == 0: return self.precpred(self._ctx, 3) if predIndex == 1: return self.precpred(self._ctx, 2) if predIndex == 2: return self.precpred(self._ctx, 1) def expr1_sempred(self, localctx:Expr1Context, predIndex:int): if predIndex == 3: return self.precpred(self._ctx, 2) if predIndex == 4: return self.precpred(self._ctx, 1) <file_sep>/zeampl/ast/decl/declaration.py from ..range import Range class Declaration(object): pass <file_sep>/zeampl/ast/__init__.py from .range import * from .expr import * from .decl import * __all__ = ['Location', 'Range'] + expr.__all__ + decl.__all__ <file_sep>/zeampl/ast/decl/__init__.py from .declaration import Declaration __all__ = [ 'Declaration', ] <file_sep>/pfisher/grammar.swift /* Grammar defintions, non-ternimals and terminals */ import Foundation func == (lhs: Terminal, rhs: Terminal) -> Bool { return lhs.hashValue == rhs.hashValue } func == (lhs: NonTerminal, rhs: NonTerminal) -> Bool { return lhs.hashValue == rhs.hashValue } func == (lhs: Grammar, rhs: Grammar) -> Bool { return true } class Grammar: Hashable { var hashValue: Int {get {return 0}} var value: String? var valueList: [Grammar]? var name: String = "" } class Terminal: Grammar { var uid: Int override var hashValue: Int { get { return self.uid } } init(regex: String, name: String, uid: Int) { self.uid = uid super.init() self.name = name self.value = regex } } class NonTerminal: Grammar { let repeating: Bool override var hashValue: Int { get { var hash: String = "" for term in self.valueList! { hash += String(term.hashValue) } return Int(hash)! } } init(value: [Grammar], repeating: Bool = false, name: String){ self.repeating = repeating super.init() self.name = name self.valueList = value } } class SymbolList: Grammar { override var hashValue: Int { get { var hash = 0 for term in self.valueList! { hash += term.hashValue } return hash } } init(value: [Grammar], name: String){ super.init() self.name = name self.valueList = value } } // Grammar Definition // === Terminal Definitions === let functionStartTerminal = Terminal(regex: "λ", name: "func start symbol", uid: 1) let lambdaTerminal = Terminal(regex: "lambda", name: "Lambda Start Symbol", uid: 2) let paranOpenTerminal = Terminal(regex: "(", name: "paranOpen", uid: 3) let paranCloseTerinal = Terminal(regex: ")", name: "paranclose", uid: 4) let keywordTerminal = Terminal(regex: "[a-zA-Z-]", name: "keyword", uid: 5) let commaTerminal = Terminal(regex: ",", name: "comma", uid: 6) let equalsTerminal = Terminal(regex: "=", name: "equals", uid: 7) let additionTerminal = Terminal(regex: "+", name: "addition operator", uid: 8) let subtractionTerminal = Terminal(regex: "-", name: "subtraction operator", uid: 9) // === Non-Terminal Definitions === let functionParameterNonTerminal = NonTerminal(value: [keywordTerminal, commaTerminal], name: "functionParameter") // TODO deal with ending comma // === Productions === let functionLabda = NonTerminal(value: [lambdaTerminal, keywordTerminal, paranOpenTerminal, functionParameterNonTerminal, paranCloseTerinal], name: "funcLambda") let functionNormal = NonTerminal(value: [functionStartTerminal, keywordTerminal, paranOpenTerminal, functionParameterNonTerminal, paranCloseTerinal], name: "funcλ") // === All Arrays === let productions: [NonTerminal] = [functionLabda, functionNormal] let allNonTerminals: [NonTerminal] = [functionParameterNonTerminal, functionLabda, functionNormal] let allTerminals: [Terminal] = [functionStartTerminal,lambdaTerminal,paranOpenTerminal,paranCloseTerinal,keywordTerminal,commaTerminal,equalsTerminal,additionTerminal,subtractionTerminal, endMarkerTerminal] let allLanguageSymbols = [functionStartTerminal,lambdaTerminal,paranOpenTerminal,paranCloseTerinal,keywordTerminal,commaTerminal,equalsTerminal,additionTerminal,subtractionTerminal, functionParameterNonTerminal] // === Special Grammars === let endMarkerTerminal = Terminal(regex: "ε", name: "end marker", uid: 10) <file_sep>/pfisher/lexer/lexer.swift /* Lexer for parsing the following language: IF statement = 'if' ID = [a-z]+ NUM = [0-9]+ ASSIGN ='=' LT ='<' LE ='<=' EQ ='==' */ import Foundation class RegexEr { static func doesRegexMatchString(regex: String, string: String) -> Bool { let regex = try! NSRegularExpression(pattern: regex, options: []) let match = regex.matchesInString(string, options: [], range: NSMakeRange(0, string.characters.count)) if match.count > 0 { return true} else { return false} } static func isString(ch: String) -> Bool { return RegexEr.doesRegexMatchString(Tag.Identifier.rawValue, string: ch) } static func isWhiteSpace(ch: String) -> Bool { return RegexEr.doesRegexMatchString(Tag.bullshit.rawValue, string: ch) } static func isRelop(ch: String) -> Bool { return RegexEr.doesRegexMatchString(Tag.Relop.rawValue, string: ch) } static func isNumber(ch: String) -> Bool { return RegexEr.doesRegexMatchString(Tag.Number.rawValue, string: ch) } } class Lexer { var words: [String: Token] var line: Int var peek: String? { get { if self.charIndex >= self.inputText.length { return nil } let char = inputText.substringWithRange(NSRange(location: self.charIndex, length: 1)) return char } } var inputText: NSString var charIndex: Int var currentCharacter: String! init() { self.words = [String: Token]() self.line = 0 self.charIndex = 0 self.inputText = NSString() // Known reserved words let if_keyword = Token(tag: Tag.ReservedWord, value: "If") self.add_reserve_word(if_keyword) } func nextCharacter() -> String? { if self.charIndex >= inputText.length { self.currentCharacter = nil return nil } let char = inputText.substringWithRange(NSRange(location: self.charIndex, length: 1)) self.currentCharacter = char self.charIndex += 1 return char } func add_reserve_word(word: Token) { self.words[word.value!] = word } func read_while_tag(tag: Tag) -> String { var string = "" while true { string += self.currentCharacter if self.peek == nil { break } else if RegexEr.doesRegexMatchString(tag.rawValue, string: self.peek!) == false { break } self.nextCharacter() } return string } func readString() -> Token { let string = self.read_while_tag(Tag.Identifier) // Check if reserved word if so return reserved word if let reservedWord = self.words[string] { return reservedWord } // return generic ID token let idToken = Token(tag: Tag.Identifier, value: string) return idToken } func readRepl() -> Token { let string = self.read_while_tag(Tag.Relop) let token = Token(tag: Tag.Relop, value: "") switch string { case "=": token.value = "ASSIGN" case "<": token.value = "LT" case "<=": token.value = "LE" case "==": token.value = "EQ" default: print("Invalid REPL read") } return token } func readNumber() -> Token { let string = self.read_while_tag(Tag.Number) return Token(tag: Tag.Number, value: string) } func scan(filePath: String) -> [Token] { /* Start tokenizing given file */ let path = NSURL(fileURLWithPath: filePath) var tokens = [Token]() // TODO Convert this eventually to a generator do { self.inputText = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding) } catch { print("Error reading file!") } while true { self.nextCharacter() if self.currentCharacter == nil { // Check for EOF break } else if RegexEr.isWhiteSpace(self.currentCharacter!) { // Check for whitespace continue } else if RegexEr.isString(self.currentCharacter!) { // Check for String tokens.append(self.readString()) } else if RegexEr.isRelop(self.currentCharacter) { // Check for Repl tokens.append(self.readRepl()) } else if RegexEr.isNumber(self.currentCharacter) { // Check for Number tokens.append(self.readNumber()) } } return tokens } } <file_sep>/zeampl/ast/expr/identifier.py from .expr import Expression, Range from ..decl.declaration import Declaration import weakref from typing import Optional class IdentifierExpression(Expression): def __init__(self, r: Range, name: str): super().__init__(r) self._name = name # After name resolution this will contain weak reference to a declaration self._declaration = None @property def name(self) -> str: return self._name @property def declaration(self) -> Optional[Declaration]: if self._declaration is None: return None else: return self._declaration() @declaration.setter def declaration(self, declaration: Optional[Declaration]): if decl is None: self._declaration = None else: self._declaration = weakref.ref(declaration) <file_sep>/zeampl/parser/tests/test.py import unittest import ast import parser class TestParser(unittest.TestCase): def test_string_escaping(self): self.assertEqual(parser.unescape_string("\"\\t\\n\\v\\f\\b\""), '\t\n\v\f\b') self.assertEqual(parser.unescape_string("\"abc\\xDE\\xa0\\u1235\\U0001034288\""), 'abc\xDE\xA0\u1235\U00010342' + '88') self.assertEqual(parser.unescape_string("\"abc\\"), 'abc\\') self.assertEqual(parser.unescape_string("\"abc\\z"), 'abc\\z') self.assertEqual(parser.unescape_string("\"abc\\x"), 'abc\\x') self.assertEqual(parser.unescape_string("\"abc\\x1"), 'abc\x01') self.assertEqual(parser.unescape_string("\"abc\\x1|"), 'abc\x01|') self.assertEqual(parser.unescape_string("\"abc\\u"), 'abc\\u') self.assertEqual(parser.unescape_string("\"abc\\u1"), 'abc\x01') self.assertEqual(parser.unescape_string("\"abc\\u1|"), 'abc\x01|') self.assertEqual(parser.unescape_string("\"abc\\U"), 'abc\\U') self.assertEqual(parser.unescape_string("\"abc\\U1"), 'abc\x01') self.assertEqual(parser.unescape_string("\"abc\\U1|"), 'abc\x01|') def test_int_literal(self): x = parser.parse_literal('123') self.assertIsInstance(x, ast.IntLiteral) self.assertEqual(x.range, ast.Range('<empty>', 1, 1, 1, 4)) self.assertEqual(x.value, 123) def test_bool_literal(self): x = parser.parse_literal('true') self.assertIsInstance(x, ast.BoolLiteral) self.assertEqual(x.range, ast.Range('<empty>', 1, 1, 1, 5)) self.assertEqual(x.value, True) x = parser.parse_literal('false') self.assertIsInstance(x, ast.BoolLiteral) self.assertEqual(x.range, ast.Range('<empty>', 1, 1, 1, 6)) self.assertEqual(x.value, False) def test_string_literal(self): x = parser.parse_literal('\"some\\ntext\"') self.assertIsInstance(x, ast.StringLiteral) self.assertEqual(x.range, ast.Range('<empty>', 1, 1, 1, 13)) self.assertEqual(x.value, 'some\ntext') def test_tuple_literal(self): x = parser.parse_literal('(1, (true, \"abc\"), ())') self.assertIsInstance(x, ast.TupleLiteral) self.assertEqual(x.range, ast.Range('<empty>', 1, 1, 1, 23)) self.assertEqual(len(x.expressions), 3) self.assertIsInstance(x.expressions[0], ast.IntLiteral) self.assertEqual(x.expressions[0].value, 1) self.assertIsInstance(x.expressions[1], ast.TupleLiteral) self.assertEqual(x.expressions[1].range, ast.Range('<empty>', 1, 5, 1, 18)) self.assertEqual(len(x.expressions[1].expressions), 2) self.assertIsInstance(x.expressions[1].expressions[0], ast.BoolLiteral) self.assertEqual(x.expressions[1].expressions[0].value, True) self.assertIsInstance(x.expressions[1].expressions[1], ast.StringLiteral) self.assertEqual(x.expressions[1].expressions[1].value, 'abc') self.assertIsInstance(x.expressions[2], ast.TupleLiteral) self.assertEqual(x.expressions[2].range, ast.Range('<empty>', 1, 20, 1, 22)) self.assertEqual(len(x.expressions[2].expressions), 0) def test_list_literal(self): x = parser.parse_literal('[1, (true, \"abc\"), ()]') self.assertIsInstance(x, ast.ListLiteral) self.assertEqual(x.range, ast.Range('<empty>', 1, 1, 1, 23)) self.assertEqual(len(x.expressions), 3) self.assertIsInstance(x.expressions[0], ast.IntLiteral) self.assertEqual(x.expressions[0].value, 1) self.assertIsInstance(x.expressions[1], ast.TupleLiteral) self.assertEqual(x.expressions[1].range, ast.Range('<empty>', 1, 5, 1, 18)) self.assertEqual(len(x.expressions[1].expressions), 2) self.assertIsInstance(x.expressions[1].expressions[0], ast.BoolLiteral) self.assertEqual(x.expressions[1].expressions[0].value, True) self.assertIsInstance(x.expressions[1].expressions[1], ast.StringLiteral) self.assertEqual(x.expressions[1].expressions[1].value, 'abc') self.assertIsInstance(x.expressions[2], ast.TupleLiteral) self.assertEqual(x.expressions[2].range, ast.Range('<empty>', 1, 20, 1, 22)) self.assertEqual(len(x.expressions[2].expressions), 0) def test_identifier(self): x = parser.parse_expression('x1') self.assertIsInstance(x, ast.IdentifierExpression) self.assertEqual(x.name, 'x1') x = parser.parse_expression('_') self.assertIsInstance(x, ast.IdentifierExpression) self.assertEqual(x.name, '_') x = parser.parse_expression('Xyz') self.assertIsInstance(x, ast.IdentifierExpression) self.assertEqual(x.name, 'Xyz') def test_expr_priority(self): x = parser.parse_expression('-1 + 2 * + 3') self.assertIsInstance(x, ast.BinaryOperatorExpression) self.assertEqual(x.range, ast.Range('<empty>', 1, 1, 1, 13)) x_lhs = x.lhs self.assertIsInstance(x_lhs, ast.PrefixOperatorExpression) self.assertEqual(x_lhs.range, ast.Range('<empty>', 1, 1, 1, 3)) self.assertEqual(x_lhs.op, '-') self.assertIsInstance(x_lhs.expr, ast.IntLiteral) self.assertEqual(x_lhs.expr.value, 1) x_rhs = x.rhs self.assertIsInstance(x_rhs, ast.BinaryOperatorExpression) self.assertEqual(x_rhs.range, ast.Range('<empty>', 1, 6, 1, 13)) x_rhs_lhs = x_rhs.lhs self.assertIsInstance(x_rhs_lhs, ast.IntLiteral) self.assertEqual(x_rhs_lhs.range, ast.Range('<empty>', 1, 6, 1, 7)) self.assertEqual(x_rhs_lhs.value, 2) x_rhs_rhs = x_rhs.rhs self.assertIsInstance(x_rhs_rhs, ast.PrefixOperatorExpression) self.assertEqual(x_rhs_rhs.range, ast.Range('<empty>', 1, 10, 1, 13)) self.assertEqual(x_rhs_rhs.op, '+') x_rhs_rhs_expr = x_rhs_rhs.expr self.assertIsInstance(x_rhs_rhs_expr, ast.IntLiteral) self.assertEqual(x_rhs_rhs_expr.range, ast.Range('<empty>', 1, 12, 1, 13)) self.assertEqual(x_rhs_rhs_expr.value, 3) def test_function_expression(self): tests = [ # Func calls 'skittles', 'skittles(rainbox)', 'skittles(taste, rainbow)', # Method calls 'rainbow.skittles', 'rainbow.skittles(taste)', 'rainbow.skittles(taste, skookum)', ] for case in tests: result = parser.parse_expression(case) self.assertIsInstance(result, ast.FuncExpression) <file_sep>/zeampl/parser/generated/__init__.py from .ZeamplParser import ZeamplParser from .ZeamplLexer import ZeamplLexer from .ZeamplVisitor import ZeamplVisitor __all__ = ['ZeamplParser', 'ZeamplLexer', 'ZeamplVisitor'] <file_sep>/zeampl/ast/expr/operator.py from .expr import Expression, Range class PrefixOperatorExpression(Expression): def __init__(self, r: Range, op: str, expr: Expression): super().__init__(r) self._op = op self._expr = expr @property def op(self) -> str: return self._op @property def expr(self): return self._expr class BinaryOperatorExpression(Expression): def __init__(self, r: Range, lhs: Expression, op: str, rhs: Expression): super().__init__(r) self._lhs = lhs self._op = op self._rhs = rhs @property def lhs(self) -> Expression: return self._lhs @property def op(self) -> str: return self._op @property def rhs(self) -> Expression: return self._rhs <file_sep>/zeampl/ast/expr/literal.py from .expr import Expression, Range from typing import List class Literal(Expression): pass class IntLiteral(Literal): def __init__(self, r: Range, value: int): super().__init__(r) self._value = value @property def value(self) -> int: return self._value class BoolLiteral(Literal): def __init__(self, r: Range, value: bool): super().__init__(r) self._value = value @property def value(self) -> bool: return self._value class StringLiteral(Literal): def __init__(self, r: Range, value: str): super().__init__(r) self._value = value @property def value(self) -> str: return self._value class TupleLiteral(Literal): def __init__(self, r: Range, expressions: List[Expression]): super().__init__(r) self._expressions = expressions @property def expressions(self): return self._expressions class ListLiteral(Literal): def __init__(self, r: Range, expressions: List[Expression]): super().__init__(r) self._expressions = expressions @property def expressions(self): return self._expressions <file_sep>/zeampl/parser/generated/ZeamplVisitor.py # Generated from /Users/npohilets/compiler-peer-group/zeampl/parser/Zeampl.g4 by ANTLR 4.5.3 from antlr4 import * if __name__ is not None and "." in __name__: from .ZeamplParser import ZeamplParser else: from ZeamplParser import ZeamplParser # This class defines a complete generic visitor for a parse tree produced by ZeamplParser. class ZeamplVisitor(ParseTreeVisitor): # Visit a parse tree produced by ZeamplParser#module. def visitModule(self, ctx:ZeamplParser.ModuleContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#decl. def visitDecl(self, ctx:ZeamplParser.DeclContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#varDecl. def visitVarDecl(self, ctx:ZeamplParser.VarDeclContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#funcDecl. def visitFuncDecl(self, ctx:ZeamplParser.FuncDeclContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#argList. def visitArgList(self, ctx:ZeamplParser.ArgListContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#arg. def visitArg(self, ctx:ZeamplParser.ArgContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#typeDecl. def visitTypeDecl(self, ctx:ZeamplParser.TypeDeclContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#classDecl. def visitClassDecl(self, ctx:ZeamplParser.ClassDeclContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#typeExpr. def visitTypeExpr(self, ctx:ZeamplParser.TypeExprContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#idType. def visitIdType(self, ctx:ZeamplParser.IdTypeContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#listType. def visitListType(self, ctx:ZeamplParser.ListTypeContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#tupleType. def visitTupleType(self, ctx:ZeamplParser.TupleTypeContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#statement. def visitStatement(self, ctx:ZeamplParser.StatementContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#block. def visitBlock(self, ctx:ZeamplParser.BlockContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#exprStmt. def visitExprStmt(self, ctx:ZeamplParser.ExprStmtContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#assign_op. def visitAssign_op(self, ctx:ZeamplParser.Assign_opContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#ifStmt. def visitIfStmt(self, ctx:ZeamplParser.IfStmtContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#whileStmt. def visitWhileStmt(self, ctx:ZeamplParser.WhileStmtContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#forStmt. def visitForStmt(self, ctx:ZeamplParser.ForStmtContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#returnStmt. def visitReturnStmt(self, ctx:ZeamplParser.ReturnStmtContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#breakStmt. def visitBreakStmt(self, ctx:ZeamplParser.BreakStmtContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#continueStmt. def visitContinueStmt(self, ctx:ZeamplParser.ContinueStmtContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#Atom. def visitAtom(self, ctx:ZeamplParser.AtomContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#PrefixOp. def visitPrefixOp(self, ctx:ZeamplParser.PrefixOpContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#BinaryOp. def visitBinaryOp(self, ctx:ZeamplParser.BinaryOpContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#expr5op. def visitExpr5op(self, ctx:ZeamplParser.Expr5opContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#expr4op. def visitExpr4op(self, ctx:ZeamplParser.Expr4opContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#expr3op. def visitExpr3op(self, ctx:ZeamplParser.Expr3opContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#expr2op. def visitExpr2op(self, ctx:ZeamplParser.Expr2opContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#Call. def visitCall(self, ctx:ZeamplParser.CallContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#MemberAccess. def visitMemberAccess(self, ctx:ZeamplParser.MemberAccessContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#Atom0. def visitAtom0(self, ctx:ZeamplParser.Atom0Context): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#expr0. def visitExpr0(self, ctx:ZeamplParser.Expr0Context): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#identifierExpression. def visitIdentifierExpression(self, ctx:ZeamplParser.IdentifierExpressionContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#literal. def visitLiteral(self, ctx:ZeamplParser.LiteralContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#intLiteral. def visitIntLiteral(self, ctx:ZeamplParser.IntLiteralContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#boolLiteral. def visitBoolLiteral(self, ctx:ZeamplParser.BoolLiteralContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#stringLiteral. def visitStringLiteral(self, ctx:ZeamplParser.StringLiteralContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#tupleLiteral. def visitTupleLiteral(self, ctx:ZeamplParser.TupleLiteralContext): return self.visitChildren(ctx) # Visit a parse tree produced by ZeamplParser#listLiteral. def visitListLiteral(self, ctx:ZeamplParser.ListLiteralContext): return self.visitChildren(ctx) del ZeamplParser<file_sep>/zeampl/parser/string_utils.py _escape_chars = { 'a': '\a', 'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t', 'v': '\v', } def unescape_string(s): if len(s) > 0 and s[0] == '\"': s = s[1:] if len(s) > 0 and s[-1] == '\"': s = s[:-1] state = 0 r = '' # result accumulator x = 0 # hex digits accumulator x_fallback = '' for c in s: if state == 0: # default if c == '\\': state = -1 else: r += c elif state == -1: # after slash if c in '\\\'\"': r += c state = 0 elif c == 'x': state = 2 x_fallback = '\\x' elif c == 'u': state = 4 x_fallback = '\\u' elif c == 'U': state = 8 x_fallback = '\\U' else: r += _escape_chars.get(c, '\\' + c) state = 0 else: append_c = False try: x = x * 16 + int(c, 16) state -= 1 x_fallback = '' except ValueError: append_c = True state = 0 if state == 0: if len(x_fallback) > 0: r += x_fallback else: r += chr(x) x = 0 if append_c: r += c if state == 0: pass elif state == -1: r += '\\' else: if len(x_fallback) > 0: r += x_fallback else: r += chr(x) return r <file_sep>/pfisher/lexer/tokens.swift /* Our language Tokens */ import Foundation enum Tag: String { case Identifier = "[a-zP]+" case ReservedWord // Keywords == Reserved words case Number = "[0-9]+" case Relop = "(<|<=|=|==)+" case bullshit = "\\s+" } class Token: Grammar { var tag: Tag! init(tag: Tag, value: String){ self.tag = tag super.init() self.value = value } }<file_sep>/pfisher/lexer/main.swift import Foundation func main() { let myLexer = Lexer() let tokens = myLexer.scan("/Users/pfisher/Dropbox/cloud_repos/compilers_peer_group/lexer/inputFile") for token in tokens { print("Token Type: \(token.tag); Value: \(token.value!)") } let parser = LLParserOne() for (nt, firstSet) in parser.firstSet { let symbol = nt for terminal in firstSet { print("Production: \(symbol.name); First Terminal: \(terminal.value)") } } for (nt, followSet) in parser.followSet { let production = nt as! NonTerminal for member in followSet { print("Production: \(production.name); Follow Terminal: \(member.value)") } } parser.printParsingTable() } main() <file_sep>/zeampl/ast/expr/function.py """ Provides for AST construction for funcs and methods calls """ from .expr import Expression, Range class FuncExpression(Expression): """ Expression Token Type: expr1 """ def __init__(self, r: Range, ID, name): super().__init__(r) self._funcName = name self._ID = ID @property def name(self): return self._funcName @property def ID(self): return self._ID <file_sep>/zeampl/ast/expr/__init__.py from .expr import Expression from .literal import Literal, IntLiteral, BoolLiteral, StringLiteral, TupleLiteral, ListLiteral from .identifier import IdentifierExpression from .operator import PrefixOperatorExpression, BinaryOperatorExpression from .function import FuncExpression __all__ = [ 'Expression', 'Literal', 'IntLiteral', 'BoolLiteral', 'StringLiteral', 'TupleLiteral', 'ListLiteral', 'IdentifierExpression', 'PrefixOperatorExpression', 'BinaryOperatorExpression', 'FuncExpression', ] <file_sep>/zeampl/ast/expr/expr.py from ..range import Range class Expression(object): def __init__(self, r: Range): self._range = r @property def range(self) -> Range: return self._range <file_sep>/zeampl/parser/ZeamplASTBuilder.py from .generated import ZeamplParser from .generated import ZeamplVisitor import antlr4 import ast from parser.string_utils import unescape_string from typing import List class ZeamplASTBuilder(ZeamplVisitor): def __init__(self, token_stream: antlr4.BufferedTokenStream): self._token_stream = token_stream def get_range(self, ctx: antlr4.ParserRuleContext) -> ast.Range: start_tok = ctx.start # type: antlr4.Token end_tok = self._token_stream.get(ctx.stop.tokenIndex + 1) # type: antlr4.Token file_name = start_tok.getInputStream().name return ast.Range(file_name, start_tok.line, start_tok.column + 1, end_tok.line, end_tok.column + 1) def get_expressions(self, contexts: List[antlr4.ParserRuleContext]): return [ctx.accept(self) for ctx in contexts] def visitIntLiteral(self, ctx: ZeamplParser.IntLiteralContext): value = int(ctx.getText()) return ast.IntLiteral(self.get_range(ctx), value) def visitBoolLiteral(self, ctx: ZeamplParser.BoolLiteralContext): value = {'true': True, 'false': False}[ctx.getText()] return ast.BoolLiteral(self.get_range(ctx), value) def visitStringLiteral(self, ctx: ZeamplParser.StringLiteralContext): value = unescape_string(ctx.getText()) return ast.StringLiteral(self.get_range(ctx), value) def visitTupleLiteral(self, ctx: ZeamplParser.TupleLiteralContext): return ast.TupleLiteral(self.get_range(ctx), self.get_expressions(ctx.x)) def visitListLiteral(self, ctx: ZeamplParser.ListLiteralContext): return ast.ListLiteral(self.get_range(ctx), self.get_expressions(ctx.x)) def visitIdentifierExpression(self, ctx: ZeamplParser.IdentifierExpressionContext): token = ctx.ID().symbol # type: antlr4.Token return ast.IdentifierExpression(self.get_range(ctx), token.text) def visitPrefixOp(self, ctx: ZeamplParser.PrefixOpContext): op = ctx.op.getChild(0).symbol # type: antlr4.Token return ast.PrefixOperatorExpression(self.get_range(ctx), op.text, ctx.x.accept(self)) def visitBinaryOp(self, ctx: ZeamplParser.BinaryOpContext): op = ctx.op.getChild(0).symbol # type: antlr4.Token lhs = ctx.lhs.accept(self) rhs = ctx.rhs.accept(self) return ast.BinaryOperatorExpression(self.get_range(ctx), lhs, op.text, rhs) def visitExpr1(self, ctx: ZeamplParser.Expr1Context): ID = ctx.ID() name = ctx.expr0().getText() return ast.FuncExpression(r=self.get_range(ctx), ID=ID, name=name)
6dd55809764d9c4bea2566abd079a05b69dd5e4b
[ "Markdown", "Python", "Swift" ]
24
Python
peterfisher/compiler-peer-group
fd2f21225f531dc3e884d57169969603664e7065
eee312a6ff2546c83a530faf3841183834cb88fa
refs/heads/master
<file_sep>// https://groups.google.com/forum/#!topic/golang-nuts/cok6xasvI3w // retrieve 'src' values from 'image' tags package main import ( "fmt" "github.com/clbanning/x2j" ) var doc = ` <doc> <image src="something.png"></image> <something> <image src="something else.jpg"></image> <title>something else</title> </something> <more_stuff> <some_images> <image src="first.gif"></image> <image src="second.gif"></image> </some_images> </more_stuff> </doc>` func main() { // get all image tag values - []interface{} images,err := x2j.ValuesForTag(doc,"image") if err != nil { fmt.Println("error parsing doc:",err.Error()) return } sources := make([]string,0) for _, v := range images { // ValuesForKey requires a map[string]interface{} value // as a starting point ... thinks its a doc m := make(map[string]interface{},1) m["dummy"] = v ss := x2j.ValuesForKey(m,"-src") for _,s := range ss { sources = append(sources,s.(string)) } } for _,src := range sources { fmt.Println(src) } } <file_sep>// https://groups.google.com/forum/#!topic/golang-nuts/-N9Toa6qlu8 // shows that you can extract attribute values directly from tag/key path. // NOTE: attribute values are encoded by prepending a hyphen, '-'. package main import ( "fmt" "github.com/clbanning/x2j" ) var doc = ` <doc> <some_tag> <geoInfo> <city name="SEATTLE"/> <state name="WA"/> <country name="USA"/> </geoInfo> <geoInfo> <city name="VANCOUVER"/> <state name="BC"/> <country name="CA"/> </geoInfo> <geoInfo> <city name="LONDON"/> <country name="UK"/> </geoInfo> </some_tag> </doc>` func main() { values, err := x2j.ValuesFromTagPath(doc, "doc.some_tag.geoInfo.country.-name") if err != nil { fmt.Println("err:", err.Error()) } for _, v := range values { fmt.Println("v:",v) } } <file_sep>package main import ( "fmt" "github.com/clbanning/x2j" ) var doc = ` <books> <book seq="1"> <author><NAME></author> <title>The Recognitions</title> <review>One of the great seminal American novels of the 20th century.</review> </book> <book seq="2"> <author><NAME></author> <title>Islandia</title> <review>An example of earlier 20th century American utopian fiction.</review> </book> <book seq="3"> <author><NAME></author> <title>The Beetle Leg</title> <review>A lyrical novel about the construction of Ft. Peck Dam in Montana.</review> </book> <book seq="4"> <author><NAME></author> <title>King's Day</title> <review>A magical novella.</review> </book> </books> ` func main() { fmt.Println(doc) v,_ := x2j.ValuesFromTagPath(doc,"books") fmt.Println("path: books; len(v):",len(v)) fmt.Printf("%+v\n\n",v) v,_ = x2j.ValuesFromTagPath(doc,"books.book") fmt.Println("path: books.book; len(v):",len(v)) fmt.Printf("%+v\n\n",v) v,_ = x2j.ValuesFromTagPath(doc,"books.*") fmt.Println("path: books.*; len(v):",len(v)) fmt.Printf("%+v\n\n",v) v,_ = x2j.ValuesFromTagPath(doc,"books.*.title") fmt.Println("path: books.*.title len(v):",len(v)) fmt.Printf("%+v\n\n",v) v,_ = x2j.ValuesFromTagPath(doc,"books.*.*") fmt.Println("path: books.*.*; len(v):",len(v)) fmt.Printf("%+v\n\n",v) } <file_sep>// https://groups.google.com/forum/#!searchin/golang-nuts/idnet$20netid/golang-nuts/guM3ZHHqSF0/K1pBpMqQSSwJ // http://play.golang.org/p/BFFDxphKYK package main import ( "fmt" "github.com/clbanning/x2j" ) // demo how to compensate for irregular tag labels in data // "netid" vs. "idnet" var doc1 = ` <?xml version="1.0" encoding="UTF-8"?> <data> <netid> <disable>no</disable> <text1>default:text</text1> <word1>default:word</word1> </netid> </data> ` var doc2 = ` <?xml version="1.0" encoding="UTF-8"?> <data> <idnet> <disable>yes</disable> <text1>default:text</text1> <word1>default:word</word1> </idnet> </data> ` func main() { var docs = []string{doc1,doc2} for n,doc := range docs { fmt.Println("\nTestValuesFromTagPath2(), iteration:",n,"\n",doc) m,_ := x2j.DocToMap(doc) fmt.Println("map:",x2j.WriteMap(m)) v,_ := x2j.ValuesFromTagPath(doc,"data.*") fmt.Println("\npath == data.*: len(v):",len(v)) for key,val := range v { fmt.Println(key,":",val) } mm := v[0] for key,val := range mm.(map[string]interface{}) { fmt.Println(key,":",val) } v,_ = x2j.ValuesFromTagPath(doc,"data.*.*") fmt.Println("\npath == data.*.*: len(v):",len(v)) for key,val := range v { fmt.Println(key,":",val) } } }
c526c251e03801a4fa0d56f93d819f919e96d289
[ "Go" ]
4
Go
clbanning/x2j
825249438eec392bc87b980fb635b336e496a888
add21c56c9ae4a093c95fc70a43df3f7522c8aab
refs/heads/master
<file_sep>## Put comments here that give an overall description of what your ## functions do ## Write a short comment describing this function # create a matrix makeCacheMatrix <- function(x = matrix()) { #init im to NULL (empty it) im <- NULL #set <- function(y) { #x <<- y #im <<- NULL #} #This function returns entered matrix get <- function() x #This function sets inverse matrix setim <- function(InverseM) im <<- InverseM #This function gets inverse matrix getim <- function() im #Put functions into a list list(get = get, setim = setim, getim = getim) } ## Write a short comment describing this function # calc inverse matrix of x. Get it from cache if it exists cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' #get inverse matrix from cache im <- x$getim() #return inverse matrix from cache if it exists if(!is.null(im)) { message("getting cached data") return(im) } #following code will only be executed if inverse matrix is not in cache #get matrix x data <- x$get() #calc inverse matrix im <- solve(data) #set inverse matrix x$setim(im) #print inverse matrix im }
7dc385281229d56d25c2b5e87949be97f645c36e
[ "R" ]
1
R
ynwa59/ProgrammingAssignment2
848d139c81b7b38bd62df53bf805b424e8e69f30
c6d75c2bd6a907b4cbf08e412d0c47182a2e0f25
refs/heads/master
<repo_name>TomasMadeja/pv204_Team_Project_Supercalifragilisticexpialidocious<file_sep>/src/main/cz/muni/fi/pv204/host/SchnorrZKP.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cz.muni.fi.pv204.host; import org.bouncycastle.jce.spec.ECParameterSpec; import org.bouncycastle.math.ec.ECPoint; import org.bouncycastle.math.ec.custom.sec.SecP256R1Curve; import java.math.BigInteger; import java.security.SecureRandom; //import cz.muni.fi.pv204.host.Util; /** * * @author minh */ public class SchnorrZKP { private ECPoint V = null; private BigInteger r = null; public SchnorrZKP () { // constructor } public SchnorrZKP (ECPoint V, BigInteger r) { this.V = V; this.r = r; } // knowledgeProofForX3.generateZKP(G, n, x1, Gx1, participantId); public void generateZKP (ECPoint generator, BigInteger n, BigInteger x, ECPoint X, byte[] userID) { /* Generate a random v from [1, n-1], and compute V = G*v */ BigInteger v = org.bouncycastle.util.BigIntegers.createRandomInRange(BigInteger.ONE, n.subtract(BigInteger.ONE), new SecureRandom()); V = generator.multiply(v); BigInteger h = Util.getSHA256(generator, V, X, userID); // h r = v.subtract(x.multiply(h)); // r = v-x*h mod n } public ECPoint getV() { return V; } public BigInteger getr() { return r; } /** * Validates the zero knowledge proof * * @throws CryptoException if the zero knowledge proof is not correct */ //public boolean verifyZKP(ECParameterSpec ecSpec, ECPoint generator, ECPoint X, ECPoint V, BigInteger r, BigInteger q, String userID) { public boolean verifyZKP(ECParameterSpec ecSpec, ECPoint generator, ECPoint X, BigInteger q, byte[] userID) { /* ZKP: {V=G*v, r} */ BigInteger h = Util.getSHA256(generator, V, X, userID); SecP256R1Curve ecCurve = (SecP256R1Curve) ecSpec.getCurve(); BigInteger coFactor = ecSpec.getH(); // Public key validation based on p. 25 // http://cs.ucsb.edu/~koc/ccs130h/notes/ecdsa-cert.pdf // 1. X != infinity if (X.isInfinity()){ return false; } // 2. Check x and y coordinates are in Fq, i.e., x, y in [0, q-1] if (X.getXCoord().toBigInteger().compareTo(BigInteger.ZERO) == -1 || X.getXCoord().toBigInteger().compareTo(q.subtract(BigInteger.ONE)) == 1 || X.getYCoord().toBigInteger().compareTo(BigInteger.ZERO) == -1 || X.getYCoord().toBigInteger().compareTo(q.subtract(BigInteger.ONE)) == 1) { return false; } // 3. Check X lies on the curve try { ecCurve.decodePoint(X.getEncoded(false)); } catch(Exception e){ e.printStackTrace(); return false; } // 4. Check that nX = infinity. // It is equivalent - but more more efficient - to check the coFactor*X is not infinity if (X.multiply(coFactor).isInfinity()) { return false; } // Now check if V = G*r + X*h. // Given that {G, X} are valid points on curve, the equality implies that V is also a point on curve. if (V.equals(generator.multiply(r).add(X.multiply(h)))) { return true; } else { return false; } } } <file_sep>/src/main/cz/muni/fi/pv204/javacard/SecureChannel.java package cz.muni.fi.pv204.javacard; import cz.muni.fi.pv204.javacard.crypto.MagicAes; import cz.muni.fi.pv204.javacard.crypto.PKCS5Padding; import cz.muni.fi.pv204.javacard.jpake.JPake; import cz.muni.fi.pv204.javacard.jpake.JPakeECParam; import cz.muni.fi.pv204.javacard.jpake.JPakePassword; import javacard.framework.*; import javacard.security.RandomData; import java.math.BigInteger; import java.security.InvalidParameterException; public class SecureChannel { public static final short PIN_SIZE = 4; public static final short PIN_TRIES = 3; public static final short ROUNDS_PER_KEY = 50; public static final short SIZE_CHALLENGE = 32; // sha 256 - 128 for AES IV public static final short SIZE_ID = 10; public static final short SIZE_EC_POINT = 65; public static final byte ROUND_1_ID = 0x11; public static final byte ROUND_1_GX = 0x12; public static final byte ROUND_1_ZKP1 = 0x13; public static final byte ROUND_1_ZKP2 = 0x14; public static final byte ROUND_2_GX = 0x21; public static final byte ROUND_2_B = 0x22; public static final byte ROUND_2_ZKP1 = 0x23; public static final byte ROUND_2_ZKP2 = 0x24; public static final byte ROUND_2_ZKP3 = 0x25; public static final byte ROUND_3_A = 0x31; public static final byte ROUND_3_ZKP1 = 0x32; public static final byte ROUND_HELLO = 0x41; public static final byte ESTABLISHED = 0x42; // COmmand reset private static SecureChannel sc; private JPakePassword pin; private JPake jpake; private MagicAes aes; private RandomData rand; private PKCS5Padding padding; private byte[] myID; private byte[] state; private byte[] Gx1; private byte[] Gx2; private byte[] Gx3; private byte[] Gx4; private byte[] A; private byte[] B; private byte[] zkp1_v; private BigInteger zkp1_r; private byte[] zkp2_v; private BigInteger zkp2_r; private byte[] zkp3_v; private BigInteger zkp3_r; private byte[] participantIDA; private byte[] challenge; private short counter; public static class UnexpectedError extends Exception { public UnexpectedError() { super(); } } private SecureChannel() { rand = RandomData.getInstance(RandomData.ALG_KEYGENERATION); state = JCSystem.makeTransientByteArray((short) 1, JCSystem.CLEAR_ON_DESELECT); state[0] = 0x00; pin = new JPakePassword((byte) PIN_TRIES , (byte) PIN_SIZE); JPakeECParam param = new JPakeECParam(); myID = new byte[SIZE_ID]; rand.nextBytes(myID, (short) 0, SIZE_ID); jpake = new JPake(myID, pin, param); aes = new MagicAes(); padding = new PKCS5Padding((short) 16); Gx1 = new byte[SIZE_EC_POINT]; Gx2 = new byte[SIZE_EC_POINT]; Gx3 = new byte[SIZE_EC_POINT]; Gx4 = new byte[SIZE_EC_POINT]; A = new byte[SIZE_EC_POINT]; B = new byte[SIZE_EC_POINT]; zkp1_v = new byte[SIZE_EC_POINT]; zkp2_v = new byte[SIZE_EC_POINT]; zkp3_v = new byte[SIZE_EC_POINT]; participantIDA = new byte[SIZE_ID]; challenge = new byte[SIZE_CHALLENGE]; counter = 0; } public static SecureChannel getSecureChannel() { if (sc == null) { sc = new SecureChannel(); } return sc; } public void setPin(byte[] newPin, short offset, byte length) throws UnexpectedError { if (length != PIN_SIZE) { throw new UnexpectedError(); } if (pin == null) { pin = new JPakePassword((byte) PIN_TRIES , (byte) PIN_SIZE); } pin.update(newPin, offset, length); } public boolean isEstablished() { return state[0] == ESTABLISHED; } public short processIncoming( APDU apdu ) throws UnexpectedError { byte[] inBuffer = apdu.getBuffer(); short inOffset = ISO7816.OFFSET_CDATA; short inLen = apdu.getIncomingLength(); byte[] outBuffer = inBuffer; short outOffset = inOffset; short outLen = 256; short size; byte command = inBuffer[ISO7816.OFFSET_INS]; switch (command) { case ROUND_1_ID: checkPinSTate(); checkLength(inLen, SIZE_ID, SIZE_ID); pin.decrement(); state[0] = ROUND_1_GX; parseIDA(inBuffer, inOffset, inLen); ISOException.throwIt(ISO7816.SW_NO_ERROR); break; case ROUND_1_GX: checkLength(inLen, (short) (2*SIZE_EC_POINT), (short) (2*SIZE_EC_POINT)); checkState(command); parseECPoint(inBuffer, inOffset, inLen, Gx1); parseECPoint(inBuffer, (short)(inOffset+SIZE_EC_POINT), (short)(inLen-SIZE_EC_POINT), Gx2); state[0] = ROUND_1_ZKP1; ISOException.throwIt(ISO7816.SW_NO_ERROR); break; case ROUND_1_ZKP1: checkLength(inLen, (short) (1+SIZE_EC_POINT), (short)255); checkState(command); parseZKP(inBuffer, inOffset, inLen, (short) 1); state[0] = ROUND_1_ZKP2; ISOException.throwIt(ISO7816.SW_NO_ERROR); break; case ROUND_1_ZKP2: checkLength(inLen, (short) (1+SIZE_EC_POINT), (short)255); checkState(command); parseZKP(inBuffer, inOffset, inLen, (short) 2); validateRound1(); generateRound2(); size = encodeIDB(outBuffer, outOffset, outLen); state[0] = ROUND_2_GX; // Response should contain participant ID sendSuccess(apdu, outOffset, size); break; case ROUND_2_GX: checkState(command); size = encodeECPoint(outBuffer, outOffset, outLen, Gx3); size += encodeECPoint(outBuffer, (short)(outOffset+SIZE_EC_POINT), outLen, Gx4); state[0] = ROUND_2_B; sendSuccess(apdu, outOffset, size); break; case ROUND_2_B: checkState(command); size = encodeECPoint(outBuffer, outOffset, outLen, B); state[0] = ROUND_2_ZKP1; sendSuccess(apdu, outOffset, size); break; case ROUND_2_ZKP1: checkState(command); size = encodeZKP(outBuffer, outOffset, outLen, zkp1_v, zkp1_r); state[0] = ROUND_2_ZKP2; sendSuccess(apdu, outOffset, size); break; case ROUND_2_ZKP2: checkState(command); size = encodeZKP(outBuffer, outOffset, outLen, zkp2_v, zkp2_r); state[0] = ROUND_2_ZKP3; sendSuccess(apdu, outOffset, size); break; case ROUND_2_ZKP3: checkState(command); size = encodeZKP(outBuffer, outOffset, outLen, zkp3_v, zkp3_r); state[0] = ROUND_3_A; sendSuccess(apdu, outOffset, size); break; case ROUND_3_A: checkLength(inLen, SIZE_EC_POINT, SIZE_EC_POINT); checkState(command); parseECPoint(inBuffer, inOffset, inLen, A); state[0] = ROUND_3_ZKP1; ISOException.throwIt(ISO7816.SW_NO_ERROR); break; case ROUND_3_ZKP1: checkLength(inLen, (short) (1+SIZE_EC_POINT), (short)255); checkState(command); parseZKP(inBuffer, inOffset, inLen, (short) 1); validateRound3(); prepareForHello(outBuffer, outOffset, outLen); state[0] = ROUND_HELLO; sendSuccess(apdu, outOffset, (short) (SIZE_CHALLENGE)); break; case ESTABLISHED: // RESET state[0] = 0x00; ISOException.throwIt(ISO7816.SW_NO_ERROR); break; case ROUND_HELLO: checkLength(inLen, (short) (SIZE_CHALLENGE*2), (short) (SIZE_CHALLENGE*2)); checkState(command); inLen = unCheckedUnwrap( inBuffer, inOffset, inLen, inBuffer, inOffset, inLen ); establishmentHello( inBuffer, inOffset, inLen, outBuffer, outOffset, outLen ); state[0] = ESTABLISHED; unCheckedWrap(outBuffer, outOffset, (short)(2* SIZE_CHALLENGE), outBuffer, outOffset, outLen); pin.correct(); counter = 0; sendSuccess(apdu, outOffset, (short) (2* SIZE_CHALLENGE)); break; default: checkState(ESTABLISHED); if (counter >= ROUNDS_PER_KEY ) ISOException.throwIt(ISO7816.SW_COMMAND_NOT_ALLOWED); counter++; if (inLen == 0) { aes.nextIV(); return 0; } outLen = unwrap( inBuffer, inOffset, inLen, outBuffer, outOffset, outLen ); short off = padding.unpad(outBuffer, outOffset, outLen); return (short)(off - outOffset); } return (short) 0; } public short wrap( byte[] inBuffer, short inOffset, short inLen, short totalLen ) { checkState(ESTABLISHED); short l; if (inLen < 1) { aes.nextIV(); return (short)0; } else { l = (short) (padding.padLength(inLen) + inLen); } if (l > 256 || l > totalLen) { return -1; } padding.pad( inBuffer, inOffset, inLen, totalLen ); return unCheckedWrap( inBuffer, inOffset, l, inBuffer, inOffset, totalLen ); } private short unwrap( byte[] inBuffer, short inOffset, short inLen, byte[] outBuffer, short outOffset, short outLen ) { checkState(ESTABLISHED); if (inLen % 16 != 0) ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); return unCheckedUnwrap( inBuffer, inOffset, inLen, outBuffer, outOffset, outLen ); } private short unCheckedWrap( byte[] inBuffer, short inOffset, short inLen, byte[] outBuffer, short outOffset, short outLen ) { return aes.encrypt( inBuffer, inOffset, inLen, outBuffer, outOffset, outLen ); } private short unCheckedUnwrap( byte[] inBuffer, short inOffset, short inLen, byte[] outBuffer, short outOffset, short outLen ) { return aes.decrypt( inBuffer, inOffset, inLen, outBuffer, outOffset, outLen ); } private void sendSuccess(APDU apdu, short offset, short len) { apdu.setOutgoingAndSend(offset, len); ISOException.throwIt(ISO7816.SW_NO_ERROR); } private void parseIDA( byte[] incoming, short incomingOffset, short incomingLength ) { Util.arrayCopy( incoming, incomingOffset, participantIDA, (short) 0, SIZE_ID ); } private short encodeIDB( byte[] outgoing, short outgoingOffset, short outgoingLength ) { Util.arrayCopy( myID, (short) 0, outgoing, outgoingOffset, SIZE_ID ); return SIZE_ID; } private void parseECPoint( byte[] incoming, short incomingOffset, short incomingLength, byte[] dst ) { Util.arrayCopy( incoming, incomingOffset, dst, (short) 0, SIZE_EC_POINT ); } private short encodeECPoint( byte[] outgoing, short outgoingOffset, short outgoingLength, byte[] src ) { Util.arrayCopy( src, (short) 0, outgoing, outgoingOffset, SIZE_EC_POINT ); return SIZE_EC_POINT; } private void parseZKP( byte[] incoming, short incomingOffset, short incomingLength, short t ) throws UnexpectedError { byte[] target; switch (t) { case 1: target = zkp1_v; break; case 2: target = zkp2_v; break; case 3: target = zkp3_v; break; default: throw new UnexpectedError(); } Util.arrayCopy( incoming, incomingOffset, target, (short) 0, SIZE_EC_POINT ); short l = (short) (incomingLength-SIZE_EC_POINT); byte[] tmp = new byte[l]; Util.arrayCopy( incoming, (short) (incomingOffset+SIZE_EC_POINT), tmp, (short) 0, (short) (l) ); BigInteger tmpBigInteger = new BigInteger(tmp); switch (t) { case 1: zkp1_r = tmpBigInteger; break; case 2: zkp2_r = tmpBigInteger; break; case 3: zkp3_r = tmpBigInteger; break; } } private short encodeZKP( byte[] outgoing, short outgoingOffset, short outgoingLength, byte[] zkp_V, BigInteger zkp_r ) { Util.arrayCopy( zkp_V, (short) 0, outgoing, outgoingOffset, SIZE_EC_POINT ); byte[] tmp = zkp_r.toByteArray(); short l = (short) tmp.length; if (l > outgoingLength - SIZE_EC_POINT) { ISOException.throwIt(ISO7816.SW_UNKNOWN); } Util.arrayCopy( tmp, (short) 0, outgoing, (short)(outgoingOffset+SIZE_EC_POINT), l ); return (short) (SIZE_EC_POINT+l); } private void validateRound1() { if (!jpake.validateRound1PayloadReceived( Gx1, Gx2, zkp1_v, zkp1_r, zkp2_v, zkp2_r, participantIDA )) { state[0] = 0x00; ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); } } private void generateRound2() { zkp1_r = new BigInteger("0"); zkp2_r = new BigInteger("0"); zkp3_r = new BigInteger("0"); BigInteger[] r = jpake.createRound2PayloadToSend( Gx3, Gx4, B, zkp1_v, zkp1_r, zkp2_v, zkp2_r, zkp3_v, zkp3_r, myID ); zkp1_r = r[0]; zkp2_r = r[1]; zkp3_r = r[2]; } private void validateRound3() { if (!jpake.validateRound3PayloadReceived( A, zkp1_v, zkp1_r, participantIDA )) { state[0] = 0x00; ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); } } private short prepareForHello( byte[] outgoing, short outgoingOffset, short outgoingLength ) throws UnexpectedError { if (outgoingLength < SIZE_CHALLENGE) { throw new UnexpectedError(); // TODO } rand.nextBytes(challenge, (short) 0, SIZE_CHALLENGE); byte[] keyingMaterial = jpake.calculateKeyingMaterial(); aes.generateKey( keyingMaterial, challenge ); // Outgoing Util.arrayCopy( challenge, (short) 0, outgoing, outgoingOffset, SIZE_CHALLENGE ); return SIZE_CHALLENGE; } private void establishmentHello( byte[] incoming, short incomingOffset, short incomingLength, byte[] outgoing, short outgoingOffset, short outgoingLength ) { for (short i = 0; i < SIZE_CHALLENGE; i++) { if ( incoming[incomingOffset+ SIZE_CHALLENGE +i] != (byte) ( challenge[i] ^ incoming[incomingOffset+i] ) ) { state[0] = 0x00; ISOException.throwIt(ISO7816.SW_DATA_INVALID); // TODO throw something } } rand.nextBytes(outgoing, SIZE_CHALLENGE, SIZE_CHALLENGE); for (short i = 0; i < SIZE_CHALLENGE; i++) { outgoing[outgoingOffset + i] = (byte) ( challenge[i] ^ outgoing[outgoingOffset + SIZE_CHALLENGE + i] ); } } private void checkPinSTate() { if (pin.getTriesRemaining() == 0x00) { state[0] = 0x00; ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); } } private void checkLength(short inLen, short lower, short upper) { if (lower > inLen || inLen > upper) { ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); } } private void checkState(byte expected) { checkPinSTate(); if (state[0] != expected) { state[0] = 0x00; ISOException.throwIt(ISO7816.SW_COMMAND_NOT_ALLOWED); } } } <file_sep>/src/main/cz/muni/fi/pv204/host/JPake.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cz.muni.fi.pv204.host; /** * This is a class similar to Participant * but it does not have a state * and it should create and verify payload of the rounds "blindly" * @author minh */ public class JPake { } <file_sep>/src/main/cz/muni/fi/pv204/host/cardTools/RunConfig.java package cz.muni.fi.pv204.host.cardTools; /** * Applet run configuration. * * @author <NAME>, <NAME> */ public class RunConfig { int targetReaderIndex = 0; public int numRepeats = 1; public Class appletToSimulate; boolean bReuploadApplet = false; byte[] installData = null; public enum CARD_TYPE { PHYSICAL, JCOPSIM, JCARDSIMLOCAL, JCARDSIMREMOTE } public CARD_TYPE testCardType = CARD_TYPE.PHYSICAL; public static RunConfig getDefaultConfig() { RunConfig runCfg = new RunConfig(); runCfg.targetReaderIndex = 0; runCfg.testCardType = CARD_TYPE.PHYSICAL; runCfg.appletToSimulate = null; runCfg.installData = new byte[15]; // bogus install data return runCfg; } public int getTargetReaderIndex() { return targetReaderIndex; } public int getNumRepeats() { return numRepeats; } public Class getAppletToSimulate() { return appletToSimulate; } public boolean isbReuploadApplet() { return bReuploadApplet; } public byte[] getInstallData() { return installData; } public CARD_TYPE getTestCardType() { return testCardType; } public RunConfig setTargetReaderIndex(int targetReaderIndex) { this.targetReaderIndex = targetReaderIndex; return this; } public RunConfig setNumRepeats(int numRepeats) { this.numRepeats = numRepeats; return this; } public RunConfig setAppletToSimulate(Class appletToSimulate) { this.appletToSimulate = appletToSimulate; return this; } public RunConfig setbReuploadApplet(boolean bReuploadApplet) { this.bReuploadApplet = bReuploadApplet; return this; } public RunConfig setInstallData(byte[] installData) { this.installData = installData; return this; } public RunConfig setTestCardType(CARD_TYPE testCardType) { this.testCardType = testCardType; return this; } } <file_sep>/src/main/cz/muni/fi/pv204/host/SecureChannel.java package cz.muni.fi.pv204.host; import cz.muni.fi.pv204.host.cardTools.Util; import javacard.framework.ISO7816; import org.bouncycastle.crypto.CryptoException; import sun.plugin.dom.exception.InvalidStateException; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.ShortBufferException; import javax.smartcardio.CardException; import javax.smartcardio.CommandAPDU; import javax.smartcardio.ResponseAPDU; import java.math.BigInteger; import java.security.*; import java.util.Arrays; public class SecureChannel { public static final short CHALLANGE_LENGTH = 32; public static final int PASS_LEN = 4; public static final short ROUNDS_PER_KEY = 50; public static final byte[] INS_R1_ID = Util.hexStringToByteArray("08110000" + "0A"); public static final byte[] INS_R1_GX = Util.hexStringToByteArray("08120000" + "82"); public static final byte[] INS_R1_ZKP1 = Util.hexStringToByteArray("08130000"); public static final byte[] INS_R1_ZKP2 = Util.hexStringToByteArray("08140000"); public static final byte[] INS_R2_GX = Util.hexStringToByteArray("08210000"); public static final byte[] INS_R2_B = Util.hexStringToByteArray("08220000"); public static final byte[] INS_R2_ZKP1 = Util.hexStringToByteArray("08230000"); public static final byte[] INS_R2_ZKP2 = Util.hexStringToByteArray("08240000"); public static final byte[] INS_R2_ZKP3 = Util.hexStringToByteArray("08250000"); public static final byte[] INS_R3_A = Util.hexStringToByteArray("08310000" + "41"); public static final byte[] INS_R3_ZKP1 = Util.hexStringToByteArray("08320000"); public static final byte[] INS_HELLO = Util.hexStringToByteArray("08410000"); public static final byte[] INS_RESET = Util.hexStringToByteArray("08420000"); public static final int SIZE_ECPOINT = 65; public static final byte SIZE_ECPOINT_BYTE = 0x41; public static final int SIZE_ID = 10; public static final short SW_NO_ERROR = (short) 0x9000; public static class ErrorResponseException extends Exception { private short errorCode; public ErrorResponseException(short errorCode) { this.errorCode = errorCode; } public short getErrorCode() { return errorCode; } } public static class ResponseFormatException extends Exception { public ResponseFormatException() { super(); } } public static class IncorrectPasswordException extends Exception { public IncorrectPasswordException() { super(); } } private JCardSymInterface channel; private MagicAes aes; private SecureRandom rand; private Participant participant; private byte[] participantIDB = new byte[SIZE_ID]; private short counter; private boolean established; public SecureChannel( JCardSymInterface channel, byte[] participantId, char[] password ) throws Exception { if (participantId.length != SIZE_ID) throw new Exception(); if (password.length != PASS_LEN) throw new Exception(); byte[] p = new byte[PASS_LEN]; for (int i=0; i < PASS_LEN; i++) { if (! Character.isDigit(password[i])) throw new Exception(); p[i] = (byte) (password[i] - '0'); } this.channel = channel; rand = SecureRandom.getInstanceStrong(); aes = new MagicAes(); participant = new Participant(participantId, p); counter = 0; established = false; } public void establishSC() throws CardException, ErrorResponseException, CryptoException, ResponseFormatException, BadPaddingException, InvalidKeyException, IllegalBlockSizeException, ShortBufferException, IncorrectPasswordException, InvalidAlgorithmParameterException, DigestException { ResponseAPDU r; r = establishmentRound1(); validationRound2(r); r = establishmentRound3(); establishmentHello(r); counter = 0; established = true; } public void clear() { participant.clear(); } public boolean isEstablished() { return established; } public void reset() throws CardException { if (established) { channel.transmit(new CommandAPDU(INS_RESET)); } } public ResponseAPDU send(byte[] buffer) throws BadPaddingException, InvalidKeyException, IllegalBlockSizeException, ShortBufferException, InvalidAlgorithmParameterException, DigestException, CardException, InterruptedException { if (!established) throw new InvalidStateException("No connection"); if (counter >= ROUNDS_PER_KEY) { established = false; throw new InterruptedException("Counter ran out. COnnection closed"); } short l = 0; if (buffer.length < 5) { aes.nextIV(); return channel.transmit(new CommandAPDU(buffer)); } else { l = (short) (aes.padding.padLength((short) (buffer.length - ISO7816.OFFSET_CDATA)) + buffer.length); } if (l > 256) { throw new InvalidParameterException(); } byte[] outBuffer = new byte[l]; System.arraycopy(buffer, 0, outBuffer, 0, buffer.length); try { aes.padding.pad( outBuffer, (short) ISO7816.OFFSET_CDATA, (short) (buffer.length - ISO7816.OFFSET_CDATA), (short) (outBuffer.length - ISO7816.OFFSET_CDATA) ); } catch (Exception e) { } l = (short) aes.encrypt( outBuffer, (short) ISO7816.OFFSET_CDATA, (short) (outBuffer.length - ISO7816.OFFSET_CDATA), outBuffer, (short) ISO7816.OFFSET_CDATA, (short) (outBuffer.length - ISO7816.OFFSET_CDATA) ); outBuffer[ISO7816.OFFSET_LC] = getLSB(l); if (l > 255) { outBuffer[ISO7816.OFFSET_LC] = 0x00; } counter++; ResponseAPDU response = channel.transmit(new CommandAPDU(outBuffer)); Arrays.fill(buffer, (byte) 0x00); return response; } public short decryptDataBuffer(byte[] buffer) throws InvalidAlgorithmParameterException, ShortBufferException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, DigestException { if (buffer.length == 0) { aes.nextIV(); return 0; } aes.decrypt( buffer, (short) 0, (short) buffer.length, buffer, (short) 0, (short) buffer.length ); return aes.padding.unpad(buffer, (short) 0, (short) buffer.length); } private ResponseAPDU establishmentRound1( ) throws CardException, ErrorResponseException { Round1Payload round1 = participant.createRound1PayloadToSend(); byte[] Gx1 = round1.getGx1().getEncoded(false); byte[] Gx2 = round1.getGx2().getEncoded(false); byte[] zkp1 = combine( round1.getKnowledgeProofForX1().getV().getEncoded(false), round1.getKnowledgeProofForX1().getr().toByteArray() ); byte[] zkp2 = combine( round1.getKnowledgeProofForX2().getV().getEncoded(false), round1.getKnowledgeProofForX2().getr().toByteArray() ); byte[] participantIDA = round1.getParticipantId(); byte[] b = round1.getKnowledgeProofForX2().getr().toByteArray(); byte[] outgoing; short offset = 0; byte[] len = new byte[1]; outgoing = participantIDA; ResponseAPDU response = channel.transmit( new CommandAPDU(combine(INS_R1_ID, outgoing)) ); checkResponseAccept(response); outgoing = new byte[Gx1.length + Gx2.length]; offset = 0; System.arraycopy( Gx1, (short) 0, outgoing, offset, Gx1.length ); offset += Gx1.length; // Gx2 System.arraycopy( Gx2, (short) 0, outgoing, offset, Gx2.length ); response = channel.transmit( new CommandAPDU(combine(INS_R1_GX, outgoing)) ); checkResponseAccept(response); outgoing = zkp1; len[0] = (byte) (getLSB(outgoing.length) ); response = channel.transmit( new CommandAPDU(combine(INS_R1_ZKP1, combine(len, outgoing))) ); checkResponseAccept(response); outgoing = zkp2; len[0] = (byte) (getLSB(outgoing.length) ); response = channel.transmit( new CommandAPDU(combine(INS_R1_ZKP2, combine(len, outgoing))) ); checkResponseAccept(response); return response; } private void validationRound2( ResponseAPDU response ) throws CardException, CryptoException, ErrorResponseException, ResponseFormatException { short sizeOfGx = SIZE_ECPOINT; byte[] Gx3 = new byte[sizeOfGx]; byte[] Gx4 = new byte[sizeOfGx]; byte[] B = new byte[sizeOfGx]; byte[] zkp1; byte[] zkp2; byte[] zkp3; // Validation byte[] incoming; short offset; checkResponseLength(response, SIZE_ID, SIZE_ID); incoming = response.getData(); offset = 0; System.arraycopy( incoming, offset, participantIDB, (short) 0, SIZE_ID ); response = channel.transmit( new CommandAPDU(INS_R2_GX) ); checkResponseAccept(response); checkResponseLength(response, 2*SIZE_ECPOINT, 2*SIZE_ECPOINT); incoming = response.getData(); offset = 0; System.arraycopy( incoming, offset, Gx3, (short) 0, sizeOfGx ); offset += sizeOfGx; // Gx2 System.arraycopy( incoming, offset, Gx4, (short) 0, sizeOfGx ); response = channel.transmit( new CommandAPDU(INS_R2_B) ); checkResponseAccept(response); checkResponseLength(response, SIZE_ECPOINT, SIZE_ECPOINT); incoming = response.getData(); offset = 0; // B System.arraycopy( incoming, offset, B, (short) 0, SIZE_ECPOINT ); response = channel.transmit( new CommandAPDU(INS_R2_ZKP1) ); checkResponseAccept(response); checkResponseLength(response, SIZE_ECPOINT+1, 255); incoming = response.getData(); offset = 0; // ZKP X3 zkp1 = split(incoming, offset, incoming.length); response = channel.transmit( new CommandAPDU(INS_R2_ZKP2) ); checkResponseAccept(response); checkResponseLength(response, SIZE_ECPOINT+1, 255); incoming = response.getData(); offset = 0; // ZKP X4 zkp2 = split(incoming, offset, incoming.length); response = channel.transmit( new CommandAPDU(INS_R2_ZKP3) ); checkResponseAccept(response); checkResponseLength(response, SIZE_ECPOINT+1, 255); incoming = response.getData(); offset = 0; // ZKP X4s zkp3 = split(incoming, offset, incoming.length); participant.validateRound2PayloadReceived( new Round2Payload( participantIDB, participant.ecCurve.decodePoint(Gx3), participant.ecCurve.decodePoint(Gx4), participant.ecCurve.decodePoint(B), decodeZKP(zkp1, 0, zkp1.length), decodeZKP(zkp2, 0, zkp2.length), decodeZKP(zkp3, 0, zkp3.length) ) ); } private ResponseAPDU establishmentRound3( ) throws CardException, ErrorResponseException { short sizeOfGx = SIZE_ECPOINT; byte[] A = new byte[sizeOfGx]; byte[] zkp1; Round3Payload round3 = participant.createRound3PayloadToSend(); A = round3.getA().getEncoded(false); zkp1 = combine( round3.getKnowledgeProofForX2s().getV().getEncoded(false), round3.getKnowledgeProofForX2s().getr().toByteArray() ); byte[] outgoing; short offset ; ResponseAPDU response; byte[] len = new byte[1]; outgoing = A; response = channel.transmit( new CommandAPDU(combine(INS_R3_A, outgoing)) ); checkResponseAccept(response); outgoing = zkp1; len[0] = (byte) (getLSB(outgoing.length)); response = channel.transmit( new CommandAPDU(combine(INS_R3_ZKP1, combine(len, outgoing))) ); checkResponseAccept(response); return response; } private void establishmentHello( ResponseAPDU response ) throws ResponseFormatException, CardException, ErrorResponseException, IncorrectPasswordException, InvalidAlgorithmParameterException, ShortBufferException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, DigestException { byte[] challenge = response.getData(); checkResponseLength(response, CHALLANGE_LENGTH, CHALLANGE_LENGTH); aes.generateKey(participant.calculateKeyingMaterial().getEncoded(false), challenge); byte[] r = new byte[CHALLANGE_LENGTH]; rand.nextBytes(r); byte[] outgoing = new byte[2*CHALLANGE_LENGTH]; System.arraycopy(challenge, 0, outgoing, 0, CHALLANGE_LENGTH); for (short i = 0; i < CHALLANGE_LENGTH; i++) { outgoing[i] = (byte) ( r[i] ^ outgoing[i] ); outgoing[CHALLANGE_LENGTH+i] = r[i]; } aes.encrypt( outgoing, (short) 0, (short) outgoing.length, outgoing, (short) 0, (short) outgoing.length ); byte[] len = {(byte) (CHALLANGE_LENGTH*2)}; response = channel.transmit(new CommandAPDU(combine(INS_HELLO, combine(len, outgoing)))); checkResponseAccept(response); checkResponseLength(response, 2*CHALLANGE_LENGTH, 2*CHALLANGE_LENGTH); // handle response byte[] incoming = response.getData(); aes.decrypt( incoming, (short) 0, (short) incoming.length, incoming, (short) 0, (short) incoming.length ); for (short i = 0; i < CHALLANGE_LENGTH; i++) { if ( incoming[CHALLANGE_LENGTH+i] != (byte) (challenge[i] ^ incoming[i]) ) { throw new IncorrectPasswordException(); } } } private void checkResponseAccept(ResponseAPDU response) throws ErrorResponseException { if ((short) response.getSW() != SW_NO_ERROR ) { throw new ErrorResponseException((short) response.getSW()); } } private ResponseAPDU checkResponseLength( ResponseAPDU response, int lower, int upper ) throws ResponseFormatException { int l = response.getData().length; if (lower > l || l > upper) { throw new ResponseFormatException(); } return response; } private byte getLSB(int length) { // only works n positive values return (byte) (length & 0xff); } private byte[] combine(byte[] a, byte[] b) { byte[] r = new byte[a.length + b.length]; System.arraycopy(a, 0, r, 0, a.length); System.arraycopy(b, 0, r, a.length, b.length); return r; } private byte[] split(byte[] buffer, int offset, int length) { byte[] r = new byte[length]; System.arraycopy(buffer, offset, r, 0, length); return r; } private SchnorrZKP decodeZKP(byte[] buffer, int offset, int length) { byte[] V = new byte[SIZE_ECPOINT]; byte[] r; System.arraycopy( buffer, offset, V, (short) 0, SIZE_ECPOINT ); r = split(buffer, offset+SIZE_ECPOINT, length-SIZE_ECPOINT); return new SchnorrZKP( participant.ecCurve.decodePoint(V), new BigInteger(r) ); } } <file_sep>/README.md | | | :---: | | This repository contains implementation of J-Pake which was a result of an assignament for the Security Technologies project of Masaryk University. The implementation has number of issues, such as secrets not being cleared, and usage of non-Javacard compatible library. It is not fit for use in transfering secrets, nor is actively supported. | # PV204 Security Technologies Project Project of [PV204 Security Technologies for Spring, 2020](https://is.muni.cz/course/fi/spring2020/PV204). 1. Analyze 3 certificates, report and presentation. * [https://www.commoncriteriaportal.org/products/](https://www.commoncriteriaportal.org/products/) 2. Design and implement secure channel using ECDH. * J-Pake secure channel establishment and AES256 encrypted communication, for JavaCard 3. Audit and attack other implementation ## Certificates * FM1280 V05 * genuscreen 7.0 * Thinklogical TLX1280 ## Team Members * [<NAME>](https://github.com/TAnhMinh) * [<NAME>](https://github.com/ankurlohchab) * [<NAME>](https://github.com/TomasMadeja ## J-Pake secure channel The implementation was only tested for JCardSym. It includes a SecureChannel class that can be used for establishing connection and communication as seen below. ``` JCardSymInterface sym = JCardSymInterface.defaultCreateConnect(); byte[] id = Util.hexStringToByteArray("00010203040506070809"); char[] password = {'<PASSWORD>'}; SecureChannel channel = new SecureChannel(sym, id, password); channel.establishSC(); ResponseAPDU r; byte[] buff; r = channel.send(CMD_HELLO); buff = r.getData(); System.out.println(channel.decryptDataBuffer(buff)); System.out.println(Util.bytesToHex(buff)); ``` The secure channel only provides option to establish it, and send/recieve data. Its user is responsible for tracking the size of their APDUS (exception is raised if APDU is too large). <file_sep>/src/main/cz/muni/fi/pv204/host/PKCS5Padding.java package cz.muni.fi.pv204.host; /** * @author https://alvinalexander.com/java/jwarehouse/openjdk-8/jdk/src/share/classes/com/sun/crypto/provider/PKCS5Padding.java.shtml */ public class PKCS5Padding { private int blockSize; PKCS5Padding(int blockSize) { this.blockSize = blockSize; } public void padWithLen(byte[] in, short off, short inLen, short paddingLen) throws Exception { short len = paddingLen; if (in == null) return; if (len > inLen) { throw new Exception(); } byte paddingOctet = (byte) (len & 0xff); for (short i = 0; i < len; i++) { in[i + off] = paddingOctet; } return; } public short pad( byte[] buffer, short off, short currentLen, short avaliableLen ) { short l = padLength(currentLen); try { padWithLen(buffer, (short) (off + currentLen), (short) (avaliableLen - currentLen), l); } catch (Exception e) { return -1; } return (short) (currentLen + l); } public short unpad(byte[] in, short off, short len) { if ((in == null) || (len == 0)) { // this can happen if input is really a padded buffer return 0; } byte lastByte = in[off + len - 1]; short padValue = (short) ((short)lastByte & 0x0ff); if ((padValue < 0x01) || (padValue > blockSize)) { return -1; } short start = (short) (off + len - ((short) lastByte & 0x0ff)); if (start < off) { return -1; } for (short i = 0; i < ((short)lastByte & 0x0ff); i++) { if (in[start+i] != lastByte) { return -1; } } return start; } public short padLength(short len) { short paddingOctet = (short) (blockSize - (len % blockSize)); return paddingOctet; } } <file_sep>/src/test/cz/muni/fi/pv204/javacard/TestMagicAes.java package cz.muni.fi.pv204.javacard; import cz.muni.fi.pv204.host.JCardSymInterface; import cz.muni.fi.pv204.host.cardTools.Util; import cz.muni.fi.pv204.javacard.crypto.MagicAes; import javacard.framework.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Assertions; import javax.crypto.spec.PBEKeySpec; import javax.smartcardio.CommandAPDU; import javax.smartcardio.ResponseAPDU; public class TestMagicAes { public static class TestApplet extends Applet { public static final byte INS_ENCRYPT = 0x01; public static final byte INS_DECRYPT = 0x02; public static final byte[] AES_KEY = { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, }; public static final byte[] IV = { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff }; private MagicAes aes; public TestApplet() { aes = new MagicAes(); aes.generateKey(AES_KEY, IV); } public static void install(byte[] bArray, short bOffset, byte bLength) { // format - (offset +) [length|pin] + [length|AID] new TestApplet().register( bArray, (short) (bOffset + bArray[bOffset] + 2), bArray[bOffset + bArray[bOffset] + 1] ); } @Override public void process(APDU apdu) throws ISOException { byte[] buffer = apdu.getBuffer(); short l = apdu.setIncomingAndReceive(); switch (buffer[ISO7816.OFFSET_INS]) { case INS_ENCRYPT: l = aes.encrypt( buffer, ISO7816.OFFSET_CDATA, l, buffer, ISO7816.OFFSET_CDATA, l ); apdu.setOutgoingAndSend( ISO7816.OFFSET_CDATA, l ); break; case INS_DECRYPT: if ((l % 16) != 0) { ISOException.throwIt((short) 0x6710); } l = aes.decrypt( buffer, ISO7816.OFFSET_CDATA, l, buffer, ISO7816.OFFSET_CDATA, l ); apdu.setOutgoingAndSend(ISO7816.OFFSET_CDATA, l); break; } } } @Test public void bounceOnce() throws Exception { String msg = ( "11223344" + "11223344" + "11223344" + "11223344" ); JCardSymInterface sym = new JCardSymInterface( JCardSymInterface.APPLET_AID_BYTE, JCardSymInterface.INSTALL_DATA_BYTE, TestApplet.class ); sym.Connect(); cz.muni.fi.pv204.host.MagicAes aes = new cz.muni.fi.pv204.host.MagicAes(); aes.generateKey(TestApplet.AES_KEY, TestApplet.IV); byte[] msg_b = Util.hexStringToByteArray( "8001000010" + msg ); ResponseAPDU response = sym.transmit( new CommandAPDU( msg_b ) ); Assertions.assertNotNull(response); byte[] resp = response.getData(); Assertions.assertNotNull(resp); byte[] r = new byte[16]; aes.decrypt( resp, (short) 0, (short) resp.length, r, (short) 0, (short) resp.length ); Assertions.assertEquals(msg.toLowerCase(), Util.bytesToHex(r).toLowerCase()); } @Test public void bounceTwice() throws Exception { String msg = ( "11223344" + "11223344" + "11223344" + "11223344" ); JCardSymInterface sym = new JCardSymInterface( JCardSymInterface.APPLET_AID_BYTE, JCardSymInterface.INSTALL_DATA_BYTE, TestApplet.class ); sym.Connect(); cz.muni.fi.pv204.host.MagicAes aes = new cz.muni.fi.pv204.host.MagicAes(); aes.generateKey(TestApplet.AES_KEY, TestApplet.IV); byte[] msg_b; byte[] resp; ResponseAPDU response; msg_b = Util.hexStringToByteArray( "8001000010" + msg ); response = sym.transmit( new CommandAPDU( msg_b ) ); resp = response.getData(); aes.decrypt( resp, (short) 0, (short) resp.length, resp, (short) 0, (short) resp.length ); Assertions.assertEquals(msg.toLowerCase(), Util.bytesToHex(resp).toLowerCase(), "Round 1"); msg_b = Util.hexStringToByteArray( "8001000010" + Util.bytesToHex(resp) ); response = sym.transmit( new CommandAPDU( msg_b ) ); resp = response.getData(); aes.decrypt( resp, (short) 0, (short) resp.length, resp, (short) 0, (short) resp.length ); Assertions.assertEquals(msg.toLowerCase(), Util.bytesToHex(resp).toLowerCase(), "Round 2"); } } <file_sep>/src/main/cz/muni/fi/pv204/javacard/jpake/JPakePassword.java package cz.muni.fi.pv204.javacard.jpake; import javacard.framework.OwnerPIN; import javacard.framework.Util; public class JPakePassword extends OwnerPIN { private byte[] password; private byte[] wrongPassword; public JPakePassword(byte tries, byte length) { super(tries, length); password = new byte[length]; wrongPassword = new byte[length]; } @Override public void update(byte[] pin, short offset, byte length) { Util.arrayCopy(pin, offset, password, (short) 0, length); Util.arrayCopy(pin, offset, wrongPassword, (short) 0, length); wrongPassword[0] ^= 0xff; super.update(pin, offset, length); } public void decrement() { super.check(wrongPassword, (short) 0, (byte) wrongPassword.length); } public void correct() { super.check(password, (short) 0, (byte) password.length); } public byte[] getPassword() {return password;} } <file_sep>/src/test/cz/muni/fi/pv204/host/ParticipantTest.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cz.muni.fi.pv204.host; import org.bouncycastle.math.ec.ECPoint; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; /** * * @author minh */ public class ParticipantTest { public ParticipantTest() { } @BeforeAll public static void setUpClass() { } @AfterAll public static void tearDownClass() { } @BeforeEach public void setUp() { } @AfterEach public void tearDown() { } /** * Test of getState method, of class Participant. */ @Test public void testGetState() { System.out.println("getState"); Participant instance = null; int expResult = 0; int result = instance.getState(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of createRound1PayloadToSend method, of class Participant. */ @Test public void testCreateRound1PayloadToSend() { System.out.println("createRound1PayloadToSend"); Participant instance = null; Round1Payload expResult = null; Round1Payload result = instance.createRound1PayloadToSend(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of validateRound1PayloadReceived method, of class Participant. */ @Test public void testValidateRound1PayloadReceived() throws Exception { System.out.println("validateRound1PayloadReceived"); Round1Payload round1PayloadReceived = null; Participant instance = null; instance.validateRound1PayloadReceived(round1PayloadReceived); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of createRound2PayloadToSend method, of class Participant. */ @Test public void testCreateRound2PayloadToSend() { System.out.println("createRound2PayloadToSend"); Participant instance = null; Round2Payload expResult = null; Round2Payload result = instance.createRound2PayloadToSend(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of validateRound2PayloadReceived method, of class Participant. */ @Test public void testValidateRound2PayloadReceived() throws Exception { System.out.println("validateRound2PayloadReceived"); Round2Payload round2PayloadReceived = null; Participant instance = null; instance.validateRound2PayloadReceived(round2PayloadReceived); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of calculateKeyingMaterial method, of class Participant. */ @Test public void testCalculateKeyingMaterial() { System.out.println("calculateKeyingMaterial"); Participant instance = null; ECPoint expResult = null; ECPoint result = instance.calculateKeyingMaterial(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of createRound3PayloadToSend method, of class Participant. */ @Test public void testCreateRound3PayloadToSend() { System.out.println("createRound3PayloadToSend"); Participant instance = null; Round3Payload expResult = null; Round3Payload result = instance.createRound3PayloadToSend(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of validateRound3PayloadReceived method, of class Participant. */ @Test public void testValidateRound3PayloadReceived() throws Exception { System.out.println("validateRound3PayloadReceived"); Round3Payload round3PayloadReceived = null; Participant instance = null; instance.validateRound3PayloadReceived(round3PayloadReceived); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } } <file_sep>/certificate_analysis/fm1280_v05/report_fm1280_v05.md # FM1280 V05 ## TOE Description The evaluated product was FM1280 V05 Dual Interface Smart Card Chip with IC Dedicated Software, ecure smart card integrated circuit with dedicated software, developed by Shanghai Fudan Microelectronics Groups Co., Ltd.; TOE is intended for use in banking and finance market, electronic commerce or governmental applications. TOE uses standard as well as OTP EEPROM, ROM; system and coprocessor, PAE, and CLA RAM. TOE supports the following communication interfaces: ISO/IEC 14443 Type A contactless interface, ISO/IEC 7816 contact interface, GPIO, SPI and High Speed SPI, I2C, and UART. TOE includes the following coprocessors: CRC-CCITT, TRNG, DES/TDES, AES, PAE for RSA, PAE for ECC, Chinese Domestic Algorithm, and HASH (sha1/sha256). As hardware protection, TOE claims: Watch Dog Timer, Clock and Reset managment, Security Controller and Enviromental Detector Circuits (light sensors, temperature sensors, clock frequency monitors, voltage and glitch sensors), and active shielding. The TOE provides RNG, DES/TDES, AES, RSA, ECC and SHA1/SHA256 by HASH as secure cryptographic services. DES and SHA only claim corectness, not security due to algorithms attack resistance. TOE claims the RNG provides high entropy true random numbers. TOEs driver provides CRC, EEPROM, and IO opperations. TOEs driver services have not been made resistant against attacks. ## Assumed Attackers Model In accordance to teh section 3.2 of the Secuirty IC Platform protection profile, there are following threads to the TOE (all of which the TOE claims to fulfil): * Inherent information leakage (T.Leak-Inherent). * Physical probing (T.Phys-Probing). * Malfunction due to enviromental stress (T.Malfunction). * Pysical manipulation (T.Phys-Manipulation). * Forced information leakage (T.Leak-Forced). * Abuse of functionality (T.Abuse-Func). * Deficiency of random numbers (T.RND). An overview of mapping of s to Security Objectives for the TOE can be found in subsection 6.4.1 of the Security Target. **Cryptographic Services** claimed to be fulfilled as security objectives add the: * Security of RSA services for encryption and decryption (O.RSA). * Security of ECC services for signature generation, signature verification, diffie-hellman key agreement, point multiplication and point addition (O.ECC). * Security of the Triple-DES services for encryption and decryption (O.TDES). * Security of the AES services for encryption and decryption (O.AES). **Additional assumptions** are the TOEs comformance to: * Protection during packaging, finishing and personalisation (A.Process-Sec-IC). * Treament of user data (especially secret keys, A.Resp-Appl). ## Testing and Evaluation **Delivery** was supposedly checked during the evaluation, and a recommendation is to check evaluated versions of the components are checked to have been supplied. **Vulnerability Analysis** was taken based on public domain sources and the visibility of TOE given by the evaluation. Idependent analysis was done based on: design and implementation review of TOE, code review of crypto library and boot code, validation tests of security features, review of previous results considering "JIL Attack Methods for Smartcards and Similiar Devices", penetration tests. **Developer's tests** were supposedly performed on: engineering samples (cards or Dual-In_line_package ICs), wafers, simaltion tools to verify logical functions. **Evaluator tests** were performed using the developers hardware testing tools and performing developers test cases. Chosen tests to be sampled were on: TSFI's, interfaces of SFR-enforcing modules, security mechanisms, all developer test methods (listed above). Addition tests were perfomed by augmenting existing tests by various parameters, and supplementation by applying developer tests to different samples then indended to (engineeering samples to wafer, etc.). ## Conclusion The report and security target specifies the expected threat model in a great detail. Together with the evaluation, it gives a semblence of idea as to the tests performed, and a setup is given in the appendix of the report. Tests performed are, however, all closed only to developers, and hence possibly not easily reproduciable. This also hides any possible mistakes that could have been performed during testing. Errors in evaluation may have occured as well, as the testing results are not given (likely due to closed nature of tests).
67b9c5ce21d008a63067a98ad99c6fe07eaf4f76
[ "Markdown", "Java" ]
11
Java
TomasMadeja/pv204_Team_Project_Supercalifragilisticexpialidocious
5d333e54a85af79c278515c7f7011549d18f528f
560cf9f935ee6e8e9f3ade923f735ac274ecbd3a
refs/heads/master
<repo_name>dimohamdy/HUIPatternLockView-Swift<file_sep>/HUIPatternLockViewDemo/ViewController.swift // // ViewController.swift // HUIPatternLockViewDemo // // Created by ZhangTinghui on 15/10/25. // Copyright © 2015年 www.morefun.mobi. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var label: UILabel! @IBOutlet var lockView: HUIPatternLockView! override func viewDidLoad() { super.viewDidLoad() configuareLockViewWithImages() /* un-comment this line to use custom drawing api */ // configuareLockViewWithCustomDrawingCodes() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: - Custom LockView with images extension ViewController { private func configuareLockViewWithImages() { let defaultLineColor = HUIPatternLockView.defaultLineColor let correctLineColor = UIColor.greenColor() let wrongLineColor = UIColor.redColor() let normalImage = UIImage(named: "dot_normal") let highlightedImage = UIImage(named: "dot_highlighted") let correctImage = highlightedImage?.tintImage(correctLineColor) let wrongImage = highlightedImage?.tintImage(wrongLineColor) lockView.didDrawPatternWithPassword = { (lockView: HUIPatternLockView, count: Int, password: String?) -> Void in guard count > 0 else { return } let unlockPassword = <PASSWORD>]" self.label.text = "Got Password: " + password! if password == unlockPassword { lockView.lineColor = correctLineColor lockView.normalDotImage = correctImage lockView.highlightedDotImage = correctImage } else { lockView.lineColor = wrongLineColor lockView.normalDotImage = wrongImage lockView.highlightedDotImage = wrongImage } dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in lockView.resetDotsState() lockView.lineColor = defaultLineColor lockView.normalDotImage = normalImage lockView.highlightedDotImage = highlightedImage } } } } // MARK: - Custom LockView Drawing extension ViewController { private enum LockViewPasswordState: Int { case Normal case Correct case Wrong } private func configuareLockViewWithCustomDrawingCodes() { lockView.drawLinePathWithContext = { [unowned self] (path, context) -> Void in self.drawLockViewLinePath(path, context: context) } lockView.drawDotWithContext = { [unowned self] (dot, context) -> Void in self.drawLockViewDot(dot, context: context) } lockView.didDrawPatternWithPassword = { [unowned self] (lockView, count, password) -> Void in self.handleLockViewDidDrawPassword(lockView, count: count, password: password) } } private func colorForLockViewState(state: LockViewPasswordState, useHighlightedColor: Bool) -> UIColor { switch state { case .Correct: return UIColor.greenColor() case .Wrong: return UIColor.redColor() default: if useHighlightedColor { return HUIPatternLockView.defaultLineColor } else { return UIColor.blackColor() } } } private func resetLockView(lockView: HUIPatternLockView) { lockView.resetDotsState() lockView.drawLinePathWithContext = { [unowned self] (path, context) -> Void in self.drawLockViewLinePath(path, context: context) } lockView.drawDotWithContext = { [unowned self] (dot, context) -> Void in self.drawLockViewDot(dot, context: context) } lockView.userInteractionEnabled = true } private func handleLockViewDidDrawPassword(lockView: HUIPatternLockView, count: Int, password: String?) { guard count > 0 else { resetLockView(lockView) return } let unlockPassword = <PASSWORD>]" var state = LockViewPasswordState.Wrong if password == unlockPassword { state = .Correct } self.label.text = "Got Password: " + password! lockView.userInteractionEnabled = false lockView.drawLinePathWithContext = { [unowned self] (path, context) -> Void in self.drawLockViewLinePath(path, context: context, state: state) } lockView.drawDotWithContext = { [unowned self] (dot, context) -> Void in self.drawLockViewDot(dot, context: context, state: state) } dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in self.resetLockView(lockView) } } private func drawLockViewLinePath(path: Array<CGPoint>, context: CGContextRef?, state: LockViewPasswordState = .Normal) { if path.isEmpty { return } let color = colorForLockViewState(state, useHighlightedColor: true) let dashLengths: [CGFloat] = [5.0, 10.0, 5.0] CGContextSetStrokeColorWithColor(context, color.CGColor); CGContextSetLineWidth(context, 3) CGContextSetLineCap(context, .Round) CGContextSetLineJoin(context, .Round) CGContextSetLineDash(context, 0, dashLengths, 3) let fistPoint = path.first for point in path { if point == fistPoint { CGContextMoveToPoint(context, point.x, point.y) } else { CGContextAddLineToPoint(context, point.x, point.y) } } CGContextDrawPath(context, .Stroke) } private func drawLockViewDot(dot: HUIPatternLockView.Dot, context: CGContextRef?, state: LockViewPasswordState = .Normal) { let dotCenter = dot.center let innerDotRadius: CGFloat = 15.0 let color = colorForLockViewState(state, useHighlightedColor: dot.highlighted) CGContextSetLineWidth(context, 1) CGContextSetFillColorWithColor(context, color.CGColor) CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextMoveToPoint(context, dotCenter.x, dotCenter.y) CGContextBeginPath(context) CGContextAddArc(context, dotCenter.x, dotCenter.y, innerDotRadius, 0, CGFloat(2*M_PI), 1) CGContextClosePath(context) CGContextFillPath(context) CGContextStrokeEllipseInRect(context, dot.frame) } } extension UIImage { public func tintImage(tintColor: UIColor) -> UIImage { return tintImage(tintColor, blendMode: .DestinationIn) } public func gradientTintImage(tintColor: UIColor) -> UIImage { return tintImage(tintColor, blendMode: .Overlay) } public func tintImage(tintColor: UIColor, blendMode: CGBlendMode) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0.0) let bounds = CGRect(origin: CGPointZero, size: size) tintColor.setFill() UIRectFill(bounds) drawInRect(bounds, blendMode: blendMode, alpha: 1.0) //draw again to save alpha channel if blendMode != .DestinationIn { drawInRect(bounds, blendMode: .DestinationIn, alpha: 1.0) } let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
f35f5915db92b1839c547108752983a32588eea6
[ "Swift" ]
1
Swift
dimohamdy/HUIPatternLockView-Swift
4a376de937029b0e40e8b61ac41c311023be877e
9a85431dfc9070f7beddf89dbd4fe9d64c7fbbc6
refs/heads/master
<repo_name>lucemans/whatthedot<file_sep>/tests/Graph.spec.ts import { GraphStylePresets } from '../src/Style'; import Graph from '../src/Graph'; import Node from '../src/Node'; describe('Graph Core', () => { test('Basic Graph', () => { const graph = new Graph('1'); expect(graph.serialize()).toEqual('digraph 1 {\n\n\n}'); }); test('Basic Graph 1 Node', () => { const graph = new Graph('1'); const a = new Node('a'); graph.add(a); expect(graph.serialize()).toEqual('digraph 1 {\n\t0 [label = a]\n}'); }); test('Basic Graph 2 Node', () => { const graph = new Graph('1'); const a = new Node('a'); const b = new Node('b'); graph.add(a); graph.add(b); expect(graph.serialize()).toEqual('digraph 1 {\n\t0 [label = a]\n\t1 [label = b]\n}'); }); }); describe('Connecections', () => { test('1 Connection', () => { const graph = new Graph('1'); const a = new Node('a'); const b = new Node('b'); a.goesTo(b); graph.add(a); graph.add(b); expect(graph.serialize()).toEqual('digraph 1 {\n\t0 [label = a]\n\t1 [label = b]\n\t0 -> 1\n}') }); }); describe('Styles', () => { test('Clean Empty', () => { const graph = new Graph('1'); graph.style = GraphStylePresets.minified; expect(graph.serialize()).toEqual('digraph 1{}'); }) });<file_sep>/tests/Node.spec.ts import Graph from '../src/Graph'; import Node, { NodeShape } from '../src/Node'; describe('Initializers', () => { test('Simple Label', () => { const graph = new Graph('1'); const n = new Node("label"); graph.add(n); expect(n.getInitializer()).toEqual('0 [label = label]'); }); test('Box Shape', () => { const graph = new Graph("1"); const n = new Node("label", {shape: NodeShape.box}); graph.add(n); expect(n.getInitializer()).toEqual('0 [label = label, shape = box]'); }); test('Custom Width', () => { const graph = new Graph("1"); const n = new Node("label", {width: 2}); graph.add(n); expect(n.getInitializer()).toEqual('0 [label = label, width = 2]'); }); test('Custom Width < 1', () => { const graph = new Graph("1"); const n = new Node("label", {width: 0.5}); graph.add(n); expect(n.getInitializer()).toEqual('0 [label = label, width = .5]'); }); test('Custom Width Default Value', () => { const graph = new Graph("1"); const n = new Node("label", {width: 0.75}); graph.add(n); expect(n.getInitializer()).toEqual('0 [label = label]'); }); }); describe('Node Linking', () => { test('Simple One-Directional', () => { const graph = new Graph('1'); const a = new Node('a'); const b = new Node('b'); graph.add(a); graph.add(b); a.goesTo(b); expect(a.getGoto()).toEqual(['0 -> 1']); }); test('Simple Multi-Directional', () => { const graph = new Graph('1'); const a = new Node('a'); const b = new Node('b'); const c = new Node('c'); graph.add(a); graph.add(b); graph.add(c); a.goesTo(b); a.goesTo(c); expect(a.getGoto()).toEqual(['0 -> 1','0 -> 2']); }); });<file_sep>/src/Graph.ts import Node from "./Node"; import { GraphStyle, GraphStylePresets } from "./Style"; export enum GraphType { GRAPH='graph', DIGRAPH='digraph' } export default class Graph { id: string; nodes: Node[] = []; type: GraphType = GraphType.DIGRAPH; style: GraphStyle = GraphStylePresets.clean; lastID = 0; constructor(id: string) { this.id = id; } add(n: Node) { this.nodes.push(n); n.graph = this; n.id = this.getNextID(); } serialize() { let c = [] .concat(this.nodes.map((a)=>{return a.getInitializer()})); this.nodes.map((a)=>{return a.getGoto()}).forEach((a) => { c = c.concat(a); }); let _content = c.map(a=>this.style.content_pre+a).join(this.style.content_delim) || this.style.graph_empty; return this.style.graph_definition.replace('$graph', this.type.toString().toLowerCase()).replace('$id', this.id).replace('$content', _content == this.style.graph_empty ? this.style.graph_empty : this.style.content_wrap.replace('$content', _content)); } getNextID(): string { this.lastID++; return (this.lastID-1).toString(); } }<file_sep>/src/Style.ts export interface GraphStyle { graph_definition: string; graph_empty: string; content_wrap: string; content_delim: string; content_pre: string; node_initializer: string; node_prop: string; node_prop_delim: string; connection_line: string; } export const GraphStylePresets = { minified: { content_delim: ";", content_pre: "", content_wrap: "$content", graph_definition: "$graph $id{$content}", graph_empty: "", node_initializer: "$id[$props]", node_prop: "$key=$value", node_prop_delim: ",", connection_line: "$connection", }, partial: { content_delim: "\n", content_pre: "\t", content_wrap: "\n$content\n", graph_definition: "$graph $id {$content}", graph_empty: "", node_initializer: "$id [$props]", node_prop: "$key=$value", node_prop_delim: ",", connection_line: "$connection", }, clean: { content_delim: "\n", content_pre: "\t", content_wrap: "\n$content\n", graph_definition: "$graph $id {$content}", graph_empty: "\n\n\n", node_initializer: "$id [$props]", node_prop: "$key = $value", node_prop_delim: ", ", connection_line: " $connection ", } }<file_sep>/src/Node.ts import { GraphStyle, GraphStylePresets } from "./Style"; import Graph, { GraphType } from "./Graph"; export enum NodeShape { elipse="elipse", box="box", circle="circle", record="record", plaintext="plaintext" } export interface NodeProperties { shape?: NodeShape; width?: number; height?: number; label?: string; } let defaultNodeProps: NodeProperties = { label: '', shape: NodeShape.elipse, width: 0.75, height: 0.5, } export default class Node { id: string; props: NodeProperties; _goto: Node[] = []; graph: Graph; constructor(label: string, props: NodeProperties = defaultNodeProps) { this.id = "-1"; this._goto = []; this.props = {}; Object.keys(defaultNodeProps).forEach(a => { this.props[a] = props[a] ? props[a] : defaultNodeProps[a]; }); this.props.label = label; } /* Settings */ goesTo(...node: Node[]) { node.forEach((node) => { this._goto.push(node); }); } /* SERIALIZATION */ getGoto(): string[] { const interject = this.getStyle().connection_line.replace('$connection', this.graph.type == GraphType.DIGRAPH ? '->' : '--'); return this._goto.map(to => this.id + interject + to.id); } getInitializer() { const style = this.getStyle(); let props = {}; Object.keys(this.props).filter(a => { return this.props[a] != defaultNodeProps[a]; }).forEach(a => { props[a] = this.props[a]; }); function parseValue(a: string) { if (typeof props[a] == 'number') { return props[a].toString().replace(/0\./g, '.'); } if (typeof props[a] == 'string') return props[a].toString().includes(' ') ? '"' + props[a] + '"' : props[a] return props[a]; } const propsArray = Object.keys(props) .map(a => style.node_prop .replace('$key', a) .replace('$value', parseValue(a))); return style.node_initializer.replace('$id', this.id).replace('$props', propsArray.join(style.node_prop_delim)); } getStyle(): GraphStyle { return this.graph ? this.graph.style : GraphStylePresets.clean; } }<file_sep>/src/Rank.ts export default class Rank { label: string; }<file_sep>/README.md # WhAtThEdOt A simple library for building dot (graphviz) files with javascript and typescript # Aim My primary aim for this project is to build something fun while learning DOT on the way. And ofc just have fun with dot # Examples Below are some examples of fun stuff you can do with dot ## Ur average dot file ### Code ```dot digraph figureName { name -> thing; thing -> name; } ``` ### Output: ![](./examples/basic.dot.svg) ## Example from the documentation ### Code ```dot digraph G { main -> parse -> execute; main -> init; main -> cleanup; execute -> make_string; execute -> printf; init -> make_string; main -> printf; execute -> compare; } ``` ### Output: ![](./examples/docs.dot.svg) # Export / Convert Exporting can be done to `pdf` file format through the following command. ```shell $ dot -Tpdf foo.dot -o foo.pdf ``` # Extension Allows you to open preview of your graph to the side # Links | Description | Link | | --------- | ---- | | The dot documentation | https://graphviz.org/pdf/dotguide.pdf | | VSCode Extension | https://marketplace.visualstudio.com/items?itemName=joaompinto.vscode-graphviz |<file_sep>/src/index.ts import Node from './Node'; import Graph from './Graph'; import Rank from './Rank'; import { GraphStylePresets, GraphStyle } from './Style'; export { GraphStyle }; export { Node }; export { Graph }; export { Rank }; export { GraphStylePresets };
06c388ff0eec1371b4c99373bc88b83ac952455c
[ "Markdown", "TypeScript" ]
8
TypeScript
lucemans/whatthedot
bcf6edb5e85ce6cb158d2bae6d7143e8cc89c01d
191dae5c4c807e99df61969245c2a5c9b8e20665
refs/heads/master
<file_sep># -*- coding: utf-8 -*- """ Created on Mon Dec 10 14:43:55 2018 @author: ASUS """ from keras.models import Model from keras.layers import LSTM, Activation, Dense, Dropout, Input, Embedding from keras.optimizers import RMSprop from keras.preprocessing.text import Tokenizer from keras.preprocessing import sequence from keras.utils import to_categorical from keras.callbacks import EarlyStopping from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.layers import Dense import numpy as np import pandas as pd #dataset = numpy.loadtxt("pima-indians-diabetes.csv") dataset = pd.read_csv('spam.csv' ,encoding = "ISO-8859-1") labels = dataset['v1'] Text = dataset['v2'] tk = Tokenizer(nb_words=2000) tk.fit_on_texts(Text) Text = tk.texts_to_sequences(Text) labels = labels.map({'spam':0, 'ham':1}) Text_Train, Text_Test, labels_train, labels_test = train_test_split(Text,labels,test_size=0.33) Text_Train = sequence.pad_sequences(Text_Train, 150) Text_Test = sequence.pad_sequences(Text_Test, 150) batch_size =20 epochs = 10 num_classes = 15 model = Sequential() model.add(Embedding(2000, 50, input_length=150)) model.add(Dropout(0.2)) model.add(LSTM(100, dropout=0.2, recurrent_dropout=0.2)) model.add(Dense(250, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) train = model.fit(Text_Train, labels_train, batch_size=batch_size,epochs=epochs)#,validation_data=(valid_X, valid_label)) eva = model.evaluate(Text_Test, labels_test, verbose=0) print('Test loss:', eva[0]) print('Test accuracy:', eva[1])
1ad4c72124038784d453028dbb6ab12dec89e891
[ "Python" ]
1
Python
anisjbili/LSTM-RNN
b8252ad3cc28b824fb4918fe3a3e36c532b5e9c5
62461ed79f946ddb14c4d83ef0ff605d1ee9049e
refs/heads/master
<repo_name>calvinfeng/k-means<file_sep>/k_mean.py import csv import pdb import matplotlib.pyplot as pyplot import matplotlib.cm as cm from random import randint from random import shuffle from math import sqrt def distance(point, centroid): square_sum = 0 for i in range(0, len(point)): square_sum += (point[i] - centroid[i])**2 return sqrt(square_sum) def k_mean(data, k): centroids = [] random_idx = generate_uniq_randoms(len(data), k) # Randomly initializing centroids for i in range(0, k): new_centroid = [] for j in range(0, len(data[i])): new_centroid.append(data[random_idx[i]][j]) centroids.append(new_centroid) labels = [None]*len(data) while True: for i in range(0, len(data)): labels[i] = assign_label(data[i], centroids) cluster_averages = compute_cluster_average(k, 2, data, labels) if is_equal(centroids, cluster_averages): break else: for i in range(0, len(centroids)): centroids[i] = cluster_averages[i] return labels def is_equal(v, u): for i in range(0, len(v)): for j in range(0, len(v[i])): if v[i][j] != u[i][j]: return False return True def compute_cluster_average(k, dimen, data, labels): cluster_averages = [] cluster_population = [0]*k # we have k clusters and we are going to initlize 0 values for averages for i in range(0, k): cluster_averages.append([0]*dimen) for i in range(0, len(data)): cluster_idx = labels[i] cluster_population[cluster_idx] += 1 for j in range(0, dimen): cluster_averages[cluster_idx][j] += data[i][j] for i in range(0, k): for j in range(0, dimen): cluster_averages[i][j] = cluster_averages[i][j]/cluster_population[i] return cluster_averages def generate_uniq_randoms(int_range, k): arr = [] max_int = int_range for i in range(0, max_int): arr.append(i) shuffle(arr) return arr[0:k] def assign_label(point, centroids): min_distance = None centroid_idx = None for i in range(0, len(centroids)): dist = distance(point, centroids[i]) if min_distance == None or dist < min_distance: min_distance = dist centroid_idx = i return centroid_idx data = [] movie_file = open('movie_metadata.csv', 'rb') csv_reader = csv.reader(movie_file) for row in csv_reader: if row[8].isdigit(): gross = float(row[8])/760505847 rating = float(row[25])/10 data.append([gross, rating]) labels = k_mean(data, 4) colors = {0: 'red', 1: 'blue', 2: 'green', 3: 'purple', 4: 'yellow', 5: 'brown'} figure = pyplot.figure() axes = figure.add_axes() sub1 = figure.add_subplot(211) sub2 = figure.add_subplot(212) for i in range(0, len(data)): sub1.scatter(data[i][0]*760505847, data[i][1]*10) sub2.scatter(data[i][0]*760505847, data[i][1]*10, color = colors[labels[i]]) pyplot.xlabel('Gross (in hundred millions $)') pyplot.ylabel('IMBD Rating') pyplot.show() <file_sep>/README.md # Unsupervised Learning - Clustering Algorithm
ba7e1cdaac2aa2095c764f3d1131a5d91ea014f6
[ "Markdown", "Python" ]
2
Python
calvinfeng/k-means
bdf30272183aab740162b739c0d3040dfe826556
e648b0f4ce6165237d814de016ddd8704a994206
refs/heads/main
<repo_name>JwoodCoding/TablesatBlayds<file_sep>/TablesatBlayds/ViewModel/BookingListViewModel.swift // // BookingListViewModel.swift // TablesatBlayds // // Created by <NAME> on 18/06/2021. // import SwiftUI import Combine final class BookingListViewModel : ObservableObject { private let userService: UserServiceProtocol private let bookingService: BookingServiceProtocol init(userService: UserServiceProtocol = UserService(), bookingService: BookingServiceProtocol = BookingService() ) { self.userService = userService self.bookingService = bookingService } } <file_sep>/TablesatBlayds/Services/UserService.swift // // UserService.swift // TablesatBlayds // // Created by <NAME> on 18/06/2021. // import Combine import FirebaseAuth protocol UserServiceProtocol { func currentUser() -> AnyPublisher<User?, Never> func signInAnonymously() -> AnyPublisher<User, Error> } final class UserService: UserServiceProtocol { func currentUser() -> AnyPublisher<User?, Never> { Just(Auth.auth().currentUser).eraseToAnyPublisher() } func signInAnonymously() -> AnyPublisher<User, Error> { return Future<User, Error> { promise in Auth.auth().signInAnonymously { result, error in if let error = error { return promise(.failure(error)) } else if let user = result?.user { return promise(.success(user)) } } }.eraseToAnyPublisher() } } <file_sep>/TablesatBlayds/View/MakeBookingView.swift // // MakeBookingView.swift // TablesatBlayds // // Created by <NAME> on 18/06/2021. // import SwiftUI struct MakeBookingTemplate: View { @State var selectedTab = "MakeBooking" @StateObject var viewModel = CreateBookingViewModel() let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .long return formatter }() @State private var bookingDate = Date() @State private var startTime = Date() @State private var endTime = Date() var dropdownList: some View { Group { DropdownView(viewModel: $viewModel.locationDropdown) DropdownView(viewModel: $viewModel.peopleDropdown) } // ForEach(viewModel.dropdowns.indices, id: \.self) { index in // DropdownView(viewModel: $viewModel.dropdowns[index]) // } } var mainContentView: some View { ScrollView{ VStack{ DatePicker(selection: $bookingDate, in: Date()..., displayedComponents: .date) { Text("Select a date") .font(.title3) .fontWeight(.semibold) } .padding() Spacer() DatePicker(selection: $startTime, in: Date()..., displayedComponents: .hourAndMinute) { Text("Select a start time") .font(.title3) .fontWeight(.semibold) } .padding() Spacer() DatePicker(selection: $endTime, in: Date()..., displayedComponents: .hourAndMinute) { Text("Select an end time") .font(.title3) .fontWeight(.semibold) } .padding() Spacer() dropdownList Spacer() Button(action: { viewModel.send(action: .createBooking) }) { Text("Submit") .font(.system(size: 24, weight: .medium)) } } } .navigationBarTitle("Make a Booking") .navigationBarBackButtonHidden(true) .padding(.bottom, 15) } var body: some View { ZStack{ if viewModel.isLoading { ProgressView() } else { mainContentView } }.alert(isPresented: Binding<Bool>.constant($viewModel.error.wrappedValue != nil) { Alert(title: Text("Error"), message: Text($viewModel.error.wrappedValue?.localizedDescription ?? ""), dismissButton: Alert.Button?) }) .navigationBarTitle("Make a booking") .navigationBarBackButtonHidden(true) .padding(.bottom, 15) } } struct MakeBookingTemplate_Previews: PreviewProvider { static var previews: some View { MakeBookingTemplate() } } <file_sep>/TablesatBlayds/ViewModel/BookingViewModel.swift //// //// BookingViewModel.swift //// TablesatBlayds //// //// Created by <NAME> on 18/06/2021. //// // //import Foundation //import Combine //import FirebaseFirestore //import FirebaseFirestoreSwift // //class bookingViewModel: ObservableObject { // // @Published var bookings = [Booking]() // // private var db = Firestore.firestore() // // func fetchData() { // db.collection("booking").addSnapshotListener { (querySnapshot, error) in // guard let documents = querySnapshot?.documents else { // print("no documents") // return // } // // self.bookings = documents.map { (queryDocumentSnapshot) -> Booking in // let data = queryDocumentSnapshot.data() // let name = data["name"] as? String ?? "" // let bookingDate = (data["date"] as? Timestamp)?.dateValue() ?? Date() // let endTime = (data["endtime"] as? Timestamp)?.dateValue() ?? Date() // let location = data["location"] as? String ?? "" // let people = data["people"] as? Int ?? 0 // // return Booking(name: name, bookingDate: bookingDate, endTime: endTime, location: location, people: people) // // } // } // } // // func create(_ booking: Booking) -> AnyPublisher<Void, Error> { // return Future<Void, Error> { promise in // do { // _ = try self.db.collection("Bookings").addDocument(from: booking) // promise(.success(())) // } catch { // promise(.failure(error)) // } // }.eraseToAnyPublisher() // } //} <file_sep>/TablesatBlayds/View/HomePageView.swift // // HomePageView.swift // TablesatBlayds // // Created by <NAME> on 18/06/2021. // import SwiftUI struct HomePageView: View { @Binding var selectedTab: String // hiding tab bar init(selectedTab : Binding<String>) { self._selectedTab = selectedTab UITabBar.appearance().isHidden = true } var body: some View { // tab view with tabs TabView(selection: $selectedTab){ // Views Home() .tag("Home") MyBookings() .tag("My Bookings") MakeBooking() .tag("Make a Booking") Settings() .tag("Settings") ContactUs() .tag("Contact Us") } } } struct HomePageView_Previews: PreviewProvider { static var previews: some View { MainView() } } // all sub views struct Home: View { var body: some View { NavigationView{ ScrollView { VStack(alignment: .leading, spacing: 20){ Image("Blaydsext") .resizable() .aspectRatio(contentMode: .fill) .frame(width: getRect().width - 50, height: 400) .cornerRadius(20) VStack(alignment: .leading, spacing: 6, content: { Text("Welcome to Blayds Bar") .font(.title) .fontWeight(.bold) .foregroundColor(.primary) Text("Book with us soon!") .font(.subheadline) .fontWeight(.semibold) .foregroundColor(.gray) VStack{ Text("Blayds Bar strives to bring a fantastic customer experience, having been an esablished bar on Call Lane for over 15 years") Spacer() Spacer() Text("Find us here:") Image("Blaydsloc") .resizable() .aspectRatio(contentMode: .fill) .frame(width: getRect().width - 50, height: 400) .cornerRadius(20) } VStack(spacing: 5){ Text("Following Covid Guidelines as prescribed by UK Gov, please find below our COVID guidelines for your time at Blayds Bar") } VStack(spacing: 5){ Text("Below you will find links to our Terms and Agreements and Privacy Policy") } }) } .navigationTitle("Home") } } .padding(.leading) } } struct MyBookings: View { var body: some View { NavigationView{ Text("My Bookings") .font(.largeTitle) .fontWeight(.heavy) .foregroundColor(.primary) .navigationTitle("My Bookings") } } } struct MakeBooking: View { var body: some View { NavigationView{ MakeBookingTemplate() } } } struct Settings: View { var body: some View { NavigationView{ SettingsView() } } } struct ContactUs: View { var body: some View { NavigationView{ Text("Contact Us") .font(.largeTitle) .fontWeight(.heavy) .foregroundColor(.primary) .navigationTitle("Contact Us") } } } <file_sep>/TablesatBlayds/TablesatBlaydsApp.swift // // TablesatBlaydsApp.swift // TablesatBlayds // // Created by <NAME> on 18/06/2021. // import SwiftUI import Firebase @main struct TablesatBlaydsApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { LandingView() } } } class AppDelegate: NSObject, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil)-> Bool { print("setting up firebase") FirebaseApp.configure() return true } } <file_sep>/TablesatBlayds/View/SettingsView.swift // // SettingsView.swift // TablesatBlayds // // Created by <NAME> on 18/06/2021. // import SwiftUI struct SettingsView: View { @State var selectedTab = "Settings" var body: some View { ScrollView { VStack(alignment: .center){ Image("blaydssupport") .resizable() .aspectRatio(contentMode: .fit) .frame(width: getRect().width - 50, height: 400) .cornerRadius(20) VStack(alignment: .center, spacing: 10, content: { Text("Settings") .font(.title) .fontWeight(.bold) .foregroundColor(.primary) Spacer() VStack(alignment: .center, spacing: 5){ Button(action: {}, label: { Text("Covid Guidelines") }) } VStack(alignment: .center, spacing: 5){ Button(action: { // display T&A }, label: { Text("Terms and Agreements") }) Spacer() Spacer() Button(action: { // display priv pol }, label: { Text(" Pivacy Policy") }) } .padding() }) .padding(.horizontal, 80) } .navigationTitle("Settings") } } } struct SettingsView_Previews: PreviewProvider { static var previews: some View { SettingsView() } } <file_sep>/TablesatBlayds/Model/MVVModel.swift // // MVVModel.swift // TablesatBlayds // // Created by <NAME> on 18/06/2021. // import Foundation import SwiftUI import Firebase class ModelData : ObservableObject { @Published var email = "" @Published var password = "" @Published var isSignUp = false @Published var email_SignUp = "" @Published var password_SignUp = "" @Published var reEnterPassword = "" @Published var isLinkSend = false // alert view wiht textfields // error alerts @Published var alert = false @Published var alertMsg = "" //User ststaus @AppStorage("log_Status") var status = false // loading @Published var isLoading = false func resetPassword(){ let alert = UIAlertController(title: "Reset Password", message: "Enter your Email to reset your password", preferredStyle: .alert) alert.addTextField { (password) in password.placeholder = "Email" } let proceed = UIAlertAction(title: "Reset", style: .default) { (_) in // sending passwor dlink if alert.textFields![0].text! != ""{ withAnimation{ self.isLoading.toggle() } Auth.auth().sendPasswordReset(withEmail: alert.textFields![0].text!) { (err) in withAnimation{ self.isLoading.toggle() } if err != nil{ self.alertMsg = err!.localizedDescription self.alert.toggle() return } // alertig user self.alertMsg = "Password reset link has been sent to your email" self.alert.toggle() } } } let cancel = UIAlertAction(title: "Cancel", style: .destructive, handler: nil) alert.addAction(cancel) alert.addAction(proceed) //presenting UIApplication.shared.windows.first?.rootViewController?.present(alert, animated: true) } // login function func login(){ // checking all fields are inputted correctly if email == "" || password == ""{ self.alertMsg = "Fill the contents properly" self.alert.toggle() return } withAnimation { self.isLoading.toggle() } Auth.auth().signIn(withEmail: email, password: <PASSWORD>) { (result, err) in withAnimation { self.isLoading.toggle() } if err != nil{ self.alertMsg = err!.localizedDescription self.alert.toggle() return } // checking if user is verified or not // if not verified means logging out let user = Auth.auth().currentUser if !user!.isEmailVerified{ self.alertMsg = "please verify email address!!!" self.alert.toggle() // logging out try! Auth.auth().signOut() return } // setting user status as true withAnimation{ self.status = true } } } // sign up func signUp() { // checking if email_SignUp == "" || password_SignUp == "" || reEnterPassword == "" { self.alertMsg = "Fill contents properly" self.alert.toggle() return } if password_SignUp != reEnterPassword{ self.alertMsg = "password mismatch" self.alert.toggle() return } withAnimation{ self.isLoading.toggle() } Auth.auth().createUser(withEmail: email_SignUp, password: <PASSWORD>) { (result, err) in withAnimation{ self.isLoading.toggle() } if err != nil{ self.alertMsg = err!.localizedDescription self.alert.toggle() return } // sending verificaitno link result?.user.sendEmailVerification(completion: { (err) in if err != nil { self.alertMsg = err!.localizedDescription self.alert.toggle() return } // alerting user to verify email self.alertMsg = "Email verification has been sent, check your inbox!" self.alert.toggle() }) } } // logOut func logOut(){ try! Auth.auth().signOut() withAnimation { self.status = false } // clearing all data email = "" password = "" email_SignUp = "" password_SignUp = "" reEnterPassword = "" } } // checking with smaller devices // loading View struct LoadingView : View { @State var animation = false var body: some View { VStack { Circle() .trim(from: 0, to: 0.7) .stroke(Color("Color2"), lineWidth: 8) .frame(width: 75, height: 75) .rotationEffect(.init(degrees: animation ? 360 : 0)) .padding(50) } .background(Color.white) .cornerRadius(20) .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color.black.opacity(0.4).ignoresSafeArea(.all, edges: .all)) .onAppear(perform: { withAnimation(Animation.linear(duration: 1)) { animation.toggle() } }) } } <file_sep>/TablesatBlayds/ViewModel/CreateBookingViewModel.swift // // CreateBookingViewModel.swift // TablesatBlayds // // Created by <NAME> on 18/06/2021. // import SwiftUI import Firebase import Combine import FirebaseFirestoreSwift import FirebaseFirestore typealias UserId = String final class CreateBookingViewModel: ObservableObject { @Published var locationDropdown = BookingPartViewModel(type: .location) @Published var peopleDropdown = BookingPartViewModel(type: .people) @Published var isLoading = false private let userService: UserServiceProtocol private let bookingService: BookingServiceProtocol private var cancellables: [AnyCancellable] = [] enum Action { case createBooking } init(userService: UserServiceProtocol = UserService(), bookingService: BookingServiceProtocol = BookingService()) { self.userService = userService self.bookingService = bookingService } func send(action: Action) { switch action { case .createBooking: isLoading = true currentUserId().flatMap { userId -> AnyPublisher<Void, Error> in return self.createBooking(userId: userId) }.sink { completion in self.isLoading = false switch completion { case let .failure(error): print(error.localizedDescription) case .finished: print("finished") } } receiveValue: { _ in print("success") }.store(in: &cancellables) } } private func createBooking(userId: UserId) -> AnyPublisher<Void, Error> { guard let location = locationDropdown.text, let people = peopleDropdown.number else { return Fail(error: NSError()).eraseToAnyPublisher() } let booking = Booking(name: name, bookingDate: bookingDate, endTime: endTime, location: location, people: people, userId: UserId) return bookingService.create(booking).eraseToAnyPublisher() } private func currentUserId() -> AnyPublisher<UserId, Error> { print("getting user id") return userService.currentUser().flatMap { user -> AnyPublisher<UserId, Error> in if let userId = user?.uid { print("user is logged in...") return Just(userId) .setFailureType(to: Error.self) .eraseToAnyPublisher() } else { print("user is being logged in anonymously...") return self.userService .signInAnonymously() .map { $0.uid } .eraseToAnyPublisher() } }.eraseToAnyPublisher() } } extension CreateBookingViewModel { struct BookingPartViewModel: DropdownItemProtocol { var selectedOption: DropdownOption var options: [DropdownOption] var headerTitle: String { type.rawValue } var dropdownTitle: String { selectedOption.formatted } var isSelected: Bool = false private let type: BookingPartType init(type: BookingPartType) { switch type { case .location: self.options = LocationOption.allCases.map { $0.toDropdownOption} case .people: self.options = PeopleOption.allCases.map {$0.toDropdownOption} } self.type = type self.selectedOption = options.first! } enum BookingPartType: String, CaseIterable { case location = "Location" case people = "Number of People" } enum LocationOption: String, CaseIterable, DropdownOptionProtocol { case indoors case outdoors case upstairs var toDropdownOption: DropdownOption { .init(type: .text(rawValue), formatted: rawValue.capitalized ) } } enum PeopleOption: Int, CaseIterable, DropdownOptionProtocol { case one = 1, two, three, four, five case outdoors case upstairs var toDropdownOption: DropdownOption { .init(type: .number(rawValue), formatted: "\(rawValue)" ) } } } } extension CreateBookingViewModel.BookingPartViewModel { var text: String? { if case let .text(text) = selectedOption.type { return text } return nil } var number: Int? { if case let .number(number) = selectedOption.type { return number } return nil } } <file_sep>/TablesatBlayds/Services/BookingService.swift // // BookingService.swift // TablesatBlayds // // Created by <NAME> on 18/06/2021. // import Combine import FirebaseFirestore import FirebaseFirestoreSwift protocol BookingServiceProtocol { func create(_ booking: Booking) -> AnyPublisher<Void, Error> } final class BookingService: BookingServiceProtocol { private let db = Firestore.firestore() func create(_ booking: Booking) -> AnyPublisher<Void, Error> { return Future<Void, Error> { promise in do { _ = try self.db.collection("bookings").addDocument(from: booking) { error in if let error = error { promise(.failure(error)) } else { promise(.success(())) } } promise(.success(())) } catch { promise(.failure(error)) } }.eraseToAnyPublisher() } } <file_sep>/README.md Blayds i hate life <file_sep>/TablesatBlayds/LandingView.swift // // ContentView.swift // TablesatBlayds // // Created by <NAME> on 18/06/2021. // import SwiftUI struct LandingView: View { @AppStorage("log_status") var status = false @StateObject var model = ModelData() @State private var isActive = false var body: some View { NavigationView { GeometryReader{ proxy in VStack { Spacer().frame(height:proxy.size.height * 0.65) Text("Blayds Bar") .font(.system(size: 64, weight: .medium)) .foregroundColor(.white) Spacer() HStack { NavigationLink(destination: GetStartedView(), isActive: $isActive) { Button(action: { isActive = true }) { HStack(spacing: 15){ Spacer() Image(systemName: "person") .font(.system(size: 24)) .foregroundColor(.white) Text("Get Started") .foregroundColor(.white) Spacer() } } .padding(.horizontal, 5) .buttonStyle(PrimaryButtonStyle()) } } } .frame(maxWidth: .infinity, maxHeight: .infinity) .background( Image("barpic") .resizable() .aspectRatio(contentMode: .fill).overlay(Color.black.opacity(0.2)) .frame(width: proxy.size.width) .edgesIgnoringSafeArea(.all) ) } }.accentColor(.primary) } } struct LandingView_Previews: PreviewProvider { static var previews: some View { LandingView() } } <file_sep>/TablesatBlayds/View/Booking/BookingListView.swift // // BookingListView.swift // TablesatBlayds // // Created by <NAME> on 18/06/2021. // //import SwiftUI // //struct BookingListView: View { // // @ObservedObject private var viewModel = bookingViewModel() // // // var body: some View { // // NavigationView{ // List(viewModel.bookings) { booking in // VStack(alignment: .leading){ // Text(booking.dateString).font(.title3) // // } // }.navigationBarTitle("My Bookings") // // .onAppear() { // self.viewModel.fetchData() // } // } // // // } //} <file_sep>/TablesatBlayds/View/BookingsTemplate.swift // // BookingsTemplate.swift // TablesatBlayds // // Created by <NAME> on 18/06/2021. // import SwiftUI struct BookingsTemplate: View { var body: some View { VStack(alignment: .leading) { Text("Your upcoming bookings") .font(.title) .fontWeight(.semibold) } } } struct BookingsTemplate_Previews: PreviewProvider { static var previews: some View { BookingsTemplate() } } <file_sep>/TablesatBlayds/Model/Booking.swift // // Booking.swift // TablesatBlayds // // Created by <NAME> on 18/06/2021. // import Foundation struct Booking: Codable{ var dateString: String { let formatter = DateFormatter() formatter.dateFormat = "EEEE, dd 'of' MMMM" return formatter.string(from: bookingDate) } var timeString: String { let formatter = DateFormatter() formatter.dateFormat = "HH:MM" return formatter.string(from: endTime) } // var UserId: String = UUID().uuidString // // var name: String // // var bookingDate: Date // // var dateString: String { // // let formatter = DateFormatter() // formatter.dateFormat = "EEEE, dd 'of' MMMM" // return formatter.string(from: bookingDate) // } // // var endTime: Date // // var endTimeString: String{ // // let formatter = DateFormatter() // formatter.dateFormat = "HH:MM" // return formatter.string(from: endTime) // } // // var location: String // // var people: Int let name: String let bookingDate: Date let endTime: Date let location: String let people: Int let userId: String } extension Booking : Equatable, Hashable {} <file_sep>/TablesatBlayds/ViewModel/DatePickerProtocol.swift // // DatePickerProtocol.swift // TablesatBlayds // // Created by <NAME> on 19/06/2021. //
a79cd41d8f4a9add3844a48e00a0dc7d2c8c0438
[ "Swift", "Markdown" ]
16
Swift
JwoodCoding/TablesatBlayds
e745728c1dadc7cd838063f42d4558f4eb4e2514
77390ae97a2c8043cf464c37ba401dc6bfe5f84c
refs/heads/master
<repo_name>maciejpokorski/ListaPracownikow<file_sep>/Napis.cpp //<NAME> <NAME> #include "Napis.h" #include <string> #include <iostream> using namespace std; Napis::Napis(void) { } Napis::~Napis(void) { } const char* Napis::Zwroc() const { return this->m_pszNapis; } void Napis::Ustaw(const char* nowy_napis) { strncpy(this->m_pszNapis,nowy_napis,40); } void Napis::Wypisz() const { cout << this->Zwroc(); } void Napis::Wpisz() { cin >> this->m_pszNapis; } int Napis::SprawdzNapis(const char* por_napis) const { return strcmp(this->m_pszNapis, por_napis); }<file_sep>/Napis.h //<NAME> <NAME> #pragma once class Napis { public: Napis(void); ~Napis(void); const char* Zwroc() const; void Ustaw(const char* nowy_napis); void Wypisz() const; void Wpisz(); int SprawdzNapis(const char* por_napis) const; private: char m_pszNapis[40]; }; <file_sep>/Pracownik.cpp //<NAME> <NAME> #include "Pracownik.h" #include <iostream> using namespace std; Pracownik::Pracownik(void) { this->m_pNastepny = 0; this->m_pPoprzedni = 0; } Pracownik::~Pracownik(void) { } const char* Pracownik::Imie() const { return this->m_Imie.Zwroc(); } const char* Pracownik::Nazwisko() const { return this->m_Nazwisko.Zwroc(); } void Pracownik::Imie(const char* nowe_imie) { this->m_Imie.Ustaw(nowe_imie); } void Pracownik::Nazwisko(const char* nowe_nazwisko) { this->m_Nazwisko.Ustaw(nowe_nazwisko); } void Pracownik::DataUrodzenia(int nowy_dzien, int nowy_miesiac, int nowy_rok) { this->m_DataUrodzenia.Ustaw(nowy_dzien, nowy_miesiac, nowy_rok); } void Pracownik::Wypisz() const { this->m_Imie.Wypisz(); cout << " "; this->m_Nazwisko.Wypisz(); cout << " "; this->m_DataUrodzenia.Wypisz(); } void Pracownik::Wpisz() { cout << "Podaj imie: "; this->m_Imie.Wpisz(); cout << "Podaj naziwsko: "; this->m_Nazwisko.Wpisz(); this->m_DataUrodzenia.Wpisz(); } int Pracownik::SprawdzImie(const char* por_imie) const { return this->m_Imie.SprawdzNapis(por_imie); } int Pracownik::SprawdzNazwisko(const char* por_nazwisko) const { return this->m_Nazwisko.SprawdzNapis(por_nazwisko); } int Pracownik::Porownaj(const Pracownik& wzor) const { int i,d; int n = this->m_Nazwisko.SprawdzNapis(wzor.m_Nazwisko.Zwroc()); if ( n != 0) return n; else if ( (i = this->m_Imie.SprawdzNapis(wzor.m_Imie.Zwroc())) != 0) return i; else if ((d = this->m_DataUrodzenia.Porownaj(wzor.m_DataUrodzenia))!= 0) return d; else return 0; }<file_sep>/ListaZatrudnionych.h //<NAME> <NAME> #pragma once #include "Pracownik.h" class ListaZatrudnionych { public: ListaZatrudnionych(void); ~ListaZatrudnionych(void); void Dodaj(const Pracownik& p); void Usun(const Pracownik& wzorzec); void WypiszListeZatrudnionych() const; const Pracownik* Szukaj(const char* nazwisko, const char* imie) const; private: Pracownik* m_pPierwszy; Pracownik* m_pOstatni; int m_nLiczbaPracownikow; }; <file_sep>/Data.h //<NAME> <NAME> #pragma once class Data { public: Data(void); ~Data(void); void Ustaw(int d, int m, int r); private: int m_nDzien; int m_nMiesiac; int m_nRok; public: int Dzien(void) const; int Miesiac(void) const; int Rok(void) const; void Wypisz(void) const; void Wpisz(void); void Koryguj(void); int Porownaj(const Data &wzor) const; }; <file_sep>/program.cpp //<NAME> <NAME> #include "Data.h" #include "Napis.h" #include "Pracownik.h" #include "ListaZatrudnionych.h" #include <iostream> using namespace std; int main() { Pracownik p,p2,p3; p.Imie("Hubert"); p.Nazwisko("Sadecki"); p.DataUrodzenia(12,2,1994); p2.Imie("Hubert"); p2.Nazwisko("Sadecki"); p2.DataUrodzenia(1,2,1994); p3.Imie("Maciej"); p3.Nazwisko("Pokorski"); p3.DataUrodzenia(27,5,1994); ListaZatrudnionych L; L.Dodaj(p); L.Dodaj(p2); L.Dodaj(p3); L.WypiszListeZatrudnionych(); }<file_sep>/Data.cpp //<NAME> <NAME> #include "Data.h" #include <iostream> using namespace std; Data::Data(void) { m_nDzien = 1; m_nMiesiac = 1; m_nRok = 2000; } Data::~Data(void) { } void Data::Ustaw(int d, int m, int r) { this->m_nDzien = d; this->m_nMiesiac = m; this->m_nRok = r; this->Koryguj(); } int Data::Dzien(void) const { return m_nDzien; } int Data::Miesiac(void) const { return m_nMiesiac; } int Data::Rok(void) const { return m_nRok; } void Data::Wypisz(void) const { cout << this->Dzien() << "-" << this->Miesiac() << "-" << this->Rok() << endl; } void Data::Wpisz(void) { cout <<"Podaj dzien: "; cin >> this->m_nDzien; cout<<"Podaj miesiac: "; cin >> this->m_nMiesiac; cout << "Podaj rok: "; cin >> this->m_nRok; this->Koryguj(); } void Data::Koryguj(void) { if(this->m_nMiesiac >12) this->m_nMiesiac = 12; else if(this->m_nMiesiac <1) this->m_nMiesiac = 1; switch(m_nMiesiac) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: if(this->m_nDzien>31) this->m_nDzien = 31; else if(this->m_nDzien<1) this->m_nDzien = 1; break; case 4: case 6: case 9: case 11: if(this->m_nDzien>30) this->m_nDzien = 30; else if(this->m_nDzien<1) this->m_nDzien = 1; break; case 2: if(this->m_nDzien>28 && this->m_nRok % 4 != 0) this->m_nDzien = 28; else if(this->m_nDzien>29 && this->m_nRok % 4 == 0) this->m_nDzien = 29; else if(this->m_nDzien<1) this->m_nDzien = 1; break; } } int Data::Porownaj(const Data &wzor) const { if(this->Dzien() == wzor.Dzien() && this->Miesiac() == wzor.Miesiac() && this->Rok() == wzor.Rok()) return 0; else if(this->Rok() < wzor.Rok() || (this->Rok() == wzor.Rok() && this->Miesiac() < wzor.Miesiac()) || (this->Miesiac() == wzor.Miesiac() && this->Rok() == wzor.Rok() && this->Dzien() < wzor.Dzien())) return -1; else return 1; } <file_sep>/ListaZatrudnionych.cpp //<NAME> <NAME> #include "ListaZatrudnionych.h" #include <iostream> using namespace std; ListaZatrudnionych::ListaZatrudnionych(void) { m_pPierwszy = 0; m_pOstatni = 0; m_nLiczbaPracownikow = 0; } ListaZatrudnionych::~ListaZatrudnionych(void) { } void ListaZatrudnionych::Dodaj(const Pracownik& p) { if(this->m_pPierwszy == 0) { m_pOstatni = new Pracownik(p); m_pPierwszy = m_pOstatni; }else { m_pOstatni ->m_pNastepny = new Pracownik(p); m_pOstatni ->m_pNastepny ->m_pPoprzedni = m_pOstatni; m_pOstatni = m_pOstatni ->m_pNastepny; } m_nLiczbaPracownikow++; } void ListaZatrudnionych::Usun(const Pracownik& wzorzec) { } void ListaZatrudnionych::WypiszListeZatrudnionych() const { Pracownik *p; p = this->m_pPierwszy; if(p!=0) { while(p != 0) { p->Wypisz(); p = p->m_pNastepny; } }else { cout << "Lista pusta" <<endl; } } const Pracownik* ListaZatrudnionych::Szukaj(const char* nazwisko, const char* imie) const { Pracownik *p; p = this->m_pPierwszy; while (p != 0) { if (p->SprawdzImie(imie) == 0 && p->SprawdzNazwisko(nazwisko) == 0) return p; p = p->m_pNastepny; } return 0; }
7d6c12c93a8028d6ddaf21b6794a7d3246823086
[ "C++" ]
8
C++
maciejpokorski/ListaPracownikow
09f680027a9debeb2f50174c5a6fa3de058c9613
485ec728085c97607666cf46cd5d843c204654af
refs/heads/master
<file_sep># you are going to die today Entry for Ludum Dare 47 <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class InteractiveItem : MonoBehaviour { private GameManager gameManager; public string choiceText; public string choiceA; public string choiceB; public bool choiceACorrect; public bool hasSelected; public int endingNumber; public string alreadySelectedMessage; public string notReadyYetMessage; public bool isReady; public bool noButtons; public AudioClip clip; // Start is called before the first frame update void Start() { gameManager = FindObjectOfType<GameManager>(); } // Update is called once per frame void Update() { } public void Selected(bool choiceACorrect) { if (this.choiceACorrect != choiceACorrect) { gameManager.endingNumber = endingNumber; } gameManager.StageUp(); hasSelected = true; InteractiveItem [] items = FindObjectsOfType<InteractiveItem>(); for (int i = 0; i < items.Length; i++) { if (items[i].endingNumber == endingNumber + 1) { items[i].isReady = true; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UIHandler : MonoBehaviour { public Text messageText; public Text mainText; public Text endingText; [Range(.05f, .5f)] public float scrollSpeed; [Range(1,3)] public float messageLife; public Button choiceAbtn; public Button choiceBbtn; private GameManager gameManager; public CanvasGroup buttons; public bool currentChoice; public void Start() { StartCoroutine("PermanentMessage", "Hello, this is your inner narrator. You are going to die today. You are going to die every day, for the rest of time. You may want to try eating something."); gameManager = FindObjectOfType<GameManager>(); } public void UpdatePermanentMessage() { StopCoroutine("PermanentMessage"); switch (gameManager.stage) { case 1: StartCoroutine("PermanentMessage", "You should check your computer. Might find something important."); break; case 2: StartCoroutine("PermanentMessage", "There's a mess in the house. Maybe your roommate could do something about it."); break; case 3: StartCoroutine("PermanentMessage", "You smell quite badly. Do you want to go to work smelling badly?"); break; case 4: StartCoroutine("PermanentMessage", "If you go to work naked, they may fire you."); break; case 5: StartCoroutine("PermanentMessage", "Time to go. Better hope you did everything right."); break; } } public void SetMessageText(string message) { StopCoroutine("DisplayMessage"); messageText.text = ""; StartCoroutine("DisplayMessage", message); } IEnumerator DisplayMessage (string message) { string renderedString = ""; for (int i = 0; i < message.Length; i++) { messageText.text += message[i]; yield return new WaitForSeconds(scrollSpeed); } yield return new WaitForSeconds(messageLife); messageText.text = ""; } IEnumerator PermanentMessage(string message) { mainText.text = ""; string renderedString = ""; for (int i = 0; i < message.Length; i++) { mainText.text += message[i]; yield return new WaitForSeconds(scrollSpeed); } } IEnumerator PrintEndMessage(string message) { string renderedString = ""; for (int i = 0; i < message.Length; i++) { endingText.text += message[i]; yield return new WaitForSeconds(scrollSpeed); } } public void ButtonClick (bool choiceA) { InteractiveItem[] items = FindObjectsOfType<InteractiveItem>(); gameManager.choosing = false; Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; buttons.alpha = 0; for (int i = 0; i < items.Length; i++) { if (gameManager.stage + 1 == items[i].endingNumber) { Debug.Log(items[i].endingNumber); InteractiveItem item = items[i]; if (item.choiceACorrect != choiceA && gameManager.endingNumber == 0) { gameManager.endingNumber = item.endingNumber; } item.hasSelected = true; } if (gameManager.stage + 2 == items[i].endingNumber) { InteractiveItem item = items[i]; item.isReady = true; } } gameManager.StageUp(); UpdatePermanentMessage(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class InteractClick : MonoBehaviour { private GameManager gameManager; private AudioSource audio; private void Start() { gameManager = FindObjectOfType<GameManager>(); audio = GetComponent<AudioSource>(); } // Update is called once per frame void Update() { if (Input.GetMouseButtonDown(0) && !gameManager.choosing) { Ray ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0)); RaycastHit hit; if (Physics.Raycast(ray, out hit, 100)) { if (hit.collider.GetComponentInParent<InteractiveItem>() != null) { UIHandler uiHandler = FindObjectOfType<UIHandler>(); InteractiveItem item = hit.collider.GetComponentInParent<InteractiveItem>(); if (item.isReady && !item.hasSelected) { gameManager.choosing = true; uiHandler.buttons.alpha = 1; uiHandler.choiceAbtn.GetComponentInChildren<Text>().text = item.choiceA; uiHandler.choiceBbtn.GetComponentInChildren<Text>().text = item.choiceB; uiHandler.SetMessageText(item.choiceText); audio.clip = item.clip; audio.Play(); if (item.noButtons) { uiHandler.choiceAbtn.gameObject.SetActive(false); uiHandler.choiceBbtn.gameObject.SetActive(false); } Cursor.lockState = CursorLockMode.None; Cursor.visible = true; if (gameManager.stage == 5 && item.endingNumber == 6) { gameManager.EndGame(); } } } } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class MessageBox : MonoBehaviour { [SerializeField] [Header("Message to be displayed")] private string m_Message; public string getMessage () { return m_Message; } public void setMessage (string message) { m_Message = message; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GameManager : MonoBehaviour { public int stage; public int endingNumber; private UIHandler uIHandler; public bool choosing; // Start is called before the first frame update void Start() { stage = 0; endingNumber = 0; uIHandler = FindObjectOfType<UIHandler>(); } // Update is called once per frame void Update() { } public void StageUp() { stage++; } public void EndGame() { if (endingNumber == 0) { endingNumber = 6; } string endMessage = ""; switch (endingNumber) { case 1: endMessage = "Skipping breakfast gave you a bad case of the hungries. You thought you could make it to lunch, but the smell wafting over to you from the taqueria next to your office is irresistable. You pop in for a breakfast burrito and wolf it down in fewer bites than you should tell any potential partner. Suddenly you're overcome with the worst pain you've ever experienced. The last thing you hear before you fade out is the doctor's excited murmuring about a new strain of \"Flash Food Poisoning\"."; break; case 2: endMessage = "A coworker you rarely speak to has sent you an email. She wants to meet for coffee at a local cafe you've never heard of. When you arrive, the cafe seems abandonded. As you enter, you realize it is abandoned. You see a makeshift medical station setup in what used to be the kitchen. You turn to leave, but you feel a small sting in your neck. The world goes black."; break; case 3: endMessage = "Your roommate reads the note and becomes irate. It's the third time this week you've left him a note to clean a mess that you made. He packs up his room and leaves in a huff, 'forgetting' to close the front door behind him. At work, you hear a report of a bear being spotted in your neighborhood. You should be careful on your way home. When you get home, you find your door ajar. Your pesky roommate must have left it open. You sit down for a beer on your new sofa, when you hear a growling coming from beneath you. You look down to realize you do not, in fact, have a new sofa. The bear mauls you, but in a final gesture of true composure, you manage to die without spilling your beer."; break; case 4: endMessage = "A nice hot shower leaves you feeling fresh and confident. As you're crossing the street, an attractive woman waves at you. You give her a smile and a wink as you're struck down by the bus she was trying to warn you about."; break; case 5: endMessage = "You put on your flashy new Unity hoody that you bought from the Unity store. On your way back to the office from lunch, you run into a gang of skinheads covered in Unreal Engine tattoos. They see your Unity hoody and jump you, leaving you to bleed out on the pavement. "; break; case 6: endMessage = "You manage to slog through your day with a sneaking suspicion that something is terribly wrong. In spite of this, you seem to make it home in one piece. Maybe tomorrow will be better."; break; } uIHandler.StartCoroutine("PrintEndMessage",endMessage); Invoke("ReloadScene", 60); } public void ReloadScene() { SceneManager.LoadScene(0); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class CharacterController : MonoBehaviour { [SerializeField] [Header("Regular walking speed for player")] private float speed = 3; [SerializeField] [Header("Sensitivity of player look")] private float lookSpeed = .5f; private Camera camera; private Rigidbody rigidbody; private Vector2 cameraRotation = new Vector2(0,0); private Vector3 lastPosition; // Start is called before the first frame update void Start() { camera = GetComponentInChildren<Camera>(); rigidbody = GetComponent<Rigidbody>(); Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } // Update is called once per frame void Update() { lastPosition = transform.position; bool isRunning = Input.GetKey(KeyCode.LeftShift); if (isRunning) { speed = 700; } else { speed = 400; } if (Input.GetAxisRaw("Horizontal") <= -0.5f) { rigidbody.velocity = speed * Time.deltaTime * -transform.right; } else if (Input.GetAxisRaw("Horizontal") >= 0.5f) { rigidbody.velocity = speed * Time.deltaTime * transform.right; } if (Input.GetAxisRaw("Vertical") <= -0.5f) { rigidbody.velocity = speed * Time.deltaTime * -transform.forward; } else if (Input.GetAxisRaw("Vertical") >= 0.5f) { rigidbody.velocity = speed * Time.deltaTime * transform.forward; } if (Input.GetAxisRaw("Horizontal") < 0.5f && Input.GetAxisRaw("Horizontal") > -.05f && Input.GetAxisRaw("Vertical") < 0.5f && Input.GetAxisRaw("Vertical") > -.05f) { rigidbody.velocity = Vector3.zero; } cameraRotation.y += Input.GetAxis("Mouse X"); cameraRotation.x += -Input.GetAxis("Mouse Y"); cameraRotation.x = Mathf.Clamp(cameraRotation.x, -90, 90); camera.transform.localRotation = Quaternion.Euler(cameraRotation.x, 0, 0); transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X"), 0); } }
9fa7fedf4afec486c37780f330a05b21a48417b6
[ "Markdown", "C#" ]
7
Markdown
geraldfingburke/you-are-going-to-die-today
a231ec3d1b62c5bccc7dc5c0676400ea15ee3605
43e0b0aae9bad7571c89dfcb50f073fae66923b2
refs/heads/master
<repo_name>dongxy1014/Quantitative-Asset-Management<file_sep>/PS3_205259521.R library(data.table) library(lubridate) library(dplyr) library(fBasics) library(foreign) ###### QUESTION 1 CRSP_Stocks = as.data.table(read.table("C:/Users/seayo/Desktop/QAM/PS2/CRSP_Stocks.csv", sep=",",header = TRUE)) PS3_Q1 = function(crsp){ #Select SHRCD = (10,11), EXCHCD = (1,2,3) crsp = crsp[SHRCD %in% c(10,11)] crsp = crsp[EXCHCD %in% c(1,2,3)] # Convert format crsp[, RET := as.numeric(levels(RET))[RET]] crsp[, DLRET := as.numeric(levels(DLRET))[DLRET]] crsp[, date := as.Date(as.character(date),format="%Y%m%d")] all_month = sort(unique(crsp$date)) # Create Year and Month crsp[, Year := year(date)] crsp[, Month := month(date)] # Raw data price has negative value crsp[, PRC := abs(PRC)] crsp[, CAP := PRC * SHROUT/1000] crsp[, lag_Mkt_Cap := shift(CAP), by = PERMNO] # Deal with RET and DLRET # As CRSP calculate the return as P(t+1)/P(t) - 1, but the paper use cummulative log return, # we convert the return into log return setkey(crsp, date) crsp <- crsp[!is.na(RET) | !is.na(DLRET), ] crsp <- crsp[is.na(RET), Ret := DLRET] crsp <- crsp[is.na(DLRET), Ret := RET] crsp <- crsp[!is.na(RET) & !is.na(DLRET), Ret := (1+RET) * (1+DLRET)-1] crsp = crsp[,logret := log(Ret+1)] crsp[, Ranking_Ret := shift(logret, n=12)+shift(logret, n=11)+shift(logret, n=10)+ shift(logret, n=9)+shift(logret, n=8)+shift(logret, n=7)+shift(logret, n=6)+ shift(logret, n=5)+shift(logret, n=4)+shift(logret, n=3)+shift(logret, n=2), by = PERMNO] # for current month return, we convert the log return back to arithmetic return crsp = na.omit(crsp, cols=c("lag_Mkt_Cap", "Ranking_Ret", "Ret")) crsp = crsp[, c("date", "Year", "Month", "PERMNO", "EXCHCD", "lag_Mkt_Cap", "Ret", "Ranking_Ret")] return(crsp) } # For the output, I kept columm date for the convinience of the following code CRSP_Stocks_Momentum = PS3_Q1(crsp = CRSP_Stocks) ###### QUESTION 2 PS3_Q2 = function(mom){ months = sort(unique(mom$date)) for (m in 1:1104){ mom[date==months[m],DM_decile :=cut(mom[date==months[m],]$Ranking_Ret, breaks=quantile(mom[date==months[m],]$Ranking_Ret,probs=c(0:10)/10,na.rm=TRUE), include.lowest=TRUE, labels=FALSE)] # Using Kenneth R. French method, we only use NYSE to do the sorting. if we still use quantile() function # it gives 11 values from 0%, 10%, ..., to 100%. Using cut() function with the quantiles as break will # lead to a problem, that is for a stock not listed in NYSE, its Ranking_Ret may not be in the range (0%, 10%) # and (90%, 100%), it may be lower than 0% or higher than 100%. To make it sure such values can be sorted into # the correct range, we do the following: mom[date==months[m],KRF_decile :=cut(mom[date==months[m],]$Ranking_Ret, breaks=c(-Inf, quantile(mom[date==months[m] & EXCHCD==1,]$Ranking_Ret, probs=c(0:10)/10,na.rm=TRUE)[2:10],Inf), include.lowest=TRUE, labels=FALSE)] } mom = mom[,-c("EXCHCD", "Ranking_Ret")] return(mom) } CRSP_Stocks_Momentum_decile = PS3_Q2(mom = CRSP_Stocks_Momentum) ###### QUESTION 3 FF_mkt = na.omit(as.data.table(read.table("C:/Users/seayo/Desktop/QAM/PS1/F-F_Research_Data_Factors.csv", skip = 3, sep=",",header = TRUE))) colnames(FF_mkt) = c("date", "Market_minus_Rf", "SMB","HML","Rf") FF_mkt[, date:= as.numeric(levels(date))[date]] FF_mkt[, Year:= date%/%100] FF_mkt[, Month:= date - Year*100] FF_mkt = FF_mkt[,c(6,7,2,3,4,5)] FF_mkt = FF_mkt[which(FF_mkt$Year==1927 & FF_mkt$Month ==1):length(FF_mkt$Year),] PS3_Q3 = function(decile,ff){ Rf = vector(mode = "numeric", length=11040) for (i in 1:1104){ Rf[10*i-9] = ff$Rf[i]/100 Rf[10*i-8] = ff$Rf[i]/100 Rf[10*i-7] = ff$Rf[i]/100 Rf[10*i-6] = ff$Rf[i]/100 Rf[10*i-5] = ff$Rf[i]/100 Rf[10*i-4] = ff$Rf[i]/100 Rf[10*i-3] = ff$Rf[i]/100 Rf[10*i-2] = ff$Rf[i]/100 Rf[10*i-1] = ff$Rf[i]/100 Rf[10*i] = ff$Rf[i]/100 } decile[, DM_VW := lag_Mkt_Cap / sum(lag_Mkt_Cap), by = list(date, DM_decile)] decile[, KRF_VW := lag_Mkt_Cap / sum(lag_Mkt_Cap), by = list(date, KRF_decile)] DM = decile[, .(DM_Ret = sum(DM_VW*Ret, na.rm=T)), by = list(date, DM_decile)] DM = DM[order(date,DM_decile)] KRF = decile[, .(KRF_Ret = sum(KRF_VW*Ret, na.rm=T)), by = list(date, KRF_decile)] KRF = KRF[order(date,KRF_decile)] colnames(KRF)[2] = "decile" colnames(DM)[2] = "decile" output = as.data.table(full_join(DM, KRF , by = c("date","decile"))) output[, Year := year(date)] output[, Month := month(date)] output = output[,c("date","Year","Month","decile","DM_Ret", "KRF_Ret")] output = cbind(output, Rf) } CRSP_Stocks_Momentum_returns = PS3_Q3(decile = CRSP_Stocks_Momentum_decile, ff = FF_mkt) ###### QUESTION 4 # Select the data from 1927.01 to 2013.03 start = which(CRSP_Stocks_Momentum_returns$Year==1927 & CRSP_Stocks_Momentum_returns$Month==1 & CRSP_Stocks_Momentum_returns$decile==1) end = which(CRSP_Stocks_Momentum_returns$Year==2013 & CRSP_Stocks_Momentum_returns$Month==3 & CRSP_Stocks_Momentum_returns$decile==10) CRSP_Stocks_Momentum_returns_2013 = CRSP_Stocks_Momentum_returns[start:end,] PS3_Q4 = function(dec_mm){ output = matrix(0,nrow = 4, ncol = 11) row.names(output) = c("mean excess return", "SD", "SR","Skewness") colnames(output) = c("Decile 1", "Decile 2", "Decile 3", "Decile 4", "Decile 5", "Decile 6", "Decile 7", "Decile 8", "Decile 9", "Decile 10", "WML") for (d in 1:10){ output[1,d] = round(mean(dec_mm[decile==d, ]$DM_Ret - dec_mm[decile==d, ]$Rf)*12,4) output[2,d] = round(sqrt(12)*sd(dec_mm[decile==d, ]$DM_Ret - dec_mm[decile==d, ]$Rf),4) output[3,d] = round(output[1,d]/output[2,d],4) output[4,d] = round(skewness(log(dec_mm[decile==d, ]$DM_Ret+1)),4) } output[1,11] = round(mean(dec_mm[decile==10, ]$DM_Ret - dec_mm[decile==1, ]$DM_Ret)*12,4) output[2,11] = round(sqrt(12)*sd(dec_mm[decile==10, ]$DM_Ret - dec_mm[decile==1, ]$DM_Ret),4) output[3,11] = round(output[1,d]/output[2,d],4) output[4,11] = round(skewness(log(dec_mm[decile==10, ]$DM_Ret - dec_mm[decile==1, ]$DM_Ret +1 + dec_mm[decile==10, ]$Rf)),4) return(output) } Q4_result = PS3_Q4(CRSP_Stocks_Momentum_returns_2013) ###### QUESTION 5 KRF_returns = na.omit(as.data.table(read.table("C:/Users/seayo/Desktop/QAM/PS3/10_Portfolios_Prior_12_2.csv", sep=",",header = TRUE))) colnames(KRF_returns)[1] = "date" KRF_returns[, Year:= date%/%100] KRF_returns[, Month:= date - Year*100] KRF_returns[,2:11] =KRF_returns[,2:11]/100 KRF_returns = KRF_returns[,c(12,13,2,3,4,5,6,7,8,9,10,11)] KRF_returns = KRF_returns[1:1104,] DM_returns = read.table("C:/Users/seayo/Desktop/QAM/PS3/m_m_pt_tot.txt",header=FALSE, sep = "", dec=".")[,c(1,2,3)] library(reshape2) DM_returns = as.data.table(dcast(DM_returns, V1 ~V2, value.var='V3' )) DM_returns$V1 = as.Date(as.character(DM_returns$V1),format="%Y%m%d") DM_returns[, Year:= year(V1)] DM_returns[, Month:= month(V1)] DM_returns = DM_returns[,c(12,13,2,3,4,5,6,7,8,9,10,11)] PS3_Q5 = function(dec_mm, dm, krf){ # DM from 1927.01 - 2016.12 # KRF from 1927.01 - 2018.12 start = which(dec_mm$Year==1927 & dec_mm$Month==1 & dec_mm$decile==1) end = which(dec_mm$Year==2016 & dec_mm$Month==12 & dec_mm$decile==10) dec_mm_2016 = dec_mm[start:end,] output = matrix(0,nrow = 2, ncol = 11) row.names(output) = c("DM correlation", "KRF correlation") colnames(output) = c("Decile 1", "Decile 2", "Decile 3", "Decile 4", "Decile 5", "Decile 6", "Decile 7", "Decile 8", "Decile 9", "Decile 10", "WML") dm = as.matrix(dm[,3:12]) krf = as.matrix(krf[,3:12]) for (d in 1:10){ output[1,d] = cor(dec_mm_2016[decile==d, ]$DM_Ret, dm[,d]) output[2,d] = cor(dec_mm[decile==d, ]$KRF_Ret, krf[,d]) } output[1,11] = cor((dec_mm_2016[decile==10, ]$DM_Ret - dec_mm_2016[decile==1, ]$DM_Ret), (dm[,10] - dm[,1])) output[2,11] = cor((dec_mm[decile==10, ]$KRF_Ret - dec_mm[decile==1, ]$KRF_Ret), (krf[,10] - krf[,1])) output = round(output,4) return(output) } Q5_result = PS3_Q5(dec_mm=CRSP_Stocks_Momentum_returns, dm=DM_returns, krf=KRF_returns) ###### QUESTION 6 # Let's view the momentum portfilio monthly returns from 2000 to now start = which(CRSP_Stocks_Momentum_returns$Year==2000 & CRSP_Stocks_Momentum_returns$Month==1 & CRSP_Stocks_Momentum_returns$decile==1) end = which(CRSP_Stocks_Momentum_returns$Year==2018 & CRSP_Stocks_Momentum_returns$Month==12 & CRSP_Stocks_Momentum_returns$decile==10) dec_mm_recent = CRSP_Stocks_Momentum_returns[start:end,] time = sort(unique(dec_mm_recent$date)) recent = PS3_Q4(dec_mm_recent) library(ggplot2) dec_mm_recent$decile = factor(dec_mm_recent$decile) dm = ggplot(dec_mm_recent, aes(x= date, y=DM_Ret, fill = decile))+geom_area() dm krf = ggplot(dec_mm_recent, aes(x= date, y=KRF_Ret, fill = decile))+geom_area() krf DM_WML = dec_mm_recent[decile=='10',]$DM_Ret - dec_mm_recent[decile=='1',]$DM_Ret KRF_WML = dec_mm_recent[decile=='10',]$KRF_Ret - dec_mm_recent[decile=='1',]$KRF_Ret DM_WML = log(DM_WML+1) KRF_WML = log(KRF_WML+1) WML = data.frame(time, cumsum(DM_WML), cumsum(KRF_WML)) dm_wml = ggplot()+geom_line(aes(x= WML$time, y=WML$cumsum.DM_WML.), colour='blue') dm_wml krf_wml = ggplot()+geom_line(aes(x= WML$time, y=WML$cumsum.KRF_WML.), colour='blue') krf_wml<file_sep>/PS2_205259521.R library(data.table) library(lubridate) library(dplyr) library(fBasics) setwd("C:/Users/seayo/Desktop/QAM/PS2") ###### QUESTION 1 CRSP_Bonds = as.data.table(read.table("CRSP_Bonds.csv", sep=",",header = TRUE)) PS2_Q1 = function(crsp){ # Convert format crsp[, KYCRSPID := as.character(levels(KYCRSPID))[KYCRSPID]] crsp[, MCALDT := as.character(levels(MCALDT))[MCALDT]] crsp[, MCALDT := as.Date(MCALDT,"%m/%d/%Y")] crsp[, lag_CAP := shift(TMTOTOUT), by = KYCRSPID] crsp = crsp[complete.cases(lag_CAP),] # Deal with RET with -99 crsp = crsp[-which(TMRETNUA==-99),] crsp[, VW := lag_CAP /sum(lag_CAP), by = MCALDT] setkey(crsp, MCALDT) # EWRET EWRET <- crsp[, .(Bond_Ew_Ret = round(mean(TMRETNUA),4)), by = MCALDT] # VWRET VWRET <- crsp[, .(Bond_Vw_Ret = round(sum(VW*TMRETNUA),4)), by = MCALDT] # Lagged Marekt Cap lag_CAP <- crsp[, .(Bond_lag_MV = round(sum(lag_CAP), 4)), by = MCALDT] # Add Year and Month lag_CAP[, Year:= year(MCALDT)] lag_CAP[, Month:= month(MCALDT)] output = full_join(lag_CAP, EWRET, by = "MCALDT") output = full_join(output, VWRET , by = "MCALDT") # If lagged market cap is not available, so is VWRET output = output[, c(3,4,2,5,6)] output$Bond_lag_MV[which(output$Bond_lag_MV==0)] = NA output = na.omit(output) return(output) } Monthly_CRSP_Bonds = PS2_Q1(crsp = CRSP_Bonds[,-1]) ###### QUESTION 2 CRSP_Stocks = as.data.table(read.table("CRSP_Stocks.csv", sep=",",header = TRUE)) PS1_Q1 = function(crsp){ # Convert format crsp[, RET := as.numeric(levels(RET))[RET]] crsp[, DLRET := as.numeric(levels(DLRET))[DLRET]] crsp[, date := as.Date(as.character(date),format="%Y%m%d")] # Raw data price has negative value crsp[, PRC := abs(PRC)] crsp[, CAP := PRC * SHROUT] crsp[, lag_CAP := shift(CAP), by = PERMNO] #Select SHRCD = (10,11), EXCHCD = (1,2,3) crsp = crsp[SHRCD %in% c(10,11)] crsp = crsp[EXCHCD %in% c(1,2,3)] crsp = na.omit(crsp, cols="lag_CAP") # Deal with RET and DLRET crsp <- crsp[!is.na(RET) | !is.na(DLRET), ] crsp <- crsp[is.na(RET), RETURN := DLRET] crsp <- crsp[is.na(DLRET), RETURN := RET] crsp <- crsp[!is.na(RET) & !is.na(DLRET), RETURN := (1+RET) * (1+DLRET) - 1] crsp <- crsp[, -c("SHRCD", "EXCHCD", "DLRET", "PRC", "SHROUT", "RET", "CAP")] setkey(crsp, date) crsp[, VW := lag_CAP / sum(lag_CAP), by = date] # EWRET EWRET <- crsp[, .(Stock_Ew_Ret = round(mean(RETURN, na.rm = T),4)), by = date] # VWRET VWRET <- crsp[, .(Stock_Vw_Ret = round(sum(VW*RETURN, na.rm=T),4)), by = date] # Lagged Marekt Value lag_CAP <- crsp[, .(Stock_lag_MV = round(sum(lag_CAP)/1000, 4)), by = date] # Add Year and Month lag_CAP[, Year:= year(date)] lag_CAP[, Month:= month(date)] output = full_join(lag_CAP, EWRET, by = "date") output = full_join(output, VWRET , by = "date") output = output[, c(3,4,2,5,6)] return(output) } Monthly_CRSP_Stocks = PS1_Q1(CRSP_Stocks) # Risk free rate from CRSP Monthly_CRSP_Riskless = as.data.table(read.table("CRSP_riskfree.csv", sep=",",header = TRUE)) Monthly_CRSP_Riskless[, caldt := as.Date(as.character(caldt),format="%Y%m%d")] ### PS2_Q2 = function(stock, bond, riskless){ Year = stock$Year Month = stock$Month Stock_lag_MV = stock$Stock_lag_MV Stock_Excess_Vw_Ret = stock$Stock_Vw_Ret - riskless$t30ret Bond_lag_MV = bond$Bond_lag_MV Bond_Excess_Vw_Ret = bond$Bond_Vw_Ret - riskless$t30ret output = as.data.table(data.frame(Year, Month, Stock_lag_MV, Stock_Excess_Vw_Ret, Bond_lag_MV, Bond_Excess_Vw_Ret)) return(output) } Monthly_CRSP_Universe = PS2_Q2(Monthly_CRSP_Stocks, Monthly_CRSP_Bonds, Monthly_CRSP_Riskless) ###### QUESTION 3 PS2_Q3 = function(universe){ universe[,index := seq(1,1116,1)] universe[, Excess_60_40_Ret := 0.6*Stock_Excess_Vw_Ret+0.4*Bond_Excess_Vw_Ret, by=index] universe[, Excess_Vw_Ret := Stock_lag_MV/(Stock_lag_MV + Bond_lag_MV)*Stock_Excess_Vw_Ret +Bond_lag_MV/(Stock_lag_MV + Bond_lag_MV)*Bond_Excess_Vw_Ret, by=index] Stock_inverse_sigma_hat = vector(mode="numeric", length=1116) Bond_inverse_sigma_hat = vector(mode="numeric", length=1116) Unlevered_k = vector(mode="numeric", length=1116) # Rolling-window sigma for (i in 1:1116){ if(i<=36){ Stock_inverse_sigma_hat[i] = NA Bond_inverse_sigma_hat[i] = NA Unlevered_k[i] =NA } else{ Stock_inverse_sigma_hat[i] = 1/sd(universe$Stock_Excess_Vw_Ret[(i-36):(i-1)], na.rm = T) Bond_inverse_sigma_hat[i] = 1/sd(universe$Bond_Excess_Vw_Ret[(i-36):(i-1)], na.rm = T) Unlevered_k[i] = 1/sum(Stock_inverse_sigma_hat[i]+Bond_inverse_sigma_hat[i]) } } universe[, Stock_inverse_sigma_hat:= Stock_inverse_sigma_hat] universe[, Bond_inverse_sigma_hat:= Bond_inverse_sigma_hat] universe[, Unlevered_k:= Unlevered_k] universe[, Excess_Unlevered_RP_Ret:= Stock_inverse_sigma_hat*Unlevered_k*Stock_Excess_Vw_Ret + Bond_inverse_sigma_hat*Unlevered_k*Bond_Excess_Vw_Ret, by = index] universe[, Levered_k := sd(Excess_Vw_Ret[-36])/sd(Stock_inverse_sigma_hat*Stock_Excess_Vw_Ret + Bond_inverse_sigma_hat*Bond_Excess_Vw_Ret , na.rm=T)] universe[, Excess_Levered_RP_Ret:= Stock_inverse_sigma_hat*Levered_k*Stock_Excess_Vw_Ret + Bond_inverse_sigma_hat*Levered_k*Bond_Excess_Vw_Ret, by = index] universe = universe[,c(1,2,4,6,8,9,10,11,12,13,14,15)] } Port_Rets = PS2_Q3(universe = Monthly_CRSP_Universe) PS2_Q4 = function(port){ # Select from 1930.01 to 2010.06 port = port[49:1014,] output = matrix(0,6,6) colnames(output) = c("Annualized Mean", "t-stat of Annualized Mean", "Annualized Standard Deviation", "Annualized Sharpe Ratio", "Skewness", "Excess Kurtosis") row.names(output) = c("CRSP stocks", "CRSP bonds", "Value-weighted portfolio", "60/40 portfolio", "unlevered RP", "levered RP") output[1,1] = mean(port$Stock_Excess_Vw_Ret)*12 output[2,1] = mean(port$Bond_Excess_Vw_Ret)*12 output[3,1] = mean(port$Excess_Vw_Ret)*12 output[4,1] = mean(port$Excess_60_40_Ret)*12 output[5,1] = mean(port$Excess_Unlevered_RP_Ret)*12 output[6,1] = mean(port$Excess_Levered_RP_Ret)*12 length = dim(port)[1] output[1,2] = mean(port$Stock_Excess_Vw_Ret)*12 / sd(port$Stock_Excess_Vw_Ret*12)*sqrt(length-1) output[2,2] = mean(port$Bond_Excess_Vw_Ret)*12 /sd(port$Bond_Excess_Vw_Ret*12)*sqrt(length-1) output[3,2] = mean(port$Excess_Vw_Ret)*12 / sd(port$Excess_Vw_Ret*12)*sqrt(length-1) output[4,2] = mean(port$Excess_60_40_Ret)*12 / sd(port$Excess_60_40_Ret*12)*sqrt(length-1) output[5,2] = mean(port$Excess_Unlevered_RP_Ret)*12 /sd(port$Excess_Unlevered_RP_Ret*12)*sqrt(length-1) output[6,2] = mean(port$Excess_Levered_RP_Ret)*12 / sd(port$Excess_Levered_RP_Ret*12)*sqrt(length-1) output[1,3] = sd(port$Stock_Excess_Vw_Ret)*sqrt(12) output[2,3] = sd(port$Bond_Excess_Vw_Ret)*sqrt(12) output[3,3] = sd(port$Excess_Vw_Ret)*sqrt(12) output[4,3] = sd(port$Excess_60_40_Ret)*sqrt(12) output[5,3] = sd(port$Excess_Unlevered_RP_Ret)*sqrt(12) output[6,3] = sd(port$Excess_Levered_RP_Ret)*sqrt(12) output[1,4] = output[1,1] / output[1,3] output[2,4] = output[2,1] / output[2,3] output[3,4] = output[3,1] / output[3,3] output[4,4] = output[4,1] / output[4,3] output[5,4] = output[5,1] / output[5,3] output[6,4] = output[6,1] / output[6,3] output[1,5] = skewness(port$Stock_Excess_Vw_Ret*12) output[2,5] = skewness(port$Bond_Excess_Vw_Ret*12) output[3,5] = skewness(port$Excess_Vw_Ret*12) output[4,5] = skewness(port$Excess_60_40_Ret*12) output[5,5] = skewness(port$Excess_Unlevered_RP_Ret*12) output[6,5] = skewness(port$Excess_Levered_RP_Ret*12) output[1,6] = kurtosis(port$Stock_Excess_Vw_Ret*12) output[2,6] = kurtosis(port$Bond_Excess_Vw_Ret*12) output[3,6] = kurtosis(port$Excess_Vw_Ret*12) output[4,6] = kurtosis(port$Excess_60_40_Ret*12) output[5,6] = kurtosis(port$Excess_Unlevered_RP_Ret*12) output[6,6] = kurtosis(port$Excess_Levered_RP_Ret*12) return(output) } output = PS2_Q4(Port_Rets) print(output) write.table(Port_Rets,file="test.csv",sep=",") <file_sep>/PS4_205259521.R library(tidyverse) library(dplyr) require(data.table) library(lubridate) library(fBasics) library(zoo) #------------------------------------------ Question 1 ---------------------------------------# setwd("C:/Users/seayo/Desktop/QAM/PS4") data.prba = as.data.table(read.csv("prba.csv")) data.comp = as.data.table(read.csv("compustat.csv")) data.crsp = as.data.table(read.csv("crsp.csv")) data.link = as.data.table(read.csv("linktable.csv")) ########################## Clean Compustat ########################## data.comp = data.comp[curcd=="USD"] data.comp = data.comp[indfmt=="INDL"] data.comp = merge(data.comp,data.prba,by=c("gvkey","datadate"),all.x=T) data.comp[, datadate:= as.Date(as.character(datadate),"%Y%m%d")] data.comp[, Month:= month(datadate)] data.comp[,Year:= year(datadate)] data.comp = data.comp[,-c(4:8)] data.comp[,BE:= coalesce(seq, ceq + pstk, at - lt -mib, at - lt) + coalesce(txditc, txdb + itcb, 0) - coalesce(pstkrv, pstkl, pstk, 0) - coalesce(prba, 0) ] data.comp = data.comp[,.(gvkey, datadate, fyear, Month, Year, BE)] ########################## Clean CRSP ########################## data.crsp = data.crsp[SHRCD %in% c(10,11)] data.crsp = data.crsp[EXCHCD %in% c(1,2,3)] data.crsp[, RET := as.numeric(levels(RET))[RET]] data.crsp[, DLRET := as.numeric(levels(DLRET))[DLRET]] data.crsp[, date := as.Date(as.character(date),format="%Y%m%d")] data.crsp[, Year := year(date)] data.crsp[, Month := month(date)] data.crsp[, PRC := abs(PRC)] data.crsp[, CAP := PRC * SHROUT/1000] data.crsp[, lag_Mkt_Cap := shift(CAP), by = PERMNO] data.crsp <- data.crsp[!is.na(RET) | !is.na(DLRET), ] data.crsp <- data.crsp[is.na(RET), Ret := DLRET] data.crsp <- data.crsp[is.na(DLRET), Ret := RET] data.crsp <- data.crsp[!is.na(RET) & !is.na(DLRET), Ret := (1+RET) * (1+DLRET)-1] ########################## Merge Linktable and Compustat data ########################## #### code from TA session merged <- merge(data.crsp, data.link, by.x='PERMCO', by.y = 'LPERMCO', allow.cartesian = T) setkey(merged) merged[,LINKDT := as.Date(as.character(LINKDT),"%Y%m%d")] merged[LINKENDDT == 'E', LINKENDDT := NA] merged[,LINKENDDT := as.Date(as.character(LINKENDDT),"%Y%m%d")] merged = merged[(is.na(LINKDT) | date >= LINKDT) & (is.na(LINKENDDT) | date <= LINKENDDT)] setorder(merged, gvkey, date) # Multiple GVKEYs per PERMCO ### First, if LC not LC linktype, only keep LC # identify Same PERMCO but different PERMNO merged[, prob := .N > 1, by = .(PERMCO, date)] merged[, Good_match := sum(LINKTYPE == 'LC'), by =.(PERMCO, date)] merged = merged[!(prob == T & Good_match == T & LINKTYPE != 'LC')] ### Second, if P and not P linkprim, only keep p merged[, prob := .N > 1, by= .(PERMCO, date)] merged[, Good_match := sum(LINKPRIM == 'P'), by =.(PERMCO, date)] merged <- merged[!(prob == T & Good_match == T & LINKPRIM != 'P')] ### Third, if 1 and not liid, only keep 1 merged[, prob := .N > 1, by = .(PERMCO, date)] merged[, Good_match := sum(LIID == 1), by =.(PERMCO,date)] merged = merged[!(prob == T & Good_match == T & LIID != 1)] ### Fourth, use the link that's current merged[, prob := .N > 1, by = .(PERMCO, date)] merged[, Good_match := sum(is.na(LINKENDDT)), by = .(PERMCO, date)] merged = merged[!(prob==T & Good_match == T & !is.na(LINKENDDT))] ### Fifth, use the link that's been around the longest merged[, prob := .N > 1, by = .(PERMCO, date)] merged[, Good_match := NULL] merged[is.na(LINKENDDT), LINKENDDT := as.Date('2019-12-31', '%Y-%m-%d')] merged[, Date_diff := as.integer(LINKENDDT - LINKDT)] setorder(merged, PERMCO, date, Date_diff) merged[prob == T, Good_match := Date_diff == Date_diff[.N], by = .(PERMCO, date)] merged = merged[!(prob==T & Good_match != T)] ### Sixth, use the gvkey that has been around the longest merged[, prob := .N > 1, by = .(PERMCO, date)] merged[, Good_match :=NULL] setorder(merged, gvkey, LINKDT) merged[prob == T, start_Date := LINKDT[1], by = .(gvkey)] setorder(merged, gvkey, LINKENDDT) merged[prob == T, end_Date := LINKENDDT[.N], by = .(gvkey)] merged[, Date_diff := as.integer(end_Date - start_Date)] setorder(merged, PERMCO, date, Date_diff) merged[prob == T, Good_match := Date_diff == Date_diff[.N], by = .(PERMCO, date)] merged = merged[!(prob == T & Good_match != T)] ### Seventh, use the smaller gvkey setorder(merged, PERMCO, date, gvkey) merged = unique(merged, by = c('PERMCO', 'date')) ### Clean up extra variables and final check of match merged = merged[, .(gvkey, date, EXCHCD, CAP, PERMCO, PERMNO, Ret , Year, Month)] ################################ Merge CRSP and Compustat together ############################################### data = as.data.table(left_join(merged,data.comp,by =c("gvkey"="gvkey","Year"="fyear"))) data = data[, .(gvkey, date, PERMNO, PERMCO, EXCHCD, Ret, CAP, BE)] data = data[complete.cases(data)] data[, Year:= year(date)] data[, Month:= month(date)] setorder(data, Year, Month) ################################ Size Portfolio ############################################### # Sum up the market cap for companies with multiple securities data = data[, MktCap := sum(CAP,na.rm = T), .(PERMCO, date)] data.june <- data[Month == 6, .(PERMCO, Year, MktCap, EXCHCD)] years = sort(unique(data.june$Year)) for (y in 1:length(years)){ data.june[Year==years[y],size_decile :=cut(data.june[Year==years[y],]$MktCap, breaks=c(-Inf, quantile(data.june[Year==years[y] & EXCHCD==1,]$MktCap, probs=c(0:10)/10,na.rm=TRUE)[2:10],Inf), include.lowest=TRUE, labels=FALSE)] } data.june = data.june[,.(PERMCO, Year, size_decile)] setorder(data, Year, Month) setorder(data.june, Year) data.size = merge(data, data.june, by = c("PERMCO","Year"), all.x = T) data.size[,c("Size","Lagged_MktCap") := .(shift(size_decile, 6), shift(MktCap,1)), by=PERMNO] data.size = data.size[Lagged_MktCap != 0] data.size = data.size[!is.na(Size) & !is.na(Lagged_MktCap)] size_port = data.size[,.(Size_Ret = weighted.mean(Ret, Lagged_MktCap, na.rm = TRUE)), .(Year, Month, Size)] setkey(size_port, Year, Month, Size) ################################ BTM Portfolio ############################################### data.btm = data[Month == 12,] data.btm[,BtM := BE/MktCap] data.btm = data.btm[!is.na(BtM) & BtM>0] data.btm[,BtM_decile := findInterval(BtM, quantile(.SD[EXCHCD==1,BtM], seq(0.1,0.9,0.1)), left.open = T) + 1,by = .(Year, Month)] data.btm[,lagged_BtM_decile := shift(BtM_decile), by=PERMNO] setorder(data, Year, Month) setorder(data.btm, Year) # MERGE the BtM decile information back to crsp cleaned up data. data.btm = data.btm[, .(PERMNO,PERMCO, Year, BtM_decile, lagged_BtM_decile)] data.btm.decile = merge(data, data.btm, by = c("PERMNO","PERMCO","Year"), all.x = T) data.btm.decile[,c("BtM_Rank","lagged_MktCap") := .(shift(lagged_BtM_decile, 6), shift(MktCap, 1)), .(PERMNO)] data.btm.decile = data.btm.decile[!is.na(BtM_Rank) & !is.na(lagged_MktCap) & lagged_MktCap!=0.0] BtM_port = data.btm.decile[,.(BtM_Ret = weighted.mean(Ret, lagged_MktCap, na.rm = TRUE)), .(Year, Month, BtM_Rank)] setkey(BtM_port, Year, Month, BtM_Rank) #################################### Find the HML SMB #################################### data.size[,SMB:=ifelse(Size<=6,"S","B")] data.btm.decile[,HML:=ifelse(BtM_Rank<=3,"L",ifelse(BtM_Rank<=7,"M","H"))] BtM = data.btm.decile[,.(PERMNO, PERMCO, Year, Month, Ret, HML,lagged_MktCap)] size = data.size[,.(PERMNO, PERMCO, Year, Month, Ret, SMB,Lagged_MktCap)] setkey(BtM,PERMCO,PERMNO,Year,Month) setkey(size,PERMCO,PERMNO,Year,Month) SizeBtM = merge(BtM,size) SMB_HML = SizeBtM[,.(Ret = weighted.mean(Ret.x, lagged_MktCap, na.rm = T)),.(Year,Month, HML,SMB)] setkey(SMB_HML, Year,Month) setorder(SMB_HML, Year) SMB = SMB_HML[,.(SMB_Ret = (.SD[SMB=="S" & HML=="L",Ret] + .SD[SMB=="S" & HML=="M",Ret]+ .SD[SMB=="S" & HML=="H",Ret] - .SD[SMB=="B" & HML=="L",Ret] - .SD[SMB=="B" & HML=="M",Ret] - .SD[SMB=="B" & HML=="H",Ret])/3), by =.(Year, Month)] HML = SMB_HML[, .(HML_Ret =(.SD[SMB=="S" & HML=="H",Ret] + .SD[SMB=="B" & HML=="H",Ret] -.SD[SMB=="S" & HML=="L",Ret] - .SD[SMB=="B" & HML=="L",Ret])/2), by =.(Year, Month)] Q1_output = full_join(size_port, BtM_port, by=c("Year", "Month")) Q1_output<- merge(Q1_output,HML) Q1_output<- merge(Q1_output,SMB) colnames(Q1_output)[3] = "Size_Rank" write.table(Q1_output, file = "Q1_output.csv", row.names=FALSE, sep=",") #------------------------------------------ Question 2 ---------------------------------------# FF_Factors<- as.data.table(read.csv("F-F_Research_Data_Factors_.csv")) size_FF_portfolio<- as.data.table(read.csv("Portfolios_Formed_on_ME.csv")) FF_Factors[, Year:= X%/%100] FF_Factors[, Month:= X - Year*100] FF_Factors= FF_Factors[ X>=197307& X<=201812,] FF_Factors= FF_Factors[,.(Year, Month, SMB,HML,RF)] setorder(FF_Factors,Year,Month) size_FF_portfolio = size_FF_portfolio[X>=197307& X<=201812,] size_FF_portfolio = size_FF_portfolio[, c(1,11:20)] colnames(size_FF_portfolio) = c("date", 1:10) size_FF_portfolio = melt(size_FF_portfolio, id.vars = "date") size_FF_portfolio[, Year:= date%/%100] size_FF_portfolio[, Month:= date - Year*100] size_FF_portfolio = size_FF_portfolio[, .(Year, Month, Ret= value/100, Size_rank = variable)] FF_Factors = FF_Factors[, .(Year, Month, SMB = SMB/100, HML= HML/100, RF= RF/100)] FF_merged.size = merge(size_FF_portfolio, FF_Factors[, c(1,2,5)], by =c("Year","Month")) size_mat = matrix(nrow=5, ncol=11,dimnames = list(c("Excess Return","Standard Deviation", "Sharpe Ratio","Skewness","Correlation"), c(1:10,"LongShort"))) for(i in 1:10){ size_mat[1,i] = mean(size_port[Size==i,Size_Ret] - FF_merged.size[Size_rank==i,RF])*12 size_mat[2,i] = sd(size_port[Size==i,Size_Ret])*sqrt(12) size_mat[3,i] = size_mat[1,i]/size_mat[2,i] size_mat[4,i] = skewness(size_port[Size==i,Size_Ret]) size_mat[5,i] = cor(size_port[Size==i,Size_Ret], FF_merged.size[Size_rank==i,Ret]) } WML_series = size_port[Size==1,Size_Ret] - FF_merged.size[Size_rank==10,Ret] size_mat[1,11] <- mean(WML_series)*12 size_mat[2,11] <- sd(WML_series)*sqrt(12) size_mat[3,11] <- size_mat[1,11]/size_mat[2,11] size_mat[4,11] <- skewness(WML_series) size_mat[5,11] <- cor(WML_series, (FF_merged.size[Size_rank==1,Ret] - FF_merged.size[Size_rank==10,Ret])) write.table(size_mat, file = "Size_Result.csv", row.names=TRUE, sep=",") #------------------------------------------ Question 3 ---------------------------------------# BEME_FF_portfolio = as.data.table(read.csv("Portfolios_Formed_on_BE-ME.csv")) BEME_FF_portfolio = BEME_FF_portfolio[X>=197307& X<=201812,] BEME_FF_portfolio = BEME_FF_portfolio[, c(1,11:20)] colnames(BEME_FF_portfolio) = c("date", 1:10) BEME_FF_portfolio = melt(BEME_FF_portfolio, id.vars = "date") BEME_FF_portfolio[, Year:= date%/%100] BEME_FF_portfolio[, Month:= date - Year*100] BEME_FF_portfolio = BEME_FF_portfolio[, .(Year, Month, Ret= value/100, BtM_rank = variable)] FF_merged.BtM = merge(BEME_FF_portfolio, FF_Factors[, c(1,2,5)], by =c("Year","Month")) BtM_mat = matrix(nrow=5, ncol=11,dimnames = list(c("Excess Return","Standard Deviation", "Sharpe Ratio","Skewness","Correlation"), c(1:10,"LongShort"))) for(i in 1:10){ BtM_mat[1,i] = mean(BtM_port[BtM_Rank==i,BtM_Ret] - FF_merged.BtM[BtM_rank==i,RF])*12 BtM_mat[2,i] = sd(BtM_port[BtM_Rank==i,BtM_Ret])*sqrt(12) BtM_mat[3,i] = BtM_mat[1,i]/BtM_mat[2,i] BtM_mat[4,i] = skewness(BtM_port[BtM_Rank==i,BtM_Ret]) BtM_mat[5,i] = cor(BtM_port[BtM_Rank==i,BtM_Ret], FF_merged.BtM[BtM_rank==i,Ret]) } WML_series = BtM_port[BtM_Rank==10,BtM_Ret] - FF_merged.BtM[BtM_rank==1,Ret] BtM_mat[1,11] <- mean(WML_series)*12 BtM_mat[2,11] <- sd(WML_series)*sqrt(12) BtM_mat[3,11] <- BtM_mat[1,11]/BtM_mat[2,11] BtM_mat[4,11] <- skewness(WML_series) BtM_mat[5,11] <- cor(WML_series, (FF_merged.BtM[BtM_rank==10,Ret] - FF_merged.BtM[BtM_rank==1,Ret])) write.table(BtM_mat, file = "BTM_Result.csv", row.names=TRUE, sep=",") #------------------------------------------ Question 4 ---------------------------------------# start = which(size_port$Year==2008 & size_port$Month==1 & size_port$Size==1) end = which(size_port$Year==2018 & size_port$Month==12 & size_port$Size==10) size_recent = size_port[start:end,] size_recent[,date:=as.yearmon(as.character(Year*100+Month),"%Y%m")] library(ggplot2) size_recent$Size = factor(size_recent$Size ) size.decile.plot = ggplot(size_recent, aes(x=date, y=Size_Ret, fill = Size))+geom_area() size.decile.plot time=sort(unique(size_recent$date)) size_WML = size_recent[Size=='1',]$Size_Ret - size_recent[Size=='10',]$Size_Ret size_WML = log(size_WML+1) size_WML_port = data.frame(time, cumsum(size_WML)) size_wml.plot = ggplot()+geom_line(aes(x= size_WML_port$time, y=size_WML_port$cumsum.size_WML.), colour='blue') size_wml.plot BtM_recent = BtM_port[start:end,] BtM_recent[,date:=as.yearmon(as.character(Year*100+Month),"%Y%m")] BtM_recent$BtM_Rank = factor(BtM_recent$BtM_Rank) btm.decile.plot = ggplot(BtM_recent, aes(x=date, y=BtM_Ret, fill = BtM_Rank))+geom_area() btm.decile.plot btm_WML = BtM_recent[BtM_Rank=='10',]$BtM_Ret - BtM_recent[BtM_Rank=='1',]$BtM_Ret btm_WML = log(btm_WML+1) btm_WML_port = data.frame(time, cumsum(btm_WML)) btm_wml.plot = ggplot()+geom_line(aes(x= btm_WML_port$time, y=btm_WML_port$cumsum.btm_WML.), colour='blue') btm_wml.plot #------------------------------------------ Question 5 ---------------------------------------# setkey(SMB,Year,Month) setkey(FF_Factors,Year,Month) SMB_mat <- matrix(nrow=5, ncol=1, dimnames = list(c("Excess Return","Standard Deviation", "Sharpe Ratio","Skewness","Correlation"),c("SMB"))) SMB_mat[1,1] <- mean(SMB$SMB_Ret - FF_Factors$RF)*12 SMB_mat[2,1] <- sd(SMB$SMB_Ret)*sqrt(12) SMB_mat[3,1] <- SMB_mat[1,1]/SMB_mat[2,1] SMB_mat[4,1] <- skewness(SMB$SMB_Ret) SMB_mat[5,1] <- cor(SMB$SMB_Ret, FF_Factors$SMB) write.table(SMB_mat, file = "SMB_Result.csv", row.names=TRUE, sep=",") setkey(HML,Year,Month) HML_mat <- matrix(nrow=5, ncol=1, dimnames = list(c("Excess Return","Standard Deviation", "Sharpe Ratio","Skewness","Correlation"),c("HML"))) HML_mat[1,1] <- mean(HML$HML_Ret - FF_Factors$RF)*12 HML_mat[2,1] <- sd(HML$HML_Ret)*sqrt(12) HML_mat[3,1] <- HML_mat[1,1]/HML_mat[2,1] HML_mat[4,1] <- skewness(HML$HML_Ret) HML_mat[5,1] <- cor(HML$HML_Ret, FF_Factors$HML) write.table(HML_mat, file = "HML_Result.csv", row.names=TRUE, sep=",") #------------------------------------------ Question 6 ---------------------------------------# size_WML_full = size_port[Size=='1',]$Size_Ret - size_port[Size=='10',]$Size_Ret SMB_full = SMB$SMB_Ret size_port[,date:=as.yearmon(as.character(Year*100+Month),"%Y%m")] time=sort(unique(size_port$date)) size_WML_full = log(size_WML_full+1) SMB_full = log(SMB_full+1) compare1 = data.frame(time, cumsum(size_WML_full),cumsum(SMB_full)) colnames(compare1) = c("time", "size_long_short","SMB") p1 = ggplot(compare1, aes(x=time)) + geom_line(aes(y=size_long_short, color="cyan")) + geom_line(aes(y=SMB, color="skylightblue"))+ scale_fill_discrete(name="colour",labels=c("Size", "SMB"))+ ggtitle("Size Long Short Portfolio vs SMB") p1 btm_WML_full = BtM_port[BtM_Rank=='10',]$BtM_Ret - BtM_port[BtM_Rank=='1',]$BtM_Ret HML_full = HML$HML_Ret BtM_port[,date:=as.yearmon(as.character(Year*100+Month),"%Y%m")] btm_WML_full = log(btm_WML_full+1) HML_full = log(HML_full+1) compare2 = data.frame(time, cumsum(btm_WML_full),cumsum(HML_full)) colnames(compare2) = c("time", "BtM_long_short","HML") p2 = ggplot(compare2, aes(x=time)) + geom_line(aes(y=BtM_long_short, color="cyan")) + geom_line(aes(y=HML, color="skylightblue"))+ ggtitle("BtM Long Short Portfolio vs HML") p2<file_sep>/PS1_205259521.R library(data.table) library(lubridate) library(dplyr) library(fBasics) setwd("C:/Users/seayo/Desktop/QAM/PS1") ###### QUESTION 1 CRSP_Stocks = as.data.table(read.table("CRSP_Stocks.csv", sep=",",header = TRUE)) PS1_Q1 = function(crsp){ # Convert format crsp[, RET := as.numeric(levels(RET))[RET]] crsp[, DLRET := as.numeric(levels(DLRET))[DLRET]] crsp[, date := as.Date(as.character(date),format="%Y%m%d")] # Raw data price has negative value crsp[, PRC := abs(PRC)] crsp[, CAP := PRC * SHROUT] crsp[, lag_CAP := shift(CAP), by = PERMNO] #Select SHRCD = (10,11), EXCHCD = (1,2,3) crsp = crsp[SHRCD %in% c(10,11)] crsp = crsp[EXCHCD %in% c(1,2,3)] crsp = na.omit(crsp, cols="lag_CAP") # Deal with RET and DLRET crsp <- crsp[!is.na(RET) | !is.na(DLRET), ] crsp <- crsp[is.na(RET), RETURN := DLRET] crsp <- crsp[is.na(DLRET), RETURN := RET] crsp <- crsp[!is.na(RET) & !is.na(DLRET), RETURN := (1+RET) * (1+DLRET) - 1] crsp <- crsp[, -c("SHRCD", "EXCHCD", "DLRET", "PRC", "SHROUT", "RET", "CAP")] setkey(crsp, date) crsp[, VW := lag_CAP / sum(lag_CAP), by = date] # EWRET EWRET <- crsp[, .(Stock_Ew_Ret = round(mean(RETURN, na.rm = T),4)), by = date] # VWRET VWRET <- crsp[, .(Stock_Vw_Ret = round(sum(VW*RETURN, na.rm=T),4)), by = date] # Lagged Marekt Value lag_CAP <- crsp[, .(Stock_lag_MV = round(sum(lag_CAP)/1000000, 4)), by = date] # Add Year and Month lag_CAP[, Year:= year(date)] lag_CAP[, Month:= month(date)] output = full_join(lag_CAP, EWRET, by = "date") output = full_join(output, VWRET , by = "date") output = output[, c(3,4,2,5,6)] return(output) } Monthly_CRSP_Stocks = PS1_Q1(CRSP_Stocks) ###### QUESTION 2 FF_mkt = na.omit(as.data.table(read.table("F-F_Research_Data_Factors.csv", skip = 3, sep=",",header = TRUE))) colnames(FF_mkt) = c("date", "Market_minus_Rf", "SMB","HML","Rf") FF_mkt[, date:= as.numeric(levels(date))[date]] FF_mkt[, Year:= date%/%100] FF_mkt[, Month:= date - Year*100] FF_mkt = FF_mkt[,c(6,7,2,3,4,5)] PS1_Q2 = function(crsp,ff){ crsp = crsp[which(crsp$Year==1926 & crsp$Month ==7):length(crsp$Year),] est = crsp$Stock_Vw_Ret-ff$Rf/100 real = ff$Market_minus_Rf/100 output = matrix(0,nrow = 5,ncol = 2) row.names(output) = c("Annualized Mean", "Annualized Standard Deviation", "Annualized Sharpe Ratio", "Skewness", "Excess Kurtosis") colnames(output) = c("Estimated FF Market Excess Return", "Actual FF Market Excess Return") output[1,1] = round(mean(est)*12,4) output[1,2] = round(mean(real)*12,4) output[2,1] = round(sd(est)*sqrt(12),4) output[2,2] = round(sd(real)*sqrt(12),4) output[3,1] = round(output[1,1]/output[2,1],4) output[3,2] = round(output[1,2]/output[2,2],4) output[4,1] = round(skewness(est),4) output[4,2] = round(skewness(real),4) output[5,1] = round(kurtosis(est,method = "excess"),4) output[5,2] = round(kurtosis(real,method = "excess"),4) return(output) } Comparision = PS1_Q2(Monthly_CRSP_Stocks,FF_mkt) ###### QUESTION 3 PS1_Q3 = function(crsp,ff){ crsp = crsp[which(crsp$Year==1926 & crsp$Month ==7):length(crsp$Year),] est = crsp$Stock_Vw_Ret-ff$Rf/100 real = ff$Market_minus_Rf/100 output = vector(mode="numeric",length=2) output[1] = round(cor(est,real),8) output[2] = round(max(abs(est-real)),8) return(output) } Difference = PS1_Q3(Monthly_CRSP_Stocks,FF_mkt)
d909b2730097c4f21d6fb2693d13c1c307b64dde
[ "R" ]
4
R
dongxy1014/Quantitative-Asset-Management
1b6fc27e1965bc7de5955918062efecdd22671df
ddd7ab61804093cbc56b7f92d63792ecd5f344a5
refs/heads/master
<file_sep># -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure(2) do |config| config.vm.box = "ubuntu/trusty64" config.vm.network "public_network", ip: "192.168.0.199" config.ssh.forward_agent = true config.vm.provider :virtualbox do |vb| vb.name = "openwhisk" vb.gui = false vb.cpus = 4 vb.customize ['modifyvm', :id, '--natdnshostresolver1', 'on'] vb.customize ['modifyvm', :id, '--natdnsproxy1', 'on'] vb.customize ['modifyvm', :id, '--ostype', 'Ubuntu_64'] vb.customize ['modifyvm', :id, '--memory', 4096] end config.vm.provision "file", source: "./openwhisk-native.sh", destination: "~/openwhisk-native.sh" config.vm.provision "shell", inline: <<-SHELL addgroup docker usermod -aG docker vagrant SHELL end <file_sep>#! /bin/sh # # openwhisk-native.sh # Copyright (C) 2016 juan <<EMAIL>> # # Distributed under terms of the MIT license. # set -e OPEN_WHISK_HOME=~/workspace/openwhisk DATABASE_CONFIG=$OPEN_WHISK_HOME/couchdb-local.env # Database config DB_USER=iamkyloren DB_PASSWORD=<PASSWORD> DB_HOST=$(ip route get 8.8.8.8 | awk '{print $NF; exit}') DB_PORT=5984 # Install dependencies echo "Installing dependencies..." sudo add-apt-repository ppa:couchdb/stable -y sudo apt-get update -qq --fix-missing sudo apt-get install git curl couchdb -y -qq # Add Docker's GPG echo "Adding Docker's GPG..." curl -fsSL https://get.docker.com/gpg | sudo apt-key add - # Allow database access from everywhere. NOT READY for production. echo "Allowing connections to CouchDB..." sudo sed -i -- "s/;bind_address = 127.0.0.1/bind_address = 0.0.0.0/g" /etc/couchdb/local.ini sudo service couchdb restart echo "Waiting for CouchDB to start..." sleep 10 # Create the admin user echo "Creating admin users to the database..." curl -X PUT http://$DB_HOST:$DB_PORT/_config/admins/$DB_USER -d '"'"$DB_PASSWORD"'"' curl -X GET http://$DB_USER:$DB_PASSWORD@$DB_HOST:$DB_PORT/_config # Create OpenWhisk directory echo "Cloning OpenWhisk..." mkdir $OPEN_WHISK_HOME -p cd $OPEN_WHISK_HOME # Clone the repo git clone https://github.com/openwhisk/openwhisk.git . # Copy template and setup the database config for OW echo "Configuring OpenWhisk's database access..." cp template-couchdb-local.env $DATABASE_CONFIG sed -i -- "s/OPEN_WHISK_DB_PROTOCOL=/OPEN_WHISK_DB_PROTOCOL=http/g" $DATABASE_CONFIG sed -i -- "s/OPEN_WHISK_DB_HOST=/OPEN_WHISK_DB_HOST=$DB_HOST/g" $DATABASE_CONFIG sed -i -- "s/OPEN_WHISK_DB_PORT=/OPEN_WHISK_DB_PORT=$DB_PORT/g" $DATABASE_CONFIG sed -i -- "s/OPEN_WHISK_DB_USERNAME=/OPEN_WHISK_DB_USERNAME=$DB_USER/g" $DATABASE_CONFIG sed -i -- "s/OPEN_WHISK_DB_PASSWORD=/OPEN_WHISK_DB_PASSWORD=$DB_PASSWORD/g" $DATABASE_CONFIG # Create the basic DB structure echo "Create basic database structure..." tools/db/createImmortalDBs.sh # Install all the rest of the dependencies echo "Install rest of dependencies..." cd tools/ubuntu-setup ./all.sh cd $OPEN_WHISK_HOME # Build, deploy and run echo "Clen, build and deploy OpenWhisk" ant clean build deploy <file_sep># OpenWhisk Native Setup The purpose of this repo is to have an automated script to setup OpenWhisk the simplest, fastest and easiest possible way. Originally produced for [this](https://developer.ibm.com/openwhisk/2016/06/28/using-openwhisk-outside-ibm-bluemix/) article. ## WARNING: ONLY FOR DEVELOPMENT PURPOSES ## How to use it ### AWS 1. Clone the repo. 2. `cd` into the cloned repo directory. 3. `cp terraform.tfvars.example terraform.tfvars` 4. Edit the `terraform.tfvars` values accordingly 3. `terraform plan && terraform apply` 4. `ssh` into your EC2 instance 5. Run the `openwhisk-native.sh` file in the user's home directory. The [Terraform](https://www.terraform.io/) provided script will create an EC2 instance and copy the `openwhisk-native.sh` file to the user's home directory. Also, it will create a security group with the necessary ports opened. ### Vagrant 1. Clone the repo. 2. `cd` into the cloned repo directory. 3. `vagrant up` 4. `vagrant ssh` 5. Run the `openwhisk-native.sh` file in the user's home directory.
99507f59d8c316ca5122e1f97ec602b99f7a17bc
[ "Markdown", "Ruby", "Shell" ]
3
Ruby
eljuanchosf/openwhisk-setup
2ed3b7463adc626171a36880763ab5c39a4f72de
c74755686f4609fd7a755a23da33b0b9601bccc2
refs/heads/master
<repo_name>atframework/atlist-rs<file_sep>/src/tests.rs use super::*; use std::iter::IntoIterator; use std::thread; use std::vec::Vec; use rand::{thread_rng, RngCore}; fn list_from<T: Clone>(v: &[T]) -> LinkedList<T> { v.iter().cloned().collect() } pub fn check_links<T>(list: &LinkedList<T>) { unsafe { let mut len = 0; let mut last_ptr: Option<&Node<T>> = None; let mut node_ptr: &Node<T>; match list.data.get_head() { None => { // tail node should also be None. assert!(list.data.get_tail().is_none()); assert_eq!(0, list.data.len); return; } Some(node) => { let left_guard = node.as_ref().read(); assert!(left_guard.as_ref().unwrap().prev.is_none()); let left = left_guard.as_ref().unwrap().end.as_ptr(); let right = Arc::as_ptr(&list.data.end); assert!(ptr::eq(left, right)); assert!(!ptr::eq(Arc::as_ptr(node.as_ref()), right)); node_ptr = &*node.as_ptr() } } loop { match (last_ptr, node_ptr.read().unwrap().prev) { (None, None) => {} (None, _) => panic!("prev link for head"), (Some(p), Some(pptr)) => { assert_eq!(p as *const Node<T>, pptr.as_ptr() as *const Node<T>); } _ => panic!("prev link is none, not good"), } len += 1; match node_ptr.read().unwrap().next { Some(next) => { let left_guard = next.as_ref().read().unwrap(); let left = left_guard.end.as_ptr(); let right = Arc::as_ptr(&list.data.end); assert!(ptr::eq(left, right)); assert!(!ptr::eq(Arc::as_ptr(next.as_ref()), right)); last_ptr = Some(node_ptr); node_ptr = &*next.as_ptr(); } None => { break; } } } // verify that the tail node points to the last node. let tail = list.data.get_tail().expect("some tail node"); let tail_ptr = &*tail.as_ptr(); assert_eq!(tail_ptr as *const Node<T>, node_ptr as *const Node<T>); // check that len matches interior links. assert_eq!(len, list.data.len); } } #[test] fn test_clone_from() { // Short cloned from long { let v = vec![1, 2, 3, 4, 5]; let u = vec![8, 7, 6, 2, 3, 4, 5]; let mut m = list_from(&v); let n = list_from(&u); m.clone_from(&n); check_links(&m); assert_eq!(m, n); for elt in u { assert_eq!(*m.pop_front().unwrap().as_ref(), elt) } } // Long cloned from short { let v = vec![1, 2, 3, 4, 5]; let u = vec![6, 7, 8]; let mut m = list_from(&v); let n = list_from(&u); m.clone_from(&n); check_links(&m); assert_eq!(m, n); for elt in u { assert_eq!(*m.pop_front().unwrap().as_ref(), elt) } } // Two equal length lists { let v = vec![1, 2, 3, 4, 5]; let u = vec![9, 8, 1, 2, 3]; let mut m = list_from(&v); let n = list_from(&u); m.clone_from(&n); check_links(&m); assert_eq!(m, n); for elt in u { assert_eq!(*m.pop_front().unwrap().as_ref(), elt) } } } #[test] #[cfg_attr(target_os = "emscripten", ignore)] fn test_send() { let n = list_from(&[1, 2, 3]); thread::spawn(move || { check_links(&n); let a: &[_] = &[&1, &2, &3]; let b = n.iter().map(|x| *x.as_ref()).collect::<Vec<_>>(); assert_eq!(a, &*b.iter().collect::<Vec<_>>()); }) .join() .ok() .unwrap(); } #[test] fn test_fuzz() { for _ in 0..25 { fuzz_test(3); fuzz_test(16); #[cfg(not(miri))] // Miri is too slow fuzz_test(189); } } fn fuzz_test(sz: i32) { let mut m: LinkedList<_> = LinkedList::new(); let mut v = vec![]; for i in 0..sz { check_links(&m); let r: u8 = thread_rng().next_u32() as u8; match r % 6 { 0 => { let _ = m.pop_back(); v.pop(); } 1 => { if !v.is_empty() { let _ = m.pop_front(); v.remove(0); } } 2 | 4 => { let _ = m.push_front(-i); v.insert(0, -i); } 3 | 5 | _ => { let _ = m.push_back(i); v.push(i); } } } check_links(&m); let mut i = 0; for (a, &b) in m.into_iter().zip(&v) { i += 1; assert_eq!(*a.as_ref(), b); } assert_eq!(i, v.len()); } #[test] fn test_iter_move_peek() { let mut m: LinkedList<u32> = LinkedList::new(); let n = [1, 2, 3, 4, 5, 6]; m.extend(&n); let mut iter = m.iter(); assert_eq!(*iter.unwrap().as_ref(), 1); assert_eq!(*iter.next().unwrap().as_ref(), 1); assert_eq!(*iter.next().unwrap().as_ref(), 2); assert_eq!(*iter.unwrap().as_ref(), 3); assert_eq!(*iter.next_back().unwrap().as_ref(), 3); assert_eq!(*iter.next_back().unwrap().as_ref(), 2); assert_eq!(*iter.next_back().unwrap().as_ref(), 1); assert_eq!(iter.next_back(), None); assert_eq!(iter.try_unwrap(), Err(LinkedListError::IteratorNotInList)); assert_eq!(iter.next(), None); assert_eq!(*iter.unwrap().as_ref(), 1); let mut iter = m.iter_back(); assert_eq!(*iter.unwrap().as_ref(), 6); assert_eq!(*iter.next().unwrap().as_ref(), 6); assert_eq!(iter.next(), None); assert_eq!(iter.next_back(), None); assert_eq!(*iter.unwrap().as_ref(), 6); assert_eq!(*iter.next_back().unwrap().as_ref(), 6); assert_eq!(*iter.unwrap().as_ref(), 5); let mut m: LinkedList<u32> = LinkedList::new(); m.extend(&[1, 2, 3, 4, 5, 6]); let mut iter = m.iter_mut(); assert_eq!(*iter.unwrap().as_ref(), 1); assert_eq!(*iter.next().unwrap().as_ref(), 1); assert_eq!(*iter.next().unwrap().as_ref(), 2); assert_eq!(*iter.unwrap().as_ref(), 3); assert_eq!(*iter.next_back().unwrap().as_ref(), 3); assert_eq!(*iter.next_back().unwrap().as_ref(), 2); assert_eq!(*iter.next_back().unwrap().as_ref(), 1); assert_eq!(iter.next_back(), None); assert_eq!(iter.try_unwrap(), Err(LinkedListError::IteratorNotInList)); assert_eq!(iter.next(), None); assert_eq!(*iter.unwrap().as_ref(), 1); let mut iter = m.iter_mut_back(); assert_eq!(*iter.unwrap().as_ref(), 6); assert_eq!(*iter.next().unwrap().as_ref(), 6); assert_eq!(iter.next(), None); assert_eq!(iter.next_back(), None); assert_eq!(*iter.unwrap().as_ref(), 6); assert_eq!(*iter.next_back().unwrap().as_ref(), 6); assert_eq!(*iter.unwrap().as_ref(), 5); } #[test] fn test_iter_mut_insert() { let mut m: LinkedList<u32> = LinkedList::new(); m.extend(&[1, 2, 3, 4, 5, 6]); let iter = m.iter_mut_front(); assert!(m.insert_before(&iter, 7).is_ok()); assert!(m.insert_after(&iter, 8).is_ok()); check_links(&m); assert_eq!( m.iter().map(|elt| *elt.as_ref()).collect::<Vec<_>>(), &[7, 1, 8, 2, 3, 4, 5, 6] ); let mut iter = m.iter_mut_front(); assert_eq!(*iter.next_back().unwrap().as_ref(), 7); assert!(m.insert_before(&iter, 9).is_ok()); assert!(m.insert_after(&iter, 10).is_ok()); check_links(&m); assert_eq!( m.iter().map(|elt| *elt.as_ref()).collect::<Vec<_>>(), &[10, 7, 1, 8, 2, 3, 4, 5, 6, 9] ); let mut iter = m.iter_mut_front(); assert_eq!(*iter.next_back().unwrap().as_ref(), 10); assert_eq!( m.remove_iter_mut(&mut iter), Err(LinkedListError::IteratorNotInList) ); assert_eq!(iter.next(), None); assert_eq!(*iter.next().unwrap().as_ref(), 10); assert_eq!(*m.remove_iter_mut(&mut iter).unwrap(), 7); assert_eq!(iter.try_unwrap(), Err(LinkedListError::IteratorNotInList)); assert_eq!(iter.next(), None); assert_eq!(iter.next_back(), None); assert_eq!(*iter.next().unwrap().as_ref(), 9); let mut iter = m.iter_mut_back(); let _ = iter.next(); let _ = iter.next_back(); assert_eq!(*m.remove_iter_mut(&mut iter).unwrap(), 9); assert_eq!(iter.try_unwrap(), Err(LinkedListError::IteratorNotInList)); assert_eq!(iter.next_back(), None); assert_eq!(iter.next(), None); assert_eq!(*iter.next_back().unwrap().as_ref(), 10); let mut iter = m.iter_mut(); assert_eq!(*m.remove_iter_mut(&mut iter).unwrap(), 10); assert_eq!(iter.try_unwrap(), Err(LinkedListError::IteratorNotInList)); assert_eq!(iter.next(), None); assert_eq!(iter.next_back(), None); assert_eq!(*iter.next().unwrap().as_ref(), 6); check_links(&m); assert_eq!( m.iter().map(|elt| *elt.as_ref()).collect::<Vec<_>>(), &[1, 8, 2, 3, 4, 5, 6] ); } #[test] fn test_iter_mut_insert_into_empty_list() { let mut m: LinkedList<u32> = LinkedList::new(); let iter = m.iter_mut(); assert!(m.insert_before(&iter, 3).is_ok()); assert!(m.insert_after(&iter, 2).is_ok()); assert!(m.insert_before(&iter, 4).is_ok()); assert!(m.insert_after(&iter, 1).is_ok()); check_links(&m); assert_eq!( m.iter().map(|elt| *elt.as_ref()).collect::<Vec<_>>(), &[1, 2, 3, 4] ); } #[test] fn test_iter_len_is_empty() { let mut m: LinkedList<u32> = LinkedList::new(); m.extend(&[1]); let mut iter = m.iter(); assert!(!iter.is_empty()); assert_eq!(iter.clone().count(), 1); assert_eq!(iter.size_hint(), (1, None)); let _ = iter.next_back(); assert!(iter.is_empty()); assert_eq!(iter.clone().count(), 0); assert_eq!(iter.size_hint(), (0, None)); let mut iter = m.iter_mut(); assert!(!iter.is_empty()); assert_eq!(iter.clone().count(), 1); assert_eq!(iter.size_hint(), (1, None)); let _ = iter.next_back(); assert!(iter.is_empty()); assert_eq!(iter.clone().count(), 0); assert_eq!(iter.size_hint(), (0, None)); } #[test] fn test_document_list_len() { let mut dl = LinkedList::new(); let _ = dl.push_front(2); assert_eq!(dl.len(), 1); let _ = dl.push_front(1); assert_eq!(dl.len(), 2); let _ = dl.push_back(3); assert_eq!(dl.len(), 3); } #[test] fn test_document_list_is_empty() { let mut dl = LinkedList::new(); assert!(dl.is_empty()); let _ = dl.push_front("foo"); assert!(!dl.is_empty()); } #[test] fn test_document_list_front() { let mut dl = LinkedList::new(); assert_eq!(dl.front(), Err(LinkedListError::Empty)); let _ = dl.push_front(1); assert_eq!(*dl.front().unwrap(), 1); } #[test] fn test_document_list_back() { let mut dl = LinkedList::new(); assert_eq!(dl.back(), Err(LinkedListError::Empty)); let _ = dl.push_back(1); assert_eq!(*dl.back().unwrap(), 1); } #[test] fn test_document_list_contains_iter() { let mut list: LinkedList<u32> = LinkedList::new(); let mut another_list: LinkedList<u32> = LinkedList::new(); let _ = list.push_back(0); let _ = list.push_back(1); let _ = another_list.push_back(2); assert_eq!(list.contains_iter(&list.iter()), Ok(())); assert_eq!( list.contains_iter(&another_list.iter()), Err(LinkedListError::IteratorNotInList) ); } #[test] fn test_document_list_contains_iter_mut() { let mut list: LinkedList<u32> = LinkedList::new(); let mut another_list: LinkedList<u32> = LinkedList::new(); let _ = list.push_back(0); let _ = list.push_back(1); let _ = another_list.push_back(2); let iter = list.iter_mut(); let another_iter = another_list.iter_mut(); assert_eq!(list.contains_iter_mut(&iter), Ok(())); assert_eq!( list.contains_iter_mut(&another_iter), Err(LinkedListError::IteratorNotInList) ); } <file_sep>/README.md # atlist [![github action badge]][github action url] [![codecov badge]][coverage status] [![crates.io badge]][crates.io package] [![docs.rs badge]][docs.rs documentation] [![license badge]][license] [Documentation] A LinkedList in which the liftime of iterator is independent from LinkedList.So it's allowed to store iterator into anywhere and insert/remove element by iterator at any time. Adding, removing and moving a iterator does not invalidate other iterators or references. An iterator is invalidated only when the corresponding element is deleted. We use ```std::sync::Arc``` to manange lifetime of real data entry, so it's slightly slower than ```std::collections::LinkedList``` . [github action badge]: https://github.com/atframework/atlist-rs/actions/workflows/build.yml/badge.svg [github action url]: https://github.com/atframework/atlist-rs/actions/workflows/build.yml [codecov badge]: https://codecov.io/gh/atframework/atlist-rs/branch/master/graph/badge.svg [coverage status]: https://codecov.io/gh/atframework/atlist-rs [crates.io badge]: https://img.shields.io/crates/v/atlist-rs.svg [crates.io package]: https://crates.io/crates/atlist-rs/ [documentation]: https://docs.rs/atlist-rs/ [docs.rs badge]: https://docs.rs/atlist-rs/badge.svg [docs.rs documentation]: (https://docs.rs/atlist-rs/) [license badge]: https://img.shields.io/crates/l/atlist-rs [license]: (https://github.com/atframework/atlist-rs/blob/master/LICENSE) <file_sep>/Cargo.toml [package] name = "atlist-rs" version = "0.2.1" authors = ["owent <<EMAIL>>"] license = "MIT OR Apache-2.0" description = "A LinkedList which is allowed to insert/remove element by immutable iterator.Adding, removing and moving the elements within the list or across several lists does not invalidate the iterators or references. An iterator is invalidated only when the corresponding element is deleted." homepage = "https://github.com/atframework/atlist-rs" repository = "https://github.com/atframework/libatbus-rs" documentation = "https://docs.rs/atlist-rs" keywords = ["collections", "list", "linkedlist"] categories = ["data-structures"] edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [lib] #proc-macro = true bench = false # It's nightly now harness = true [dependencies] [dev-dependencies] rand = "0.8" rand_xorshift = "0.3" <file_sep>/src/lib.rs // MIT License // Copyright (c) 2021 OWenT // 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. //! A LinkedList which is allowed to insert/remove element by immutable iterator. //! Adding, removing and moving the elements within the list or across several lists //! does not invalidate the iterators or references. An iterator is invalidated only //! when the corresponding element is deleted. //! //! ## Example //! //! ```rust,no_run //! extern crate atlist_rs; //! //! use atlist_rs::LinkedList; //! //! fn main() { //! let mut l = LinkedList::new(); //! let _ = l.push_back(3); //! let _ = l.push_front(2); //! //! assert_eq!(l.len(), 2); //! assert_eq!(*l.front().unwrap(), 2); //! assert_eq!(*l.back().unwrap(), 3); //! } //! ``` //#![no_std] #![cfg_attr(feature = "nightly", feature(negative_impls, auto_traits))] use core::cmp::Ordering; use core::fmt; use core::hash::{Hash, Hasher}; use core::iter::{Extend, FromIterator, FusedIterator}; use core::marker; use core::mem; use core::pin::Pin; use core::ptr; use core::ptr::NonNull; use core::result::Result; use core::usize; use std::{borrow::BorrowMut, error::Error}; use std::{ ops::Deref, sync::{Arc, PoisonError, RwLock, TryLockError, Weak}, }; //#[cfg(test)] //extern crate rand; #[cfg(test)] mod tests; #[derive(PartialEq, PartialOrd, Eq, Ord)] pub enum LinkedListError { /// Try mutex lock failed TryLockError(String), /// Iterator is not in specified LinkedList IteratorNotInList, /// LinkedList or iterator is empty Empty, /// LinkedList inner bad data BadData, } impl fmt::Display for LinkedListError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { &LinkedListError::TryLockError(ref e) => write!(f, "Try lock failed: {}", e), LinkedListError::IteratorNotInList => write!(f, "Iterator not in list"), LinkedListError::Empty => write!(f, "LinkedList or iterator is empty"), LinkedListError::BadData => write!(f, "LinkedList or iterator bad data"), } } } impl fmt::Debug for LinkedListError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { &LinkedListError::TryLockError(ref e) => write!(f, "Try lock failed: {}", e), LinkedListError::IteratorNotInList => write!(f, "Iterator not in list"), LinkedListError::Empty => write!(f, "LinkedList or iterator is empty"), LinkedListError::BadData => write!(f, "LinkedList or iterator bad data"), } } } impl Error for LinkedListError { #[allow(deprecated)] // call to `description` fn description(&self) -> &str { match self { &LinkedListError::TryLockError(_) => &"LinkedList or iterator lock failed", LinkedListError::IteratorNotInList => &"Iterator not in list", LinkedListError::Empty => &"LinkedList or iterator is empty", LinkedListError::BadData => &"LinkedList or iterator bad data", } } fn cause(&self) -> Option<&dyn Error> { Some(self) } } impl<'a, T> From<PoisonError<T>> for LinkedListError { fn from(err: PoisonError<T>) -> Self { LinkedListError::TryLockError(format!("{}", err)) } } impl<'a, T> From<TryLockError<T>> for LinkedListError { fn from(err: TryLockError<T>) -> Self { LinkedListError::TryLockError(format!("{}", err)) } } pub type LinkedListResult<T> = Result<T, LinkedListError>; pub type LinkedListItem<T> = Arc<T>; type Node<T> = Arc<RwLock<NodeEntry<T>>>; struct NodeEntry<T> { next: Option<NonNull<Node<T>>>, prev: Option<NonNull<Node<T>>>, element: Option<LinkedListItem<T>>, end: Weak<RwLock<NodeEntry<T>>>, leak: Option<NonNull<Node<T>>>, } struct UnmoveableLinkedList<T> { end: Node<T>, len: usize, } /// A doubly-linked list in which the liftime of iterator is independent from /// self. /// /// The `LinkedList` allows pushing and popping elements at either end /// in constant time. pub struct LinkedList<T> { data: Pin<Box<UnmoveableLinkedList<T>>>, } /// An iterator over the elements of a `LinkedList`. /// /// This `struct` is created by [`LinkedList::iter()`]. See its /// documentation for more. /// /// This iterator is just like `std::collections::linked_list::Cursor` /// but it's allowed to be saved into anywhere and can be converted into /// `IterMut`. by any time. pub struct Iter<T> { node: Weak<RwLock<NodeEntry<T>>>, last_back: bool, } /// A mutable iterator over the elements of a `LinkedList`. /// /// This `struct` is created by [`LinkedList::iter_mut()`]. See its /// documentation for more. /// /// This iterator is just like `std::collections::linked_list::CursorMut` /// but it can freely seek back-and-forth, and can safely mutate the list /// during iteration and also it can also be saved into anywhere and yield /// multiple elements at once.We will use `std::sync::RwLock` to keep it safe. pub struct IterMut<T> { node: Weak<RwLock<NodeEntry<T>>>, last_back: bool, } fn check_iter_valid<T>(iter: &Iter<T>) -> bool { iter.node.strong_count() > 0 && if let Some(x) = iter.node.upgrade() { if let Ok(y) = x.read() { y.element.is_some() } else { false } } else { false } } fn check_iter_mut_valid<T>(iter: &IterMut<T>) -> bool { iter.node.strong_count() > 0 && if let Some(x) = iter.node.upgrade() { if let Ok(y) = x.read() { y.element.is_some() } else { false } } else { false } } impl<T> NodeEntry<T> { #[inline] fn new(elt: T, container: &mut Pin<Box<UnmoveableLinkedList<T>>>) -> Box<Node<T>> { NodeEntry::from(Arc::new(elt), container) } fn from( elt: LinkedListItem<T>, container: &mut Pin<Box<UnmoveableLinkedList<T>>>, ) -> Box<Node<T>> { let container = unsafe { Pin::get_unchecked_mut(container.as_mut()) }; let ret = NodeEntry { next: None, prev: None, element: Some(elt), end: Arc::downgrade(&container.end), leak: None, }; Box::new(Arc::new(RwLock::new(ret))) } #[inline] fn uninited_new() -> Node<T> { let ret = NodeEntry { next: None, prev: None, element: None, end: Weak::default(), leak: None, }; Arc::new(RwLock::new(ret)) } } impl<T: fmt::Debug> fmt::Debug for Iter<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(x) = self.node.upgrade() { let current_node = match x.read() { Ok(x) => x, Err(e) => { return write!(f, "Iter: Locked: {:?}", e); } }; f.debug_tuple("Iter").field(&current_node.element).finish() } else { f.debug_tuple("Iter: Empty").finish() } } } impl<T> Clone for Iter<T> { fn clone(&self) -> Self { Iter { node: self.node.clone(), last_back: self.last_back, } } } impl<T> Clone for IterMut<T> { fn clone(&self) -> Self { IterMut { node: self.node.clone(), last_back: self.last_back, } } } impl<T: fmt::Debug> fmt::Debug for IterMut<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(x) = self.node.upgrade() { let current_node = match x.read() { Ok(x) => x, Err(e) => { return write!(f, "IterMut: Locked: {:?}", e); } }; f.debug_tuple("IterMut") .field(&current_node.element) .finish() } else { f.debug_tuple("IterMut: Empty").finish() } } } impl<T> Iterator for Iter<T> { type Item = LinkedListItem<T>; fn next(&mut self) -> Option<Self::Item> { let watcher = self.node.upgrade()?; let node = match watcher.read() { Ok(x) => x, Err(_) => { return None; } }; if !self.last_back && node.element.is_none() { return None; } let next_node = if let Some(next_watcher) = node.next { unsafe { Arc::downgrade(next_watcher.as_ref()) } } else { node.end.clone() }; self.node = next_node; self.last_back = false; node.element.clone() } fn size_hint(&self) -> (usize, Option<usize>) { if check_iter_valid(&self) { (1, None) } else { (0, None) } } fn count(self) -> usize { self.size_hint().0 } } impl<T> Iterator for IterMut<T> { type Item = LinkedListItem<T>; fn next(&mut self) -> Option<Self::Item> { let watcher = self.node.upgrade()?; let node = match watcher.read() { Ok(x) => x, Err(_) => { return None; } }; if !self.last_back && node.element.is_none() { return None; } let next_node = if let Some(next_watcher) = node.next { unsafe { Arc::downgrade(next_watcher.as_ref()) } } else { node.end.clone() }; self.node = next_node; self.last_back = false; node.element.clone() } fn size_hint(&self) -> (usize, Option<usize>) { if check_iter_mut_valid(&self) { (1, None) } else { (0, None) } } fn count(self) -> usize { self.size_hint().0 } } impl<T> DoubleEndedIterator for Iter<T> { #[inline] fn next_back(&mut self) -> Option<Self::Item> { let watcher = self.node.upgrade()?; let node = match watcher.read() { Ok(x) => x, Err(_) => { return None; } }; if self.last_back && node.element.is_none() { return None; } let prev_node = if let Some(prev_watcher) = node.prev { unsafe { Arc::downgrade(prev_watcher.as_ref()) } } else { node.end.clone() }; self.node = prev_node; self.last_back = true; node.element.clone() } } impl<T> DoubleEndedIterator for IterMut<T> { #[inline] fn next_back(&mut self) -> Option<Self::Item> { let watcher = self.node.upgrade()?; let node = match watcher.read() { Ok(x) => x, Err(_) => { return None; } }; if self.last_back && node.element.is_none() { return None; } let prev_node = if let Some(prev_watcher) = node.prev { unsafe { Arc::downgrade(prev_watcher.as_ref()) } } else { node.end.clone() }; self.node = prev_node; self.last_back = true; node.element.clone() } } impl<T> FusedIterator for Iter<T> {} impl<T> FusedIterator for IterMut<T> {} impl<T> Iter<T> { fn from(node: &Node<T>) -> Iter<T> { Iter { node: Arc::downgrade(&node), last_back: false, } } fn from_weak(node: Weak<RwLock<NodeEntry<T>>>) -> Iter<T> { Iter { node, last_back: false, } } pub fn try_unwrap(&self) -> LinkedListResult<LinkedListItem<T>> { let watcher = if let Some(x) = self.node.upgrade() { x } else { return Err(LinkedListError::IteratorNotInList); }; let guard = watcher.read()?; if guard.element.is_none() { return Err(LinkedListError::IteratorNotInList); } let ret = guard.element.as_ref().unwrap().clone(); drop(guard); Ok(ret) } pub fn unwrap(&self) -> LinkedListItem<T> { self.try_unwrap().unwrap() } pub fn is_empty(&self) -> bool { !check_iter_valid(self) } } impl<T> IterMut<T> { fn from(node: &Node<T>) -> IterMut<T> { IterMut { node: Arc::downgrade(&node), last_back: false, } } fn from_weak(node: Weak<RwLock<NodeEntry<T>>>) -> IterMut<T> { IterMut { node, last_back: false, } } pub fn try_unwrap(&self) -> LinkedListResult<LinkedListItem<T>> { let watcher = if let Some(x) = self.node.upgrade() { x } else { return Err(LinkedListError::IteratorNotInList); }; let guard = watcher.read()?; if guard.element.is_none() { return Err(LinkedListError::IteratorNotInList); } let ret = guard.element.as_ref().unwrap().clone(); drop(guard); Ok(ret) } pub fn unwrap(&self) -> LinkedListItem<T> { self.try_unwrap().unwrap() } pub fn is_empty(&self) -> bool { !check_iter_mut_valid(self) } } #[doc(hidden)] struct LinkedListCheckContainerResult<T> { current_is_end: bool, current: NonNull<Node<T>>, prev: Option<NonNull<Node<T>>>, next: Option<NonNull<Node<T>>>, } impl<T> UnmoveableLinkedList<T> { /// Unlinks the specified node from the current list. /// /// Warning: this will not check that the provided node belongs to the current list. #[inline] fn unlink_node(&mut self, node: NonNull<Node<T>>) -> LinkedListResult<LinkedListItem<T>> { let mut node = unsafe { node.as_ref() }.write()?; if node.leak.is_none() { return Err(LinkedListError::BadData); } if node.element.is_none() { return Err(LinkedListError::IteratorNotInList); } if node.prev.is_none() && node.next.is_none() && self.len > 0 { // Bad data return Err(LinkedListError::BadData); } if node.prev == node.next { let mut prev_next_node = if let Some(x) = &node.prev { Some(unsafe { x.as_ref() }.write()?) } else { None }; match &mut prev_next_node { Some(prev_next) => { prev_next.next = node.next; prev_next.prev = node.prev; } None => { self.set_head(node.next); self.set_tail(node.next); } }; } else { let mut prev_node = if let Some(x) = &node.prev { Some(unsafe { x.as_ref() }.write()?) } else { None }; let mut next_node = if let Some(x) = &node.next { Some(unsafe { x.as_ref() }.write()?) } else { None }; match &mut prev_node { Some(prev) => prev.next = node.next, None => self.set_head(node.next), }; match &mut next_node { Some(next) => next.prev = node.prev, // this node is the tail node None => self.set_tail(node.prev), }; } self.len -= 1; let unlinked_node = unsafe { Box::from_raw(node.leak.unwrap().as_ptr()) }; node.prev = None; node.next = None; node.leak = None; let ret = node.element.as_ref().unwrap().clone(); drop(node); drop(unlinked_node); Ok(ret) } /// Splices a series of nodes between two existing nodes. /// /// Warning: this will not check that the provided node belongs to the two existing lists. #[inline] fn splice_node( &mut self, existing_prev: Option<NonNull<Node<T>>>, existing_next: Option<NonNull<Node<T>>>, splice_node: Box<Node<T>>, ) -> LinkedListResult<IterMut<T>> { let splice_node_rc = splice_node.as_ref().clone(); let mut lock_node = splice_node_rc.write()?; if lock_node.leak.is_some() { return Err(LinkedListError::BadData); } // This method takes care not to create multiple mutable references to whole nodes at the same time, // to maintain validity of aliasing pointers into `element`. let leak_node; if existing_prev == existing_next { let mut prev_next_node = if let Some(x) = &existing_prev { Some(unsafe { x.as_ref() }.write()?) } else { None }; leak_node = Box::leak(splice_node).into(); if let Some(prev_next) = &mut prev_next_node { prev_next.next = Some(leak_node); prev_next.prev = Some(leak_node); } else { self.set_head(Some(leak_node)); self.set_tail(Some(leak_node)); } lock_node.leak = Some(leak_node); } else { let mut prev_node = if let Some(x) = &existing_prev { Some(unsafe { x.as_ref() }.write()?) } else { None }; let mut next_node = if let Some(x) = &existing_next { Some(unsafe { x.as_ref() }.write()?) } else { None }; leak_node = Box::leak(splice_node).into(); if let Some(prev) = &mut prev_node { prev.next = Some(leak_node); } else { self.set_head(Some(leak_node)); } if let Some(next) = &mut next_node { next.prev = Some(leak_node); } else { self.set_tail(Some(leak_node)); } } lock_node.prev = existing_prev; lock_node.next = existing_next; lock_node.leak = Some(leak_node); self.len += 1; Ok(IterMut::from(unsafe { leak_node.as_ref() })) } /// Adds the given node to the front of the list. #[inline] fn push_front_node(&mut self, node: Box<Node<T>>) -> LinkedListResult<()> { // This method takes care not to create mutable references to whole nodes, // to maintain validity of aliasing pointers into `element`. let node_rc = node.as_ref().clone(); let mut lock_node = node_rc.write()?; let head_node_rc = match self.get_head() { None => None, Some(head) => Some(unsafe { head.as_ref() }.clone()), }; let head_node = match &head_node_rc { None => None, Some(head) => Some(head.write()?), }; lock_node.next = self.get_head(); lock_node.prev = None; lock_node.leak = Some(Box::leak(node).into()); match head_node { None => self.set_tail(lock_node.leak), Some(mut head) => head.prev = lock_node.leak, } self.set_head(lock_node.leak); self.len += 1; Ok(()) } /// Removes and returns the node at the front of the list. #[inline] fn pop_front_node(&mut self) -> LinkedListResult<Box<Node<T>>> { // This method takes care not to create mutable references to whole nodes, // to maintain validity of aliasing pointers into `element`. let head_nonull = self.get_head(); if head_nonull.is_none() { return Err(LinkedListError::Empty); } let node = head_nonull.unwrap(); let mut head_node = unsafe { node.as_ref() }.write()?; if head_node.element.is_none() { return Err(LinkedListError::Empty); } let next_node_rc = match head_node.next { None => None, Some(next) => Some(unsafe { next.as_ref() }.clone()), }; let next_node = match &next_node_rc { None => None, Some(next) => Some(next.write()?), }; if head_node.leak.is_none() { return Err(LinkedListError::BadData); } let ret = unsafe { Box::from_raw(head_node.leak.unwrap().as_ptr()) }; self.set_head(head_node.next); head_node.next = None; head_node.leak = None; match next_node { None => self.set_tail(None), Some(mut next) => next.prev = None, } self.len -= 1; Ok(ret) } /// Adds the given node to the back of the list. #[inline] fn push_back_node(&mut self, node: Box<Node<T>>) -> LinkedListResult<()> { // This method takes care not to create mutable references to whole nodes, // to maintain validity of aliasing pointers into `element`. let node_rc = node.as_ref().clone(); let mut lock_node = node_rc.write()?; let tail_node_rc = match self.get_tail() { None => None, Some(tail) => Some(unsafe { tail.as_ref() }.clone()), }; let tail_node = match &tail_node_rc { None => None, Some(tail) => Some(tail.as_ref().write()?), }; lock_node.next = None; lock_node.prev = self.get_tail(); lock_node.leak = Some(Box::leak(node).into()); match tail_node { None => self.set_head(lock_node.leak), Some(mut tail) => tail.next = lock_node.leak, } self.set_tail(lock_node.leak); self.len += 1; Ok(()) } /// Removes and returns the node at the back of the list. #[inline] fn pop_back_node(&mut self) -> LinkedListResult<Box<Node<T>>> { // This method takes care not to create mutable references to whole nodes, // to maintain validity of aliasing pointers into `element`. let tail_nonull = self.get_tail(); if tail_nonull.is_none() { return Err(LinkedListError::Empty); } let node = tail_nonull.unwrap(); let mut tail_node = unsafe { node.as_ref() }.write()?; if tail_node.element.is_none() { return Err(LinkedListError::Empty); } let prev_node_rc = match tail_node.prev { None => None, Some(prev) => Some(unsafe { prev.as_ref() }.clone()), }; let prev_node = match &prev_node_rc { None => None, Some(prev) => Some(prev.write()?), }; if tail_node.leak.is_none() { return Err(LinkedListError::BadData); } let ret = unsafe { Box::from_raw(tail_node.leak.unwrap().as_ptr()) }; self.set_tail(tail_node.prev); tail_node.prev = None; tail_node.leak = None; match prev_node { None => self.set_head(None), Some(mut prev) => prev.next = None, } self.len -= 1; Ok(ret) } #[inline] fn check_container(&self, x: &NodeEntry<T>) -> Option<LinkedListCheckContainerResult<T>> { if ptr::eq(x.end.as_ptr(), Arc::as_ptr(&self.end)) { x.leak.map(|y| LinkedListCheckContainerResult { next: x.next, prev: x.prev, current: y, current_is_end: x.element.is_none(), }) } else { None } } #[inline] fn contains_iter(&self, x: &Iter<T>) -> LinkedListResult<LinkedListCheckContainerResult<T>> { let lock = if let Some(y) = x.node.upgrade() { y } else { return Err(LinkedListError::IteratorNotInList); }; let lock = lock.read()?; match self.check_container(&lock) { Some(x) => Ok(x), None => Err(LinkedListError::IteratorNotInList), } } #[inline] fn contains_iter_mut( &self, x: &IterMut<T>, ) -> LinkedListResult<LinkedListCheckContainerResult<T>> { let lock = if let Some(y) = x.node.upgrade() { y } else { return Err(LinkedListError::IteratorNotInList); }; let lock = lock.read()?; match self.check_container(&lock) { Some(x) => Ok(x), None => Err(LinkedListError::IteratorNotInList), } } #[inline] fn remove_iter(&mut self, iter: &mut IterMut<T>) -> LinkedListResult<LinkedListItem<T>> { let node = self.contains_iter_mut(&iter)?; let ret = self.unlink_node(node.current)?; iter.node = Arc::downgrade(&self.end); Ok(ret) } } impl<T> UnmoveableLinkedList<T> { #[inline] fn new() -> Pin<Box<Self>> { let res = UnmoveableLinkedList { end: NodeEntry::uninited_new(), len: 0, }; let mut boxed = Box::pin(res); let container = unsafe { Pin::get_unchecked_mut(boxed.as_mut()) }; let mut container = unsafe { NonNull::new_unchecked(container) }; let mut guard = boxed.end.write().unwrap(); guard.borrow_mut().end = Arc::downgrade(&unsafe { container.as_ref() }.end); guard.borrow_mut().leak = Some(unsafe { NonNull::new_unchecked((&mut container.as_mut().end) as *mut Node<T>) }); drop(guard); boxed } #[inline] fn get_head(&self) -> Option<NonNull<Node<T>>> { if let Ok(guard) = self.end.read() { guard.next } else { None } } #[inline] fn get_tail(&self) -> Option<NonNull<Node<T>>> { if let Ok(guard) = self.end.read() { guard.prev } else { None } } #[inline] fn set_head(&mut self, v: Option<NonNull<Node<T>>>) { self.end.write().unwrap().next = v; } #[inline] fn set_tail(&self, v: Option<NonNull<Node<T>>>) { self.end.write().unwrap().prev = v; } } impl<T> LinkedList<T> { #[inline] fn data_mut(&mut self) -> &mut UnmoveableLinkedList<T> { unsafe { Pin::get_unchecked_mut(self.data.as_mut()) } } /// Creates an empty `LinkedList`. /// /// # Examples /// /// ``` /// use atlist_rs::LinkedList; /// /// let list: LinkedList<u32> = LinkedList::new(); /// ``` #[inline] pub fn new() -> Self { let data = UnmoveableLinkedList::new(); LinkedList { data } } /// Returns the length of the `LinkedList`. /// /// This operation should compute in *O*(1) time. /// /// # Examples /// /// ``` /// use atlist_rs::LinkedList; /// /// let mut dl = LinkedList::new(); /// /// let _ = dl.push_front(2); /// assert_eq!(dl.len(), 1); /// /// let _ = dl.push_front(1); /// assert_eq!(dl.len(), 2); /// /// let _ = dl.push_back(3); /// assert_eq!(dl.len(), 3); /// ``` #[inline] pub fn len(&self) -> usize { self.data.len } /// Returns `true` if the `LinkedList` is empty. /// /// This operation should compute in *O*(1) time. /// /// # Examples /// /// ``` /// use atlist_rs::LinkedList; /// /// let mut dl = LinkedList::new(); /// assert!(dl.is_empty()); /// /// let _ = dl.push_front("foo"); /// assert!(!dl.is_empty()); /// ``` #[inline] pub fn is_empty(&self) -> bool { 0 == self.data.len } /// Removes all elements from the `LinkedList`. /// /// This operation should compute in *O*(*n*) time. /// /// # Examples /// /// ``` /// use atlist_rs::{LinkedList, LinkedListError}; /// /// let mut dl = LinkedList::new(); /// /// dl.push_front(2); /// dl.push_front(1); /// assert_eq!(dl.len(), 2); /// assert_eq!(*dl.front().unwrap(), 1); /// /// dl.clear(); /// assert_eq!(dl.len(), 0); /// assert_eq!(dl.front(), Err(LinkedListError::Empty)); /// ``` #[inline] pub fn clear(&mut self) { *self = Self::new(); } /// Provides a forward iterator. /// /// # Examples /// /// ``` /// use atlist_rs::LinkedList; /// /// let mut list: LinkedList<u32> = LinkedList::new(); /// /// let _ = list.push_back(0); /// let _ = list.push_back(1); /// let _ = list.push_back(2); /// /// let mut iter = list.iter(); /// assert_eq!(*iter.next().unwrap(), 0); /// assert_eq!(*iter.next().unwrap(), 1); /// assert_eq!(*iter.next().unwrap(), 2); /// assert_eq!(iter.next(), None); /// ``` #[inline] pub fn iter(&self) -> Iter<T> { self.iter_front() } /// Provides a forward iterator. /// /// # Examples /// /// ``` /// use atlist_rs::LinkedList; /// use std::cell::RefCell; /// /// let mut list: LinkedList<RefCell<u32>> = LinkedList::new(); /// /// let _ = list.push_back(RefCell::new(0)); /// let _ = list.push_back(RefCell::new(1)); /// let _ = list.push_back(RefCell::new(2)); /// /// for element in list.iter_mut() { /// *(*element).borrow_mut() += 10; /// } /// /// let mut iter = list.iter_mut(); /// assert_eq!(*(*iter.next().unwrap()).borrow(), 10); /// assert_eq!(*(*iter.next().unwrap()).borrow(), 11); /// assert_eq!(*(*iter.next().unwrap()).borrow(), 12); /// assert_eq!(iter.next(), None); /// ``` #[inline] pub fn iter_mut(&mut self) -> IterMut<T> { self.iter_mut_front() } /// Provides a iterator at the front element. /// /// The iterator is pointing to the "ghost" non-element if the list is empty. #[inline] pub fn iter_front(&self) -> Iter<T> { if let Some(head) = self.data.get_head() { Iter::from(unsafe { head.as_ref() }) } else { Iter::from_weak(Arc::downgrade(&self.data.end)) } } /// Provides a iterator at the back element. /// /// The iterator is pointing to the "ghost" non-element if the list is empty. #[inline] pub fn iter_back(&self) -> Iter<T> { if let Some(tail) = self.data.get_tail() { Iter::from(unsafe { tail.as_ref() }) } else { Iter::from_weak(Arc::downgrade(&self.data.end)) } } /// Provides a iterator with editing operations at the front element. /// /// The iterator is pointing to the "ghost" non-element if the list is empty. #[inline] pub fn iter_mut_front(&mut self) -> IterMut<T> { if let Some(head) = self.data.get_head() { IterMut::from(unsafe { head.as_ref() }) } else { IterMut::from_weak(Arc::downgrade(&self.data.end)) } } /// Provides a iterator with editing operations at the back element. /// /// The iterator is pointing to the "ghost" non-element if the list is empty. #[inline] pub fn iter_mut_back(&mut self) -> IterMut<T> { if let Some(tail) = self.data.get_tail() { IterMut::from(unsafe { tail.as_ref() }) } else { IterMut::from_weak(Arc::downgrade(&self.data.end)) } } /// Adds an element first in the list. /// /// This operation should compute in *O*(1) time. pub fn push_front(&mut self, elt: T) -> LinkedListResult<()> { let node = NodeEntry::new(elt, &mut self.data); self.data_mut().push_front_node(node) } /// Removes the first element and returns it, or `None` if the list is /// empty. /// /// This operation should compute in *O*(1) time. pub fn pop_front(&mut self) -> LinkedListResult<LinkedListItem<T>> { let n = self.data_mut().pop_front_node()?; let ret = n.read()?; if ret.element.is_none() { return Err(LinkedListError::IteratorNotInList); } Ok(ret.element.as_ref().unwrap().clone()) } /// Appends an element to the back of a list. /// /// This operation should compute in *O*(1) time. pub fn push_back(&mut self, elt: T) -> LinkedListResult<()> { let node = NodeEntry::new(elt, &mut self.data); self.data_mut().push_back_node(node) } /// Removes the last element from a list and returns it, or `None` if /// it is empty. /// /// This operation should compute in *O*(1) time. pub fn pop_back(&mut self) -> LinkedListResult<LinkedListItem<T>> { let n = self.data_mut().pop_back_node()?; let ret = n.read()?; if ret.element.is_none() { return Err(LinkedListError::IteratorNotInList); } Ok(ret.element.as_ref().unwrap().clone()) } /// Provides a reference to the front element, or `None` if the list is /// empty. /// /// # Examples /// /// ``` /// use atlist_rs::{LinkedList, LinkedListError}; /// /// let mut dl = LinkedList::new(); /// assert_eq!(dl.front(), Err(LinkedListError::Empty)); /// /// let _ = dl.push_front(1); /// assert_eq!(*dl.front().unwrap(), 1); /// ``` #[inline] pub fn front(&self) -> LinkedListResult<LinkedListItem<T>> { if let Some(head) = self.data.get_head() { unsafe { head.as_ref() } .read() .map_err(|x| x.into()) .map(|x| x.element.as_ref().unwrap().clone()) } else { Err(LinkedListError::Empty) } } /// Provides a reference to the back element, or `None` if the list is /// empty. /// /// # Examples /// /// ``` /// use atlist_rs::{LinkedList, LinkedListError}; /// /// let mut dl = LinkedList::new(); /// assert_eq!(dl.back(), Err(LinkedListError::Empty)); /// /// let _ = dl.push_back(1); /// assert_eq!(*dl.back().unwrap(), 1); /// ``` #[inline] pub fn back(&self) -> LinkedListResult<LinkedListItem<T>> { if let Some(tail) = self.data.get_tail() { unsafe { tail.as_ref() } .read() .map_err(|x| x.into()) .map(|x| x.element.as_ref().unwrap().clone()) } else { Err(LinkedListError::Empty) } } /// Returns `true` if the `LinkedList` contains an element equal to the /// given value. /// /// # Examples /// /// ``` /// use atlist_rs::{LinkedList, LinkedListError}; /// /// let mut list: LinkedList<u32> = LinkedList::new(); /// let mut another_list: LinkedList<u32> = LinkedList::new(); /// /// let _ = list.push_back(0); /// let _ = list.push_back(1); /// let _ = another_list.push_back(2); /// /// assert_eq!(list.contains_iter(&list.iter()), Ok(())); /// assert_eq!(list.contains_iter(&another_list.iter()), Err(LinkedListError::IteratorNotInList)); /// ``` #[inline] pub fn contains_iter(&self, x: &Iter<T>) -> LinkedListResult<()> { self.data.contains_iter(&x).map(|_| ()) } /// Returns `true` if the `LinkedList` contains an element equal to the /// given value. /// /// # Examples /// /// ``` /// use atlist_rs::{LinkedList, LinkedListError}; /// /// let mut list: LinkedList<u32> = LinkedList::new(); /// let mut another_list: LinkedList<u32> = LinkedList::new(); /// /// let _ = list.push_back(0); /// let _ = list.push_back(1); /// let _ = another_list.push_back(2); /// /// let iter = list.iter_mut(); /// let another_iter = another_list.iter_mut(); /// assert_eq!(list.contains_iter_mut(&iter), Ok(())); /// assert_eq!(list.contains_iter_mut(&another_iter), Err(LinkedListError::IteratorNotInList)); /// ``` #[inline] pub fn contains_iter_mut(&self, x: &IterMut<T>) -> LinkedListResult<()> { self.data.contains_iter_mut(&x).map(|_| ()) } /// Inserts a new element into the `LinkedList` before the current one. /// /// If the cursor is pointing at the "ghost" non-element then the new element is /// inserted at the end of the `LinkedList`. /// /// Returns the iterator of inserted value if success, or error if failed #[inline] pub fn insert_before(&mut self, iter: &IterMut<T>, elt: T) -> LinkedListResult<IterMut<T>> { let current = self.data.contains_iter_mut(&iter)?; if current.current_is_end { self.push_back(elt)?; return Ok(self.iter_mut_back()); } let new_node = NodeEntry::new(elt, &mut self.data); self.data_mut() .splice_node(current.prev, Some(current.current), new_node) } /// Inserts a new element into the `LinkedList` after the current one. /// /// If the cursor is pointing at the "ghost" non-element then the new element is /// inserted at the front of the `LinkedList`. /// /// Returns the iterator of inserted value if success, or error if failed #[inline] pub fn insert_after(&mut self, iter: &IterMut<T>, elt: T) -> LinkedListResult<IterMut<T>> { let current = self.data.contains_iter_mut(&iter)?; if current.current_is_end { self.push_front(elt)?; return Ok(self.iter_mut_front()); } let new_node = NodeEntry::new(elt, &mut self.data); self.data_mut() .splice_node(Some(current.current), current.next, new_node) } /// Removes the current iterator from the `LinkedList`. /// /// The element that was removed is returned, the iterator will point to /// the "ghost" non-element. /// /// If the iterator is currently pointing to the "ghost" non-element then /// no element is removed and `Err(LinkedListError::IteratorNotInList)` is /// returned. #[inline] pub fn remove_iter_mut( &mut self, iter: &mut IterMut<T>, ) -> LinkedListResult<LinkedListItem<T>> { self.data_mut().remove_iter(iter) } } impl<T> Default for LinkedList<T> { /// Creates an empty `LinkedList<T>`. #[inline] fn default() -> Self { Self::new() } } impl<T> Drop for UnmoveableLinkedList<T> { fn drop(&mut self) { struct DropGuard<'a, T>(&'a mut UnmoveableLinkedList<T>); impl<'a, T> Drop for DropGuard<'a, T> { fn drop(&mut self) { // Continue the same loop we do below. This only runs when a destructor has // panicked. If another one panics this will abort. while self.0.pop_front_node().is_ok() {} } } while let Ok(node) = self.pop_front_node() { let guard = DropGuard(self); drop(node); mem::forget(guard); } } } impl<T> FromIterator<T> for LinkedList<T> { fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self { let mut list = Self::new(); list.extend(iter); list } } impl<T> IntoIterator for &LinkedList<T> { type Item = LinkedListItem<T>; type IntoIter = Iter<T>; fn into_iter(self) -> Iter<T> { self.iter() } } impl<T> IntoIterator for &mut LinkedList<T> { type Item = LinkedListItem<T>; type IntoIter = IterMut<T>; fn into_iter(self) -> IterMut<T> { self.iter_mut() } } impl<T> Extend<T> for LinkedList<T> { fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) { iter.into_iter().for_each(move |elt| { let _ = self.push_back(elt); }); } #[cfg(feature = "nightly")] #[inline] fn extend_one(&mut self, elem: T) { let _ = self.push_back(elem); } } impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList<T> { fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) { iter.into_iter().cloned().for_each(move |elt| { let _ = self.push_back(elt); }); } #[cfg(feature = "nightly")] #[inline] fn extend_one(&mut self, &elem: &'a T) { let _ = self.push_back(elem); } } impl<T: PartialEq> PartialEq for NodeEntry<T> { fn eq(&self, other: &Self) -> bool { self.element.as_ref() == other.element.as_ref() } } impl<T: Eq> Eq for NodeEntry<T> {} fn _core_cmp_op_eq_list<T: PartialEq, CF>( left: &LinkedList<T>, right: &LinkedList<T>, mut cmp_op: CF, ) -> bool where CF: FnMut(&T, &T) -> bool, { let mut left_iter = left.iter(); let mut right_iter = right.iter(); loop { loop { let x = match left_iter.next() { None => return right_iter.next().is_none(), Some(val) => val, }; let y = match right_iter.next() { None => return false, Some(val) => val, }; if !cmp_op(x.as_ref(), y.as_ref()) { return false; } } } } impl<T: PartialEq> PartialEq for LinkedList<T> { fn eq(&self, other: &Self) -> bool { self.len() == other.len() && _core_cmp_op_eq_list(&self, &other, |x, y| x == y) } } impl<T: Eq> Eq for LinkedList<T> {} fn _core_cmp_op_partial_cmp_by_list<T: PartialOrd, CF>( left: &LinkedList<T>, right: &LinkedList<T>, mut partial_cmp: CF, ) -> Option<Ordering> where CF: FnMut(&T, &T) -> Option<Ordering>, { let mut left_iter = left.iter(); let mut right_iter = right.iter(); loop { let x = match left_iter.next() { None => { if right_iter.next().is_none() { return Some(Ordering::Equal); } else { return Some(Ordering::Less); } } Some(val) => val, }; let y = match right_iter.next() { None => return Some(Ordering::Greater), Some(val) => val, }; match partial_cmp(x.as_ref(), y.as_ref()) { Some(Ordering::Equal) => (), non_eq => return non_eq, } } } impl<T: PartialOrd> PartialOrd for LinkedList<T> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { _core_cmp_op_partial_cmp_by_list(&self, &other, |x, y| x.partial_cmp(y)) } } fn _core_cmp_op_cmp_by_list<T: Ord, CF>( left: &LinkedList<T>, right: &LinkedList<T>, mut cmp_op: CF, ) -> Ordering where CF: FnMut(&T, &T) -> Ordering, { let mut left_iter = left.iter(); let mut right_iter = right.iter(); loop { let x = match left_iter.next() { None => { if right_iter.next().is_none() { return Ordering::Equal; } else { return Ordering::Less; } } Some(val) => val, }; let y = match right_iter.next() { None => return Ordering::Greater, Some(val) => val, }; match cmp_op(x.as_ref(), y.as_ref()) { Ordering::Equal => (), non_eq => return non_eq, } } } impl<T: Ord> Ord for LinkedList<T> { #[inline] fn cmp(&self, other: &Self) -> Ordering { _core_cmp_op_cmp_by_list(&self, &other, |x, y| x.cmp(y)) } } impl<T: Clone> Clone for LinkedList<T> { fn clone(&self) -> Self { let mut ret = LinkedList::new(); for elem in self { let _ = ret.push_back(elem.as_ref().clone()); } ret } fn clone_from(&mut self, other: &Self) { let mut iter_other = other.iter(); while self.len() > other.len() { let _ = self.pop_back(); } for (elem, elem_other) in self.iter_mut().zip(&mut iter_other) { let dst = unsafe { &mut *(Arc::as_ptr(&elem) as *mut T) }; dst.clone_from(elem_other.as_ref()); } for elem in iter_other { let _ = self.push_back(elem.deref().clone()); } } } impl<T: fmt::Debug> fmt::Debug for LinkedList<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_list().entries(self).finish() } } impl<T: Hash> Hash for LinkedList<T> { fn hash<H: Hasher>(&self, state: &mut H) { self.len().hash(state); for elem in self { elem.as_ref().hash(state); } } } fn _core_cmp_op_weak<T: PartialEq, CF, EF>( left: &Weak<RwLock<NodeEntry<T>>>, right: &Weak<RwLock<NodeEntry<T>>>, mut cmp_op: CF, mut eq_op: EF, ) -> bool where CF: FnMut(&NodeEntry<T>, &NodeEntry<T>) -> bool, EF: FnMut() -> Option<bool>, { if Weak::ptr_eq(&left, &right) { if let Some(r) = eq_op() { return r; } } let left_ptr = left.upgrade(); let right_ptr = right.upgrade(); if left_ptr.is_none() && right_ptr.is_none() { if let Some(r) = eq_op() { return r; } } let left_ptr = left_ptr.unwrap(); let right_ptr = right_ptr.unwrap(); let left_node = if let Ok(g) = left_ptr.read() { g } else { return false; }; let right_node = if let Ok(g) = right_ptr.read() { g } else { return false; }; cmp_op(&left_node, &right_node) } #[inline] fn _core_cmp_eq_weak<T: PartialEq>( left: &Weak<RwLock<NodeEntry<T>>>, right: &Weak<RwLock<NodeEntry<T>>>, ) -> bool { _core_cmp_op_weak(left, right, |x, y| x == y, || Some(true)) } impl<T: PartialEq> PartialEq for Iter<T> { fn eq(&self, other: &Self) -> bool { _core_cmp_eq_weak(&self.node, &other.node) } } impl<T: PartialEq> PartialEq<IterMut<T>> for Iter<T> { fn eq(&self, other: &IterMut<T>) -> bool { _core_cmp_eq_weak(&self.node, &other.node) } } impl<T: PartialEq> Eq for Iter<T> {} impl<T: PartialEq> PartialEq for IterMut<T> { fn eq(&self, other: &Self) -> bool { _core_cmp_eq_weak(&self.node, &other.node) } } impl<T: PartialEq> PartialEq<Iter<T>> for IterMut<T> { fn eq(&self, other: &Iter<T>) -> bool { _core_cmp_eq_weak(&self.node, &other.node) } } impl<T: PartialEq> Eq for IterMut<T> {} impl<T> From<&Iter<T>> for IterMut<T> { fn from(iter: &Iter<T>) -> IterMut<T> { IterMut::from_weak(iter.node.clone()) } } impl<T> From<Iter<T>> for IterMut<T> { fn from(iter: Iter<T>) -> IterMut<T> { IterMut::from_weak(iter.node) } } impl<T> From<&IterMut<T>> for Iter<T> { fn from(iter: &IterMut<T>) -> Iter<T> { Iter::from_weak(iter.node.clone()) } } impl<T> From<IterMut<T>> for Iter<T> { fn from(iter: IterMut<T>) -> Iter<T> { Iter::from_weak(iter.node) } } // unsafe impl<T> !marker::Unpin for UnmoveableLinkedList<T> {} unsafe impl<T: marker::Sync + marker::Send> marker::Send for UnmoveableLinkedList<T> {} unsafe impl<T: marker::Sync + marker::Send> marker::Sync for UnmoveableLinkedList<T> {} unsafe impl<T: marker::Sync + marker::Send> marker::Send for Iter<T> {} unsafe impl<T: marker::Sync + marker::Send> marker::Sync for Iter<T> {} unsafe impl<T: marker::Sync + marker::Send> marker::Send for IterMut<T> {} unsafe impl<T: marker::Sync + marker::Send> marker::Sync for IterMut<T> {} <file_sep>/CHANGELOG.md # Changelog ## v0.2.1 - Add document, examples, unit tests and coverage test. ## v0.2.0 - All basic APIs are finished. ## v0.1.0 - Initial release.
e514ce8b04d04ec7c5411b7398e288abd87f3672
[ "Markdown", "Rust", "TOML" ]
5
Rust
atframework/atlist-rs
86cce793d0263e449b5759a9ecb62b8c8a026db0
546739d7ae6a05f968832ba617e604b53d67607d
refs/heads/master
<repo_name>narmadha1998/atmm<file_sep>/application/controllers/User.php <?php /** * Description of About * * @author VidhyaPrakash */ if (!defined('BASEPATH')) { exit('No direct script access allowed'); } class User extends MY_Controller { public function __construct() { parent::__construct(); } public function index() { $this->render("dashboard", get_defined_vars()); } public function postcomplaints() { $this->render("postcomplaints", get_defined_vars()); } public function PostComplaintSave() { $postData = $this->input->post(); if ($this->form_validation("usercomplaint")): $condition = array("complaintsid" => ""); $DBData = array( "comp_usr_ref" => $_SESSION['UserId'], "comp_comments" => $postData['comments'] ); $response = $this->Adminmodel->AllInsert($condition, $DBData, "", "comp"); if (!empty($response)): $this->session->set_flashdata('ME_SUCCESS', 'Complaint Filed Successfully'); else: $this->session->set_flashdata('ME_ERROR', 'Data not Saved. Kindly Re Enter'); endif; else: $this->session->set_flashdata('ME_ERROR', "Form Validation Failed"); endif; redirect($_SERVER['HTTP_REFERER']); } public function users_cases_ajax_list($options = null) { switch (strtolower($options)) { case "cases": $Condition = array("userid" => $_SESSION['UserId']); $TableListname = "case"; $ColumnOrder = array('fir_no', 'victimname', 'victimmobile', 'offendername', 'offencedate', 'case_status_name'); $ColumnSearch = array('fir_no', 'victimname', 'victimmobile'); $OrderBy = array('caseid' => 'desc'); break; case "solvedcases": $Condition = array("casestatus" => '2', "userid" => $_SESSION['UserId']); $TableListname = "case"; $ColumnOrder = array('fir_no', 'victimname', 'victimmobile', 'offendername', 'offencedate', 'case_status_name'); $ColumnSearch = array('fir_no', 'victimname', 'victimmobile', 'case_status_name'); $OrderBy = array('caseid' => 'desc'); break; case "pendingcases": $Condition = array("casestatus" => '3', "userid" => $_SESSION['UserId']); $TableListname = "case"; $ColumnOrder = array('fir_no', 'victimname', 'victimmobile', 'offendername', 'offencedate', 'case_status_name'); $ColumnSearch = array('fir_no', 'victimname', 'victimmobile', 'case_status_name'); $OrderBy = array('caseid' => 'desc'); break; default: $Condition = array(); break; } $list = $this->Adminmodel->get_datatables($TableListname, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, true); $data = array(); $no = $_POST['start']; foreach ($list as $logNotice) { $no++; $row = array(); $row[] = $logNotice->fir_no; $row[] = $logNotice->victimname; $row[] = $logNotice->victimmobile; $row[] = $logNotice->offendername; $row[] = $logNotice->offencedate; $row[] = $logNotice->case_status_name; //add html for action $row[] = '<a class="btn btn-xs btn-primary" href="' . base_url('index.php/' . $this->router->fetch_class() . '/casehistory/show/' . $logNotice->caseid) . '" title="Edit" target="_blank"><i class="fa fa-eye"></i> View</a>'; $data[] = $row; } $output = array( "draw" => $_POST['draw'], "recordsTotal" => $this->Adminmodel->count_all($TableListname, $Condition), "recordsFiltered" => $this->Adminmodel->count_filtered($TableListname, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, true), "data" => $data, ); //output to json format echo json_encode($output); } public function UpdatePassword() { $postData = $this->input->post(); if ($this->form_validation("password")): //add to database $condition = array("user_id" => "1", "password" => $postData['<PASSWORD>']); $select = "user_id as ID,email as EmailID"; $result = $this->Adminmodel->CSearch($condition, $select, "usr", "", "", "", "", "", "", ""); if (!empty($result)): $condition = array("user_id" => "1"); $DBData = array("password" => $postData['<PASSWORD>']); $response = $this->Adminmodel->AllInsert($condition, $DBData, "", "usr"); if (!empty($response)): $Message = $this->load->view("emaillayouts/userpasswordupdate", get_defined_vars(), true); $Subject = "Atrocity Case Management - Your password has been updated."; // $this->SendEmail(trim($result['EmailID']), $Message, "N", $Subject, ""); $this->session->set_flashdata('ME_SUCCESS', 'Password Changed Successfully'); else: $this->session->set_flashdata('ME_ERROR', 'Data not Saved. Kindly Re Enter'); endif; endif; else: $this->session->set_flashdata('ME_FORM', "ERROR"); endif; $this->load->view('homepage/dashboard'); } public function posted_complaints_ajax_list($options = null) { switch (strtolower($options)) { case "postedcomplaints": $Condition = array("complaintsid"=>""); $TableListname = "comp"; $ColumnOrder = array('comp_comments'); $ColumnSearch = array('comp_comments'); $OrderBy = array('complaintsid' => 'desc'); break; default: $Condition = array(); break; } $list = $this->Adminmodel->get_datatables($TableListname, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, true); $data = array(); $no = $_POST['start']; foreach ($list as $logNotice) { $no++; $row = array(); $row[] = $logNotice->comp_comments; //add html for action // $row[] = '<a class="btn btn-xs btn-primary" href="' . base_url('index.php/' . $this->router->fetch_class() . '/complaint/action/' . $logNotice->complaintsid) . '" title="Edit" target="_blank"><i class="fa fa-eye"></i> View</a>'; $data[] = $row; } $output = array( "draw" => $_POST['draw'], "recordsTotal" => $this->Adminmodel->count_all($TableListname, $Condition), "recordsFiltered" => $this->Adminmodel->count_filtered($TableListname, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, true), "data" => $data, ); //output to json format echo json_encode($output); } } <file_sep>/application/controllers/Police.php <?php /** * Description of About * * @author VidhyaPrakash */ if (!defined('BASEPATH')) { exit('No direct script access allowed'); } class Police extends MY_Controller { public function __construct() { parent::__construct(); $FunctionS = array("SendEmail"); if (!in_array($this->router->fetch_method(), $FunctionS)): if (strtolower($_SESSION["UserRoleName"]) != strtolower(__CLASS__)) { $this->Inti(__CLASS__); } endif; $userNameCnd = array("username" => $this->session->userdata("UserName")); $this->user = current($this->Adminmodel->CSearch($userNameCnd, "username as UserName", "usr")); $this->userid = current($this->Adminmodel->CSearch($userNameCnd, "user_id as UserId", "usr")); $this->userRole = current($this->Adminmodel->CSearch($userNameCnd, "role as UserRole", "usr", "", TRUE)); } public function index() { $usercount = $this->TotalUserCount(); $casecount = $this->TotalCaseCount(); $pendingcount = $this->PendingCaseCount(); $solvedcount = $this->SolvedCaseCount(); $newcase = $this->NewCaseShow(); $solvedcase = $this->SolvedCaseShow(); $pendingcase = $this->PendingCaseShow(); $this->render("dashboard", get_defined_vars()); } public function complaint($options = null, $id = null) { $render = ""; switch (strtolower($options)) { case "allcomplaints"; $render = "viewallcomplaints"; break; case "action"; $render = "complaintaction"; $VerifyStatus = $this->toVerifyAssigned($id); break; default: break; } $this->render($render, get_defined_vars()); } protected function toVerifyAssigned($id) { $condition = array("complaintsid" => $id); $select = "isassignedto as AssignedTo "; return $this->Adminmodel->CSearch($condition, $select, "comp"); } public function complaints_ajax_list($options = null) { switch (strtolower($options)) { case "complaints": $Condition = array(); $TableListname = "comp"; $ColumnOrder = array('name', 'city', 'mobilenumber', 'comp_comments'); $ColumnSearch = array('name', 'city'); $OrderBy = array('complaintsid' => 'desc'); break; default: $Condition = array(); break; } $list = $this->Adminmodel->get_datatables($TableListname, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, true); $data = array(); $no = $_POST['start']; foreach ($list as $logNotice) { $no++; $row = array(); $row[] = $logNotice->name; $row[] = $logNotice->city; $row[] = $logNotice->mobilenumber; $row[] = $logNotice->comp_comments; //add html for action $row[] = '<a class="btn btn-xs btn-primary" href="' . base_url('index.php/' . $this->router->fetch_class() . '/complaint/action/' . $logNotice->complaintsid) . '" title="Edit" target="_blank"><i class="fa fa-eye"></i> View</a>'; $data[] = $row; } $output = array( "draw" => $_POST['draw'], "recordsTotal" => $this->Adminmodel->count_all($TableListname, $Condition), "recordsFiltered" => $this->Adminmodel->count_filtered($TableListname, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, true), "data" => $data, ); //output to json format echo json_encode($output); } } <file_sep>/application/controllers/Organization.php <?php /** * Description of About * * @author VidhyaPrakash */ if (!defined('BASEPATH')) { exit('No direct script access allowed'); } class Organization extends MY_Controller { public function __construct() { parent::__construct(); if (!in_array($this->router->fetch_method(), $FunctionS)): if (strtolower($_SESSION["UserRoleName"]) != strtolower(__CLASS__)) { $this->Inti(__CLASS__); } endif; $userNameCnd = array("username" => $this->session->userdata("UserName")); $this->user = current($this->Adminmodel->CSearch($userNameCnd, "username as UserName", "usr")); $this->userid = current($this->Adminmodel->CSearch($userNameCnd, "user_id as UserId", "usr")); $this->userRole = current($this->Adminmodel->CSearch($userNameCnd, "role as UserRole", "usr", "", TRUE)); } public function index() { $usercount = $this->TotalUserCount(); $casecount = $this->TotalCaseCount(); $pendingcount = $this->PendingCaseCount(); $solvedcount = $this->SolvedCaseCount(); $newcase = $this->NewCaseShow(); $solvedcase = $this->SolvedCaseShow(); $pendingcase = $this->PendingCaseShow(); $profileurl = $this->ShowProfileImage($_SESSION['UserId']); $this->render("dashboard", get_defined_vars()); } } <file_sep>/application/language/marathi/message_lang.php <?php /* marathi language */ $lang['mobile_number'] = 'मोबाइल नंबर'; $lang['submit'] = 'सबमिट करा'; $lang['login'] = 'लॉगइन'; $lang['signup'] = 'साइनअप'; $lang['select'] = 'निवडा'; $lang['name'] = 'नाव'; $lang['select'] = 'निवडा'; $lang['email_id'] = 'ई - मेल आयडी'; $lang['user_name'] = 'वापरकर्त<NAME>'; $lang['address1'] = 'पत्ता 1'; $lang['address2'] = 'पत्ता 2'; $lang['city'] = 'शहर'; $lang['state'] = 'राज्य'; $lang['aadhaar_number'] = 'आधार नंबर'; $lang['country'] = 'देश'; $lang['password'] = '<PASSWORD>'; $lang['old_password'] = '<PASSWORD>'; $lang['new_password'] = '<PASSWORD>'; $lang['confirmation_password'] = '<PASSWORD>'; $lang['change_password'] = '<PASSWORD>ा'; $lang['edit_password'] = '<PASSWORD>ा'; $lang['profile_change'] = 'प्रोफाइल बदल'; $lang['edit_profile'] = 'प्रोफाईल संपादित करा'; $lang['personal_information'] = 'वैयक्तिक माहिती'; $lang['confirmation_password'] = '<PASSWORD>ा'; $lang['register'] = 'नोंदणी करा'; $lang['update_profile'] = 'प्रोफाइल अद्यतनित करा'; $lang['personal_information'] = 'वैयक्तिक माहिती'; $lang['all_users'] = 'सर्व वापरकर्ते'; /* Log Managment Starts Here */ $lang['log_mgnt'] = 'लॉग व्यवस्थापन'; $lang['more_info'] = 'और जानकारी'; $lang['notice'] = 'सूचना'; /* Log Managment Ends Here */ /* case management form */ $lang['cases'] = 'प्रकरणे'; $lang['new_cases'] = 'नवीन प्रकरण'; $lang['pending_cases'] = 'प्रलंबित प्रकरणे'; $lang['solved_cases'] = 'निराकरण प्रकरणी'; $lang['address'] = 'पत्ता '; $lang['registration_form'] = 'नोंदणी पत्रक'; $lang['case_details'] = 'केस तपशील'; $lang['case_id']='केस आयडी'; $lang['if_others'] = 'इतरांना तर'; $lang['case_description'] = 'केस विवरण'; $lang['victim_details'] = 'बळी तपशील'; $lang['case_management'] = 'विषयव्यवस्थापन'; $lang['offender_details'] = 'अपराधी तपशील'; $lang['offender_address'] = 'पत्ता'; $lang['victim_address'] = 'पत्ता'; $lang['gender'] = 'लिंग'; $lang['offence_date'] = 'गुन्हा तारीख'; $lang['victim_name'] = 'बळी चे नाव'; $lang['offender_name'] = 'अपराधाचे नाव'; $lang['age'] = 'वय'; $lang['status'] = 'स्थिती'; $lang['actions'] = 'क्रिया'; $lang['all_cases'] = 'सर्व प्रकरणांमध्ये'; $lang['male'] = 'नर'; $lang['female'] = 'महिला'; $lang['others'] = 'इतर'; $lang['select_gender'] = 'लिंग निवडा'; $lang['victimdob'] = 'जन्म तारीख'; $lang['fir_no'] = 'एफआयआर क्रमांक'; $lang['all_solvedcases'] = 'सर्व निराकरण प्रकरणी'; $lang['all_pendingcases'] = 'सर्व प्रलंबित प्रकरण'; $lang['offencename'] = 'गुन्हा नाव'; $lang['alloffenders'] = 'सर्व गुन्हेगार'; $lang['district'] = 'जिल्हा'; $lang['show'] = 'शो'; $lang['entries'] = 'नोंदी'; $lang['search'] = 'शोध'; $lang['postcomplaints'] = 'पोस्ट तक्रार'; $lang['complainthere'] = 'येथे तक्रार'; $lang['postyourcomplaintshere'] = 'येथे आपल्या तक्रारी पोस्ट करा'; /* case managment Ends Here */ /* case history starts here */ $lang['post'] = 'पोस्ट'; $lang['casehistory'] = 'प्रकरण इतिहास'; $lang['postedcomments'] = 'टिप्पण्या'; $lang['commenthere'] = 'येथे टिप्पणी'; $lang['typeyourcommenthere'] = 'येथे आपली टिप्पणी टाइप करा'; /* case history ends here */ /* Dashboard Starts Here */ $lang['dashboard'] = 'डॅशबोर्ड'; $lang['control_panel'] = 'नियंत्रण पॅनेल'; $lang['total_users'] = 'एकूण वापरकर्ते'; $lang['total_cases'] = 'एकूण प्रकरणे'; $lang['solved_cases'] = 'निराकरण प्रकरणी'; $lang['pending_cases'] = 'प्रलंबित प्रकरणे'; $lang['more_info'] = 'अधिक माहिती'; $lang['map'] = 'https://www.maharashtra.gov.in:443/Images/mapMaharashtraM.jpg'; /* district ends here */ /* Fir Format starts here */ $lang['send_to_sjsa'] = 'सामाजिक न्याय आणि विशेष मदत पाठवा'; $lang['fir_no'] = 'एफ आय आर संख्या'; $lang['fir_form'] = 'एफ आय आर फॉर्म'; $lang['police_station'] = 'पोलीस चौकी'; $lang['year'] = 'वर्ष'; $lang['date'] = 'तारीख'; $lang['act1'] = 'कृत्य1'; $lang['section1'] = 'विभाग1'; $lang['act2'] = 'कृत्य2'; $lang['section2'] = 'विभाग2'; $lang['offence_day'] = 'गुन्हा दिवस'; $lang['date_from'] = 'पासून तारीख'; $lang['date_to'] = 'तारीख ते'; $lang['time_from'] = 'पासून वेळ'; $lang['time_to'] = 'वेळ ते'; $lang['information_received_at_police_station'] = 'पोलीस ठाण्यात मिळालेली माहिती'; $lang['time'] = 'वेळ'; $lang['type_of_information'] = 'माहितीचा प्रकार'; $lang['place_of_occurrence'] = 'घटनेची जागा'; $lang['complianant/informant'] = 'तक्रार करणारा'; $lang['complianantname'] = 'अनुपालनदार नाव'; $lang['complianantdob'] = 'तक्रार करणारा जन्म'; $lang['nationality'] = 'राष्ट्रीयत्व'; $lang['occupation'] = 'व्यवसाय'; $lang['address'] = 'पत्ता'; $lang['suspectparticulars'] = 'संशय तपशील'; /* fir format ends here */ /* bread crumbs starts */ $lang['home'] = 'घर'; $lang['dashboard'] = 'डॅशबोर्ड'; $lang['cases'] = 'प्रकरणे'; $lang['new_cases'] = 'नवीन प्रकरण'; $lang['all_cases'] = 'सर्व प्रकरणांमध्ये'; $lang['all_offenders'] = 'सर्व गुन्हेगार'; $lang['all_pending_cases'] = 'सर्व प्रलंबित प्रकरणे'; $lang['all_solved_cases'] = 'सर्व निराकरण प्रकरणी'; $lang['logs'] = 'नोंदी'; $lang['all'] = 'सर्व'; $lang['errors'] = 'त्रुटी'; $lang['notices'] = 'सूचना'; $lang['warnings'] = 'इशारे'; $lang['show_notices'] = 'नोटीस दाखवा'; $lang['all_offences'] = 'सर्व अपराध'; $lang['users'] = 'वापरकर्ते'; $lang['all_users'] = 'सर्व वापरकर्ते'; $lang['mobile_number'] = 'मोबाइल नंबर'; /* bread crumbs ends here */ $lang['offender_offence'] = 'अपराधी गुन्हा'; $lang['offencereport'] = 'गुन्हा अहवाल'; $lang['act'] = 'गुन्हा कायदा'; $lang['compensation'] = 'भरपाई'; /* email */ $lang['mail_box'] = 'मेल बॉक्स'; $lang['compose'] = 'तयार '; $lang['folder'] = 'फोल्डर '; $lang['inbox'] = 'रचनारचना'; $lang['sent'] = 'पाठविले'; $lang['bold'] = 'ठळक'; $lang['italic'] = 'तिर्यक'; $lang['underline'] = 'सामान्य'; $lang['normal_text'] = 'मजकूर संलग्नक'; $lang['attachment'] = 'रेखांकन'; $lang['compose_new_message'] = 'नवीन संदेश तयार करा'; /* complaints */ $lang['complaint_action'] = 'तक्रार कारवाई'; $lang['police_details'] = 'पोलिस विवरण'; $lang['comments'] = 'टिप्पण्या'; $lang['complaint'] = 'तक्रार'; $lang['view_all_complaints'] = 'सर्व तक्रारी पहा'; $lang['ChoosePoliceStation'] = 'पोलीस स्टेशन निवडा'; /* Offences and Punishement Language starts here*/ $lang['off_one']="Putting any inedible or obnoxious substance [Section 3(1)(a) of the Act]"; /* Offences and Punishement Language ends here*/ /* navigator */ $lang['atrocity_tracking'] = 'अत्याचार ट्रॅकिंग'; $lang['dashboard'] = 'डॅशबोर्ड'; $lang['user_management'] = 'वापरकर्ता व्यवस्थापन'; $lang['case_management'] = 'विषयव्यवस्थापन'; $lang['logout'] = 'बाहेर पडणे'; $lang['message'] = 'बाहेर पडणे'; $lang['update'] = 'अद्यतन करा'; $lang['change_password'] = '<PASSWORD>ा'; $lang['update_profile'] = 'प्रोफाइल अद्यतनित करा'; $lang['offences_and_compensations'] = 'गुन्हे आणि नुकसानभरपाई'; $lang['post_complaints'] = 'तक्रार करा'; $lang['show_all_cases'] = 'सर्व प्रकरणं दाखवा'; $lang['register_new_case'] = 'नवीन केस नोंदवा'; $lang['show_all_offenders'] = 'सर्व अपराध्यांना दाखवा'; $lang['show_all_user_complaints'] = 'सर्व वापरकर्ता तक्रारी दाखवा';<file_sep>/application/views/error/login.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Atrocity Tracking and Management</title> <!-- Tell the browser to be responsive to screen width --> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <!-- Bootstrap 3.3.7 --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/bootstrap/dist/css/bootstrap.min.css') ?>"/> <!-- Font Awesome --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/font-awesome/css/font-awesome.min.css') ?>"/> <!-- Ionicons --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/Ionicons/css/ionicons.min.css') ?>"/> <!-- Theme style --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/css/AdminLTE.min.css') ?>"/> <!-- AdminLTE Skins. Choose a skin from the css/skins folder instead of downloading all of them to reduce the load. --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/css/skins/skin-blue-light .css') ?>"/> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <![endif]--> <!-- Google Font --> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic"> <script> var Geo = ""; function GeoLocaiton(Json) { Geo = Json; } var base_url = "<?= base_url(); ?>"; var role = "<?= $this->router->fetch_class(); ?>"; </script> </head> <?php $config = array("question_format" => "numeric", "operation" => "addition"); $this->mathcaptcha->init($config); $data = $this->mathcaptcha->get_question(); $breadcrumb = $this->uri->segment(3); ?> <body class="hold-transition login-page"> <div class="login-box"> <div class="login-logo"> <a href="../../index2.html">Atrocity Tracking Management System</a> </div> <!-- /.login-logo --> <div class="login-box-body"> <form action="../../index2.html" method="post"> <div class="form-group has-feedback"> <input type="email" class="form-control" placeholder="Email"> <span class="glyphicon glyphicon-envelope form-control-feedback"></span> </div> <div class="form-group has-feedback"> <input type="password" class="form-control" placeholder="Password"> <span class="glyphicon glyphicon-lock form-control-feedback"></span> </div> <div class="row"> <!-- /.col --> <div class="col-md-6 col-md-offset-3"> <button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button> </div> <!-- /.col --> </div> </form> <br/> <a href="#">I forgot my password</a><br> <a href="register.html" class="text-center">Register a new membership</a> </div> <!-- /.login-box-body --> </div> <!-- /.login-box --> <!-- BEGIN WEBSITE JAVASCRIPT --> <script src="<?= base_url('assets/plugins/jquery/dist/jquery.min.js') ?>"></script> <!-- Bootstrap 3.3.7 --> <script src="<?= base_url('assets/plugins/bootstrap/dist/js/bootstrap.min.js') ?>"></script> <!-- Bootstrap 3.3.7 --> <script src="<?= base_url('assets/plugins/iCheck/icheck.min.js') ?>"></script> <!-- END WEBSITE JAVASCRIPT --> </body> </html><file_sep>/database-04.03.sql -- MySQL dump 10.13 Distrib 5.7.17, for Win64 (x86_64) -- -- Host: 127.0.0.1 Database: atrocity -- ------------------------------------------------------ -- Server version 5.6.36 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `case_status_master` -- DROP TABLE IF EXISTS `case_status_master`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `case_status_master` ( `case_status_id` int(11) NOT NULL AUTO_INCREMENT, `case_status_name` varchar(45) NOT NULL, `case_status_shortname` varchar(5) NOT NULL, `case_status_display` varchar(1) DEFAULT 'Y', `createdby` varchar(45) DEFAULT NULL, `createdat` timestamp(2) NULL DEFAULT NULL, `createdip` varchar(45) DEFAULT NULL, `updatedby` varchar(45) DEFAULT NULL, `updatedat` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `updatedip` varchar(45) DEFAULT NULL, `deletedby` varchar(45) DEFAULT NULL, `deletedat` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `deletedip` varchar(45) DEFAULT NULL, PRIMARY KEY (`case_status_id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1 COMMENT='This table contains case status master information'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `case_status_master` -- LOCK TABLES `case_status_master` WRITE; /*!40000 ALTER TABLE `case_status_master` DISABLE KEYS */; INSERT INTO `case_status_master` VALUES (1,'Filed','F','Y','ADMIN',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL),(2,'Solved','S','Y','ADMIN',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL),(3,'Police Verification Pending','PV','Y','ADMIN',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL),(4,'Police Verification Completed','PVC','Y','ADMIN',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); /*!40000 ALTER TABLE `case_status_master` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `casehistory` -- DROP TABLE IF EXISTS `casehistory`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `casehistory` ( `casehistoryid` int(10) unsigned NOT NULL, `caseid` int(11) NOT NULL, `userid` int(11) NOT NULL, `casehistorydesc` varchar(255) NOT NULL, `caseshow` varchar(1) NOT NULL DEFAULT 'Y', `createdby` varchar(45) DEFAULT NULL, `createdat` timestamp(2) NULL DEFAULT NULL, `createdip` varchar(45) DEFAULT NULL, `updatedby` varchar(45) DEFAULT NULL, `updatedat` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `updatedip` varchar(45) DEFAULT NULL, `deletedby` varchar(45) DEFAULT NULL, `deletedat` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `deletedip` varchar(45) DEFAULT NULL, PRIMARY KEY (`casehistoryid`), KEY `case_ref_idx` (`caseid`), KEY `user_ref_idx` (`userid`), CONSTRAINT `case_ref` FOREIGN KEY (`caseid`) REFERENCES `cases` (`caseid`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `user_ref` FOREIGN KEY (`userid`) REFERENCES `users` (`user_id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='list contains all case history'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `casehistory` -- LOCK TABLES `casehistory` WRITE; /*!40000 ALTER TABLE `casehistory` DISABLE KEYS */; /*!40000 ALTER TABLE `casehistory` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `cases` -- DROP TABLE IF EXISTS `cases`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `cases` ( `caseid` int(11) NOT NULL AUTO_INCREMENT, `userid` int(11) NOT NULL, `offid` int(11) NOT NULL, `victimname` varchar(105) NOT NULL, `victimaddress` varchar(255) NOT NULL, `vicitmdob` varchar(45) NOT NULL, `victimgender` int(11) NOT NULL, `victimmobile` varchar(45) NOT NULL, `victimemail` varchar(45) NOT NULL, `victimaadhar` varchar(45) NOT NULL, `casedescription` varchar(255) NOT NULL, `caseimage` varchar(45) DEFAULT NULL, `casestatus` int(11) NOT NULL, `caseshow` varchar(1) NOT NULL DEFAULT 'Y', `otp` varchar(45) NOT NULL, `createdby` varchar(45) DEFAULT NULL, `createdat` timestamp(2) NULL DEFAULT NULL, `createdip` varchar(45) DEFAULT NULL, `updatedby` varchar(45) DEFAULT NULL, `updatedat` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `updatedip` varchar(45) DEFAULT NULL, `deletedby` varchar(45) DEFAULT NULL, `deletedat` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `deleteip` varchar(45) DEFAULT NULL, PRIMARY KEY (`caseid`), KEY `off_ref_idx` (`offid`), KEY `user_ref_idx` (`userid`,`victimgender`), KEY `gender_ref_idx` (`victimgender`), KEY `cases_status_ref_idx` (`casestatus`), CONSTRAINT `case_user_ref` FOREIGN KEY (`userid`) REFERENCES `users` (`user_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `cases_status_ref` FOREIGN KEY (`casestatus`) REFERENCES `case_status_master` (`case_status_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `gender_ref` FOREIGN KEY (`victimgender`) REFERENCES `gender` (`gender_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `off_ref` FOREIGN KEY (`offid`) REFERENCES `offences` (`offid`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Which contains all case details'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `cases` -- LOCK TABLES `cases` WRITE; /*!40000 ALTER TABLE `cases` DISABLE KEYS */; /*!40000 ALTER TABLE `cases` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `gender` -- DROP TABLE IF EXISTS `gender`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `gender` ( `gender_id` int(11) NOT NULL AUTO_INCREMENT, `gender_name` varchar(45) NOT NULL, `gender_shortname` varchar(5) NOT NULL, `gender_display` varchar(1) DEFAULT 'Y', `createdby` varchar(45) DEFAULT NULL, `createdat` timestamp(2) NULL DEFAULT NULL, `createdip` varchar(45) DEFAULT NULL, `updatedby` varchar(45) DEFAULT NULL, `updatedat` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `updatedip` varchar(45) DEFAULT NULL, `deletedby` varchar(45) DEFAULT NULL, `deletedat` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `deletedip` varchar(45) DEFAULT NULL, PRIMARY KEY (`gender_id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1 COMMENT='Master Table for Gender Details'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `gender` -- LOCK TABLES `gender` WRITE; /*!40000 ALTER TABLE `gender` DISABLE KEYS */; INSERT INTO `gender` VALUES (1,'Male','M','Y',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL),(2,'Female','F','Y',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL),(3,'Others','O','Y',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); /*!40000 ALTER TABLE `gender` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `logs` -- DROP TABLE IF EXISTS `logs`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `logs` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(5) DEFAULT NULL, `usermachineinfo` varchar(255) DEFAULT NULL, `errno` int(2) NOT NULL, `errtype` varchar(32) NOT NULL, `errstr` text NOT NULL, `errfile` varchar(255) NOT NULL, `errline` int(4) NOT NULL, `user_agent` varchar(120) NOT NULL, `ip_address` varchar(45) NOT NULL DEFAULT '0', `time` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `logs` -- LOCK TABLES `logs` WRITE; /*!40000 ALTER TABLE `logs` DISABLE KEYS */; /*!40000 ALTER TABLE `logs` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `offences_master` -- DROP TABLE IF EXISTS `offences_master`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `offences_master` ( `offid` int(11) NOT NULL AUTO_INCREMENT, `offname` varchar(255) NOT NULL, `offdescription` varchar(255) NOT NULL, `offshow` varchar(1) NOT NULL, `createdby` varchar(45) DEFAULT 'Y', `createdat` timestamp(2) NULL DEFAULT NULL, `createdip` varchar(45) DEFAULT NULL, `updatedby` varchar(45) DEFAULT NULL, `updatedat` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `updatedip` varchar(45) DEFAULT NULL, `deletedby` varchar(45) DEFAULT NULL, `deletedat` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `deletedip` varchar(45) DEFAULT NULL, PRIMARY KEY (`offid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Contains all offenses'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `offences_master` -- LOCK TABLES `offences_master` WRITE; /*!40000 ALTER TABLE `offences_master` DISABLE KEYS */; /*!40000 ALTER TABLE `offences_master` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `privatemessages` -- DROP TABLE IF EXISTS `privatemessages`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `privatemessages` ( `msgid` int(11) NOT NULL AUTO_INCREMENT, `msgfrom` int(11) NOT NULL, `msgto` int(11) NOT NULL, `msgdetails` varchar(255) DEFAULT NULL, `msgshow` varchar(1) DEFAULT 'Y', `createdby` varchar(45) DEFAULT NULL, `createdat` timestamp(2) NULL DEFAULT NULL, `createdip` varchar(45) DEFAULT NULL, `updatedby` varchar(45) DEFAULT NULL, `updatedat` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `updatedip` varchar(45) DEFAULT NULL, `deletedby` varchar(45) DEFAULT NULL, `deletedat` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `deletedip` varchar(45) DEFAULT NULL, PRIMARY KEY (`msgid`), KEY `message_from_user_idx` (`msgfrom`), KEY `message_to_user_idx` (`msgto`), CONSTRAINT `message_from_user` FOREIGN KEY (`msgfrom`) REFERENCES `users` (`user_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `message_to_user` FOREIGN KEY (`msgto`) REFERENCES `users` (`user_id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Contains all private messages in the forum'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `privatemessages` -- LOCK TABLES `privatemessages` WRITE; /*!40000 ALTER TABLE `privatemessages` DISABLE KEYS */; /*!40000 ALTER TABLE `privatemessages` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `roles` -- DROP TABLE IF EXISTS `roles`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `roles` ( `roleid` int(11) NOT NULL AUTO_INCREMENT, `rolename` varchar(45) NOT NULL, `roleslug` varchar(45) NOT NULL, `roledescription` varchar(45) NOT NULL, `roleshow` varchar(45) NOT NULL, `createdby` varchar(45) DEFAULT NULL, `createdat` timestamp(2) NULL DEFAULT NULL, `createdip` varchar(15) DEFAULT NULL, `updatedby` varchar(45) DEFAULT NULL, `updatedat` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `updatedip` varchar(45) DEFAULT NULL, `deletedby` varchar(45) DEFAULT NULL, `deletedat` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `deletedip` varchar(45) DEFAULT NULL, PRIMARY KEY (`roleid`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `roles` -- LOCK TABLES `roles` WRITE; /*!40000 ALTER TABLE `roles` DISABLE KEYS */; INSERT INTO `roles` VALUES (1,'User','user','User Details','','ADMIN',NULL,NULL,NULL,'2018-03-04 12:36:37',NULL,NULL,'2018-03-04 12:36:37',NULL),(2,'Police','police','Police Role','','ADMIN',NULL,NULL,NULL,'2018-03-04 12:36:37',NULL,NULL,'2018-03-04 12:36:37',NULL),(3,'Organization','orgaanization','NGO','','ADMIN',NULL,NULL,NULL,'2018-03-04 12:36:37',NULL,NULL,'2018-03-04 12:36:37',NULL),(4,'Guest','guest','Guest','','ADMIN',NULL,NULL,NULL,'2018-03-04 12:36:37',NULL,NULL,'2018-03-04 12:36:37',NULL); /*!40000 ALTER TABLE `roles` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `users` -- DROP TABLE IF EXISTS `users`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `users` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `role` int(5) NOT NULL, `name` varchar(75) NOT NULL, `username` varchar(45) NOT NULL, `password` varchar(45) NOT NULL, `address1` varchar(75) NOT NULL, `address2` varchar(75) NOT NULL, `city` varchar(45) NOT NULL, `state` varchar(45) NOT NULL, `country` varchar(45) NOT NULL, `mobilenumber` varchar(45) NOT NULL, `email` varchar(45) DEFAULT NULL, `aadhar` varchar(45) DEFAULT NULL, `lastlogin` varchar(45) DEFAULT NULL, `isactive` varchar(1) DEFAULT 'Y', `createdby` varchar(45) DEFAULT NULL, `createdat` timestamp(2) NULL DEFAULT NULL, `createdip` varchar(45) DEFAULT NULL, `updatedby` varchar(45) DEFAULT NULL, `updatedat` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `updatedip` varchar(45) DEFAULT NULL, `deletedby` varchar(45) DEFAULT NULL, `deletedat` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `deletedip` varchar(45) DEFAULT NULL, PRIMARY KEY (`user_id`), KEY `role_ref_idx` (`role`), CONSTRAINT `role_ref` FOREIGN KEY (`role`) REFERENCES `roles` (`roleid`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Contains List of Users'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `users` -- LOCK TABLES `users` WRITE; /*!40000 ALTER TABLE `users` DISABLE KEYS */; /*!40000 ALTER TABLE `users` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2018-03-04 21:20:30 <file_sep>/application/language/english/mathcaptcha_lang.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * Words for numbers 1 to 100 */ $lang['mathcaptcha_numeric_word_0'] = 'zero'; $lang['mathcaptcha_numeric_word_1'] = 'one'; $lang['mathcaptcha_numeric_word_2'] = 'two'; $lang['mathcaptcha_numeric_word_3'] = 'three'; $lang['mathcaptcha_numeric_word_4'] = 'four'; $lang['mathcaptcha_numeric_word_5'] = 'five'; $lang['mathcaptcha_numeric_word_6'] = 'six'; $lang['mathcaptcha_numeric_word_7'] = 'seven'; $lang['mathcaptcha_numeric_word_8'] = 'eight'; $lang['mathcaptcha_numeric_word_9'] = 'nine'; $lang['mathcaptcha_numeric_word_10'] = 'ten'; $lang['mathcaptcha_numeric_word_11'] = 'eleven'; $lang['mathcaptcha_numeric_word_12'] = 'twelve'; $lang['mathcaptcha_numeric_word_13'] = 'thirteen'; $lang['mathcaptcha_numeric_word_14'] = 'fourteen'; $lang['mathcaptcha_numeric_word_15'] = 'fifteen'; $lang['mathcaptcha_numeric_word_16'] = 'sixteen'; $lang['mathcaptcha_numeric_word_17'] = 'seventeen'; $lang['mathcaptcha_numeric_word_18'] = 'eighteen'; $lang['mathcaptcha_numeric_word_19'] = 'nineteen'; $lang['mathcaptcha_numeric_word_20'] = 'twenty'; $lang['mathcaptcha_numeric_word_21'] = 'twenty one'; $lang['mathcaptcha_numeric_word_22'] = 'twenty two'; $lang['mathcaptcha_numeric_word_23'] = 'twenty three'; $lang['mathcaptcha_numeric_word_24'] = 'twenty four'; $lang['mathcaptcha_numeric_word_25'] = 'twenty five'; $lang['mathcaptcha_numeric_word_26'] = 'twenty six'; $lang['mathcaptcha_numeric_word_27'] = 'twenty seven'; $lang['mathcaptcha_numeric_word_28'] = 'twenty eight'; $lang['mathcaptcha_numeric_word_29'] = 'twenty nine'; $lang['mathcaptcha_numeric_word_30'] = 'thirty'; $lang['mathcaptcha_numeric_word_31'] = 'thirty one'; $lang['mathcaptcha_numeric_word_32'] = 'thirty two'; $lang['mathcaptcha_numeric_word_33'] = 'thirty three'; $lang['mathcaptcha_numeric_word_34'] = 'thirty four'; $lang['mathcaptcha_numeric_word_35'] = 'thirty five'; $lang['mathcaptcha_numeric_word_36'] = 'thirty six'; $lang['mathcaptcha_numeric_word_37'] = 'thirty seven'; $lang['mathcaptcha_numeric_word_38'] = 'thirty eight'; $lang['mathcaptcha_numeric_word_39'] = 'thirty nine'; $lang['mathcaptcha_numeric_word_40'] = 'forty'; $lang['mathcaptcha_numeric_word_41'] = 'forty one'; $lang['mathcaptcha_numeric_word_42'] = 'forty two'; $lang['mathcaptcha_numeric_word_43'] = 'forty three'; $lang['mathcaptcha_numeric_word_44'] = 'forty four'; $lang['mathcaptcha_numeric_word_45'] = 'forty five'; $lang['mathcaptcha_numeric_word_46'] = 'forty six'; $lang['mathcaptcha_numeric_word_47'] = 'forty seven'; $lang['mathcaptcha_numeric_word_48'] = 'forty eight'; $lang['mathcaptcha_numeric_word_49'] = 'forty nine'; $lang['mathcaptcha_numeric_word_50'] = 'fifty'; $lang['mathcaptcha_numeric_word_51'] = 'fifty one'; $lang['mathcaptcha_numeric_word_52'] = 'fifty two'; $lang['mathcaptcha_numeric_word_53'] = 'fifty three'; $lang['mathcaptcha_numeric_word_54'] = 'fifty four'; $lang['mathcaptcha_numeric_word_55'] = 'fifty five'; $lang['mathcaptcha_numeric_word_56'] = 'fifty six'; $lang['mathcaptcha_numeric_word_57'] = 'fifty seven'; $lang['mathcaptcha_numeric_word_58'] = 'fifty eight'; $lang['mathcaptcha_numeric_word_59'] = 'fifty nine'; $lang['mathcaptcha_numeric_word_60'] = 'sixty'; $lang['mathcaptcha_numeric_word_61'] = 'sixty one'; $lang['mathcaptcha_numeric_word_62'] = 'sixty two'; $lang['mathcaptcha_numeric_word_63'] = 'sixty three'; $lang['mathcaptcha_numeric_word_64'] = 'sixty four'; $lang['mathcaptcha_numeric_word_65'] = 'sixty five'; $lang['mathcaptcha_numeric_word_66'] = 'sixty six'; $lang['mathcaptcha_numeric_word_67'] = 'sixty seven'; $lang['mathcaptcha_numeric_word_68'] = 'sixty eight'; $lang['mathcaptcha_numeric_word_69'] = 'sixty nine'; $lang['mathcaptcha_numeric_word_70'] = 'seventy'; $lang['mathcaptcha_numeric_word_71'] = 'seventy one'; $lang['mathcaptcha_numeric_word_72'] = 'seventy two'; $lang['mathcaptcha_numeric_word_73'] = 'seventy three'; $lang['mathcaptcha_numeric_word_74'] = 'seventy four'; $lang['mathcaptcha_numeric_word_75'] = 'seventy five'; $lang['mathcaptcha_numeric_word_76'] = 'seventy six'; $lang['mathcaptcha_numeric_word_77'] = 'seventy seven'; $lang['mathcaptcha_numeric_word_78'] = 'seventy eight'; $lang['mathcaptcha_numeric_word_79'] = 'seventy nine'; $lang['mathcaptcha_numeric_word_80'] = 'eighty'; $lang['mathcaptcha_numeric_word_81'] = 'eighty one'; $lang['mathcaptcha_numeric_word_82'] = 'eighty two'; $lang['mathcaptcha_numeric_word_83'] = 'eighty three'; $lang['mathcaptcha_numeric_word_84'] = 'eighty four'; $lang['mathcaptcha_numeric_word_85'] = 'eighty five'; $lang['mathcaptcha_numeric_word_86'] = 'eighty six'; $lang['mathcaptcha_numeric_word_87'] = 'eighty seven'; $lang['mathcaptcha_numeric_word_88'] = 'eighty eight'; $lang['mathcaptcha_numeric_word_89'] = 'eighty nine'; $lang['mathcaptcha_numeric_word_90'] = 'ninety'; $lang['mathcaptcha_numeric_word_91'] = 'ninety one'; $lang['mathcaptcha_numeric_word_92'] = 'ninety two'; $lang['mathcaptcha_numeric_word_93'] = 'ninety three'; $lang['mathcaptcha_numeric_word_94'] = 'ninety four'; $lang['mathcaptcha_numeric_word_95'] = 'ninety five'; $lang['mathcaptcha_numeric_word_96'] = 'ninety six'; $lang['mathcaptcha_numeric_word_97'] = 'ninety seven'; $lang['mathcaptcha_numeric_word_98'] = 'ninety eight'; $lang['mathcaptcha_numeric_word_99'] = 'ninety nine'; $lang['mathcaptcha_numeric_word_100'] = 'one hundred'; /** * Addition phrases for two numbers */ $lang['mathcaptcha_addition_2_1'] = 'What is !1 + !2?'; $lang['mathcaptcha_addition_2_2'] = 'Add together !1 and !2'; $lang['mathcaptcha_addition_2_3'] = 'What do you get if you add !1 to !2?'; $lang['mathcaptcha_addition_2_4'] = 'Add !1 to !2, what do you get?'; $lang['mathcaptcha_addition_2_5'] = 'What is the sum of !1 and !2?'; /** * Subraction phrases for two numbers * In this case !2 is always >= !1 */ $lang['mathcaptcha_subtraction_2_1'] = 'What is !2 minus !1?'; $lang['mathcaptcha_subtraction_2_2'] = 'Substract !1 from !2'; $lang['mathcaptcha_subtraction_2_3'] = 'Substract !1 from !2, what do you get?'; $lang['mathcaptcha_subtraction_2_4'] = 'What do you get if you substract !1 from !2?'; $lang['mathcaptcha_subtraction_2_5'] = 'What is the substraction !1 from !2?'; /** * Multiplication phrases for two numbers */ $lang['mathcaptcha_multiplication_2_1'] = 'What is !1 times !2?'; $lang['mathcaptcha_multiplication_2_2'] = 'What is !1 multiplied by !2?'; $lang['mathcaptcha_multiplication_2_3'] = 'Multiply !1 by !2, what do you get?'; $lang['mathcaptcha_multiplication_2_4'] = 'What do you get if you multiply !1 by !2?'; $lang['mathcaptcha_multiplication_2_5'] = 'What is the multiplication of !1 and !2?'; /** * Division phrases for two numbers * In this case !1 is a number we will divide */ $lang['mathcaptcha_division_2_1'] = 'Divide !1 by !2?'; $lang['mathcaptcha_division_2_2'] = 'What is !1 divided by !2?'; $lang['mathcaptcha_division_2_3'] = 'Divide !1 by !2, what do you get?'; $lang['mathcaptcha_division_2_4'] = 'What do yiu get if you divide !1 by !2?'; $lang['mathcaptcha_division_2_5'] = 'What is the division of !1 by !2?'; /* End of file mathcaptcha_lang.php */ /* Location: ./application/languages/english/mathcaptcha_lang.php */<file_sep>/README.md # atmm A website to register and to monitor the status of the cases which are registered under the Atrocity Cases <file_sep>/application/views/police/cases/showregistercase.php <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1><?= $this->lang->line('case_management') ?></h1> <ol class="breadcrumb"> <li><a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/index") ?>"><i class="fa fa-dashboard"></i><?= $this->lang->line('home') ?></a></li> <li class="active"><?= $this->lang->line('new_cases') ?></li> </ol> </section> <!-- Main content --> <section class="content"> <!-- Small boxes (Stat box) --> <div class="row"> <div class="col-md-12"> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title"><?= $this->lang->line('registeration_form') ?></h3> </div> <!-- /.box-header --> <form role="form" method="post" action="<?= base_url('index.php/' . strtolower($this->router->fetch_class()) . "/CaseRegisterSave") ?> "> <div class="box-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="FIR Number"><?= $this->lang->line('fir_no') ?> <span style="color: red ">*</span></label> <input class="form-control" id="FIR Number" placeholder="Enter FIR Number" type="text" name="fir_no" required="true"> </div> </div> </div> <h4><?= $this->lang->line('victim_details') ?></h4> <div class="row"> <div class="col-md-3"> <div class="form-group"> <label for="Victim Name"><?= $this->lang->line('name') ?> <span style="color: red ">*</span></label> <input class="form-control" id="Victim Name" placeholder="Enter name" type="text" name="victimname" required="true"> </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="gender"><?= $this->lang->line('gender') ?></label> <select class="form-control" id="gender" name="victimgender" placeholder="Select Gender" required="true"> <option>Select Gender</option> <?php foreach ($this->db->where(array("gender_display" => "Y"))->order_by("gender_name", "asc")->get('gender')->result() as $detail) { ?> <option value="<?= $detail->gender_id ?>"> <?= strtoupper($detail->gender_name) ?> </option> <?php } ?> </select> </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="email"><?= $this->lang->line('email_id') ?></label> <input class="form-control" id="email" placeholder="Enter Email id" type="email" name="victimemail" > </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="mobile no"><?= $this->lang->line('mobile_number') ?><span style="color: red ">*</span></label> <input type="text" class="form-control" id="mobile no" name="victimmobile" required="true" placeholder="Enter Mobile No"> </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="aadhar"><?= $this->lang->line('aadhaar_number') ?></label> <input type="text" class="form-control" id="aadhar" name="victimaadhar" placeholder="Enter Aadhaar No"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="Address"><?= $this->lang->line('victim_address') ?><span style="color: red ">*</span></label> <input type="text" class="form-control" id="Address" name="victimaddress" placeholder="Enter Address" required="true"> </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="dob"><?= $this->lang->line('victimdob') ?><span style="color: red ">*</span></label> <input type="date" class="form-control" id="dob" name="victimdob" placeholder="Enter date of birth" required="true"> </div> </div> </div> <div class="row"> <div class="col-md-3"> <div class="form-group"> <label for="state"><?= $this->lang->line('state') ?><span style="color: red ">*</span></label> <select class="form-control" id="state" name="victimstate" placeholder="Select State" required="true"> <option>Select State</option> <?php foreach ($this->db->where(array("show" => "Y"))->order_by("statename", "asc")->get('states')->result() as $detail) { ?> <option value="<?= $detail->stateid ?>"> <?= strtoupper($detail->statename) ?> </option> <?php } ?> </select> </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="district"><?= $this->lang->line('district') ?><span style="color: red ">*</span></label> <select class="form-control" id="vdistrict" name="victimdistrict" placeholder="Select District" required="true"> <option>Select District</option> <?php foreach ($this->db->where(array("districtshow" => "Y"))->order_by("districtname", "asc")->get('district')->result() as $detail) { ?> <option value="<?= $detail->dist_id ?>"> <?= strtoupper($detail->districtname) ?> </option> <?php } ?> </select> </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="city"><?= $this->lang->line('city') ?><span style="color: red ">*</span></label> <select class="form-control" id="vcity" name="victimcity" placeholder="Select City" required="true"> <option>Select City</option> </select> </div> </div> </div> <hr> <h4><?= $this->lang->line('offender_details') ?></h4> <div class="row"> <div class="col-md-3"> <div class="form-group"> <label for="offender name"><?= $this->lang->line('name') ?><span style="color: red ">*</span></label> <input type="text" class="form-control" id="offender name" name="offendername" placeholder="Enter Name" required="true"> </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="gender"><?= $this->lang->line('gender') ?></label> <select class="form-control" id="gender" name="offendergender" placeholder="Select Gender" required="true"> <option>Select Gender</option> <?php foreach ($this->db->where(array("gender_display" => "Y"))->order_by("gender_name", "asc")->get('gender')->result() as $detail) { ?> <option value="<?= $detail->gender_id ?>"> <?= strtoupper($detail->gender_name) ?> </option> <?php } ?> </select> </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="age"><?= $this->lang->line('age') ?><span style="color: red ">*</span></label> <input type="text" class="form-control" id="Address" name="offenderage" placeholder="Enter Age" required="true"> </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="mobile no"><?= $this->lang->line('mobile_number') ?></label> <input type="text" class="form-control" id="mobile no" name="offendermobile" placeholder="Enter Mobile No"> </div> </div> </div> <div class="row"> <div class="col-md-3"> <div class="form-group"> <label for="emailid"><?= $this->lang->line('email_id') ?></label> <input type="email" class="form-control" id="emailid" name="offenderemail" placeholder="Enter emailid"> </div> </div> <div class="col-md-9"> <div class="form-group"> <label for="Address"><?= $this->lang->line('offender_address') ?><span style="color: red ">*</span></label> <input type="text" class="form-control" id="Address" name="offenderaddress" placeholder="Enter Address" required="true"> </div> </div> </div> <div class="row"> <div class="col-md-3"> <div class="form-group"> <label for="state"><?= $this->lang->line('state') ?><span style="color: red ">*</span></label> <select class="form-control" id="state" name="offenderstate" placeholder="Select State" required="true"> <option>Select State</option> <?php foreach ($this->db->where(array("show" => "Y"))->order_by("statename", "asc")->get('states')->result() as $detail) { ?> <option value="<?= $detail->stateid ?>"> <?= strtoupper($detail->statename) ?> </option> <?php } ?> </select> </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="district"><?= $this->lang->line('district') ?><span style="color: red ">*</span></label> <select class="form-control" id="odistrict" name="offenderdistrict" placeholder="Select District" required="true"> <option>Select District</option> <?php foreach ($this->db->where(array("districtshow" => "Y"))->order_by("districtname", "asc")->get('district')->result() as $detail) { ?> <option value="<?= $detail->dist_id ?>"> <?= strtoupper($detail->districtname) ?> </option> <?php } ?> </select> </div> </div> <div class="col-md-3"> <div class="form-group"> <label for="city"><?= $this->lang->line('city') ?><span style="color: red ">*</span></label> <select class="form-control" id="ocity" name="offendercity" placeholder="Select City" required="true"> <option>Select City</option> </select> </div> </div> </div> <hr> <h4><?= $this->lang->line('case_details') ?><span style="color: red ">*</span></h4> <div class="row"> <div class="col-md-8"> <div class="form-group"> <label> </label> <select class="form-control select2 select2-hidden-accessible" style="width: 100%;" tabindex="-1" aria-hidden="true" name="offenece" required="true"> <option>Select offenses from List</option> <?php foreach ($this->db->where(array("offshow" => "Y"))->order_by("offid", "asc")->get('offences_master')->result() as $detail) { ?> <option value="<?= $detail->offid ?>"> <?= strtoupper($detail->offname) ?> </option> <?php } ?> </select> <span class="select2 select2-container select2-container--default select2-container--above" dir="ltr" style="width: 100%;"> <span class="selection"> <span class="select2-selection__arrow" role="presentation"> <b role="presentation"></b> </span> </span> </span> <span class="dropdown-wrapper" aria-hidden="true"> </span> </div> </div> <div class="col-md-4"> <div class="form-group"> <label><?= $this->lang->line('offence_date') ?><span style="color: red ">*</span></label> <input class="form-control" id="date" placeholder="date" type="date" name="offencedate" required="true"> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label><?= $this->lang->line('if_others') ?></label> <input class="form-control" id="others" placeholder="Others" type="text" name="ifothers"> </div> </div> </div> <br/> <div class="row"> <div class="form-group"> <div class="col-md-12"> <label><?= $this->lang->line('case_description') ?><span style="color: red ">*</span></label> <textarea class="form-control" rows="3" placeholder="Enter ..." name="casedescription" required="true"></textarea> </div> </div> </div><br/> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label><?= $this->lang->line('police_details') ?><span style="color: red ">*</span></label> <select class="form-control" id="police" name="policeassigned" placeholder="Choose Police Station" required="true"> <option>Choose Police Station</option> <?php foreach ($this->db->where(array("isactive" => "Y", "rolename" => "Police"))->order_by("username", "asc")->join("roles", "roleid=role")->get('users')->result() as $detail) { ?> <option value="<?= $detail->user_id ?>"> <?= $detail->username . " - " . $detail->rolename ?> </option> <?php } ?> </select> </div> </div> <div class="col-md-6"> <label><?= $this->lang->line('organisation_details') ?></label> <select class="form-control" id="organisation" name="organisationassigned" placeholder="Choose Organisation" required="true"> <option>Choose Organisation</option> <?php foreach ($this->db->where(array("isactive" => "Y", "rolename" => "Organization"))->order_by("username", "asc")->join("roles", "roleid=role")->get('users')->result() as $detail) { ?> <option value="<?= $detail->user_id ?>"> <?= $detail->username . " - " . $detail->rolename ?> </option> <?php } ?> </select> </div> </div> </div> <div class="box-footer"> <center> <div class="col-md-12"> <button type="submit" class="btn btn-primary"><?= $this->lang->line('submit') ?></button> </div></center> </div> </div> </form> </div> </div> </div> </section> <!-- /.content --> </div> <script type="text/javascript"> $("#vdistrict").on("change", function (event, r) { LastUrl = ""; AjaxCall("index.php/" + role + "/FetchCities", "id=" + $(this).val(), "vcity", "id"); }); $("#odistrict").on("change", function (event, r) { LastUrl = ""; AjaxCall("index.php/" + role + "/FetchCities", "id=" + $(this).val(), "ocity", "id"); }); </script> <file_sep>/application/helpers/randomgen_helper.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /* * function randomgen * */ function randomgen($min, $max, $quantity) { $numbers = range($min, $max); shuffle($numbers); return array_slice($numbers, 0, $quantity); } function calculateexp($months) { $year = floor($months / 12); if ($year > 1): $year = $year . " Years"; elseif ($year === 1): $year = $year . " Year"; else: $year = $year . " Year"; endif; $mth = $months % 12; if ($mth > 1): $mth = $mth . " Months"; elseif ($mth === 1): $mth = $mth . " Months"; else: $mth = ""; endif; return $year . " " . $mth; } function passwordhashencode($Password) { $options = array("cost" => 4); return password_hash($Password, PASSWORD_BCRYPT, $options); } function verifypassword($password, $hashPassword) { if (password_verify($password, $hashPassword)) { return true; } else { return false; } } function time_elapsed_string($datetime, $full = false) { $now = new DateTime; $ago = new DateTime($datetime); $diff = $now->diff($ago); $diff->w = floor($diff->d / 7); $diff->d -= $diff->w * 7; $string = array( 'y' => 'year', 'm' => 'month', 'w' => 'week', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ); foreach ($string as $k => &$v) { if ($diff->$k) { $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : ''); } else { unset($string[$k]); } } if (!$full) $string = array_slice($string, 0, 1); return $string ? implode(', ', $string) . ' ago' : 'just now'; }<file_sep>/application/views/police/casehistory/casehistory.php <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1><?= $this->lang->line('casehistory') ?></h1> <ol class="breadcrumb"> <li><a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/index") ?>"><i class="fa fa-dashboard"></i> <?= $this->lang->line('home') ?></a></li> <li><a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/cases/allcases") ?>"><?= $this->lang->line('cases') ?></a></li> <li class="active"><?= $this->lang->line('casehistory') ?></li> </ol> </section> <?php if (empty($casevictimdatabase['VictimName']) == 0): ?> <section class="content"> <div class="box"> <!-- /.box-header --> <div class="box-body"> <div class="row"> <div class="col-sm-6"> <div class="box-header"> <h3 class="box-title"><?= $this->lang->line('victim_details') ?></h3> </div> <table id="showallNotices" class="table table-bordered table-striped dataTable" role="grid" aria-describedby="example1_info"> <tbody> <tr> <td width="50%" style="line-height: 10px"><b><?= $this->lang->line('name') ?></b></td> <td width="50%" style="line-height: 10px"> <?= $casevictimdatabase['VictimName'] ?></td> </tr> <tr> <td width="50%" style="line-height: 10px"><b><?= $this->lang->line('gender') ?></b></td> <td width="50%" style="line-height: 10px"> <?= $casevictimdatabase['VictimGender'] ?></td> </tr> <tr> <td width="50%" style="line-height: 10px"> <b><?= $this->lang->line('mobile_number') ?></b></td> <td width="50%" style="line-height: 10px"> <?= $casevictimdatabase['VictimMobile'] ?></td> </tr> <tr> <td width="50%" style="line-height: 10px"><b><?= $this->lang->line('victimdob') ?></b> </td> <td width="50%" style="line-height: 10px"> <?= $casevictimdatabase['VictimDob'] ?></td> </tr> <tr> <td width="50%" style="line-height: 10px"><b><?= $this->lang->line('email_id') ?></b> </td> <td width="50%" style="line-height: 10px"> <?= $casevictimdatabase['VictimEmail'] ?></td> </tr> <tr> <td width="50%" style="line-height: 10px"> <b><?= $this->lang->line('victim_address') ?></b></td> <td width="50%" style="line-height: 10px"> <?= $casevictimdatabase['VictimAddress'] ?></td> </tr> <tr> <td width="50%" style="line-height: 10px"><b><?= $this->lang->line('state') ?></b></td> <td width="50%" style="line-height: 10px"> <?= $casevictimdatabase['VictimState'] ?></td> </tr> <tr> <td width="50%" style="line-height: 10px"><b><?= $this->lang->line('district') ?></b></td> <td width="50%" style="line-height: 10px"> <?= $casevictimdatabase['VictimDistrict'] ?></td> </tr> <tr> <td width="50%" style="line-height: 10px"><b><?= $this->lang->line('city') ?></b></td> <td width="50%" style="line-height: 10px"> <?= $casevictimdatabase['VictimCity'] ?></td> </tr> </table> </div> </centre> <div class="col-sm-6"> <div class="box-header"> <h3 class="box-title"><?= $this->lang->line('offender_details') ?></h3> </div> <table id="showallNotices" class="table table-bordered table-striped dataTable" role="grid" aria-describedby="example1_info"> <tbody> <tr> <td width="50%" style="line-height: 10px"><b><?= $this->lang->line('name') ?></b></td> <td width="50%" style="line-height: 10px"> <?= $caseoffenderdatabase['OffenderName'] ?></td> </tr> <tr> <td width="50%" style="line-height: 10px"><b><?= $this->lang->line('gender') ?></b></td> <td width="50%" style="line-height: 10px"> <?= $caseoffenderdatabase['OffenderGender'] ?></td> </tr> <tr> <td width="50%" style="line-height: 10px"> <b><?= $this->lang->line('offender_address') ?></b></td> <td width="50%" style="line-height: 10px"> <?= $caseoffenderdatabase['OffenderAddress'] ?></td> </tr> <tr> <td width="50%" style="line-height: 10px"><b><?= $this->lang->line('city') ?></b></td> <td width="50%" style="line-height: 10px"> <?= $caseoffenderdatabase['OffenderCity'] ?></td> </tr> <tr> <td width="50%" style="line-height: 10px"><b><?= $this->lang->line('state') ?></b></td> <td width="50%" style="line-height: 10px"> <?= $caseoffenderdatabase['OffenderState'] ?></td> </tr> <tr> <td width="50%" style="line-height: 10px"><b><?= $this->lang->line('fir_no') ?></b></td> <td width="50%" style="line-height: 10px"> <?= $casevictimdatabase['FirNumber'] ?></td> </tr><tr> <td width="50%" style="line-height: 10px"><b>Case Current Status</b></td> <td width="50%" style="line-height: 10px"> <?= $casevictimdatabase['CaseStatusName'] ?></td> </tr> </tbody> </table> <?php if ($casevictimdatabase['CaseStatus'] != 2): ?> <div class="row"> <div class="col-md-6"> <form method="post" action="<?= base_url('index.php/' . strtolower($this->router->fetch_class()) . "/CaseStatusSave") ?>"> <input type="hidden" name="caseid" value="<?= $casevictimdatabase['CaseID'] ?>"/> <div class="form-group"> <label for="exampleInputFile">Case Status ?</label> <select class="form-control" id="email" name="casestatus" placeholder="Select Mail ID" required="true"> <option>Select Status</option> <?php foreach ($this->db->where(array("case_status_display" => "Y"))->order_by("case_status_id", "asc")->get('case_status_master')->result() as $detail) { ?> <option value="<?= $detail->case_status_id ?>"> <?= $detail->case_status_name ?> </option> <?php } ?> </select> </div> <div class="form-group"> <button type="submit" class="btn btn-md btn-primary">Submit</button> </div> </form> </div> </div> <?php endif; ?> </div> </div> <div class="row"> <div class="col-md-6"> <div class="box box-solid box-primary"> <div class="box-header with-border"> <h3 class="box-title"><?= $this->lang->line('act') ?></h3> </div> <div class="box-body"> <blockquote class="pull-left"> <?= $casevictimdatabase['OffenceName'] ?> </blockquote> </div> </div> </div> <div class="col-md-6"> <div class="box box-solid box-info"> <div class="box-header with-border"> <h3 class="box-title"><?= $this->lang->line('compensation') ?></h3> </div> <div class="box-body"> <blockquote class="pull-left text-justify"> <?= $casevictimdatabase['Compensation'] ?> </blockquote> </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="box box-solid"> <div class="box-header with-border"> <h3 class="box-title"><?= $this->lang->line('case_description') ?></h3> </div> <div class="box-body"> <blockquote class="pull-left"> <?= $casevictimdatabase['CaseDescription'] ?> </blockquote> </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="box box-solid"> <div class="box-header with-border"> <h3 class="box-title"><?= $this->lang->line('postedcomments') ?></h3> </div> <ul class="timeline"> <!-- timeline item --> <?php foreach ($casecomments as $comments): ?> <li> <i class="fa fa-envelope bg-blue"></i> <div class="timeline-item"> <span class="time"><i class="fa fa-clock-o"></i> <?= time_elapsed_string($comments['CreatedOn']) ?></span> <h3 class="timeline-header"><a href="#"><?= $comments['CreatedBy'] . " ( " . $comments['RoleName'] . " ) " ?></a> posted a comment</h3> <div class="timeline-body"> <?= $comments ['CaseHistoryDesc'] ?> </div> <?php if ($comments['Attachment'] != null || (!empty($comments['Attachment']))): ?> <div class="timeline-footer"> <a class="btn btn-info btn-xs" href="<?= base_url('/assets/attachment/' . $comments['Attachment']) ?>" target="_blank">Attachment</a> </div> <?php endif; ?> </div> </li> <!-- END timeline item --> <?php endforeach; ?> </ul> </div> </div> </div> </div> </div> <div class="row"> <?php if ($casevictimdatabase['CaseStatus'] != 2): ?> <div class="col-md-12"> <div class="box"> <div class="box-header"> <h3 class="box-title"> <?= $this->lang->line('commenthere') ?> </h3> </div> <form method="post" action="<?= base_url('index.php/' . strtolower($this->router->fetch_class()) . "/CaseHistorySave") ?> " autocomplete="off" enctype="multipart/form-data"> <input type="hidden" name="caseid" value="<?= $casevictimdatabase['CaseID'] ?>"/> <div class="box-body pad"> <textarea class="textarea" placeholder="<?= $this->lang->line('typeyourcommenthere') ?>" name="casehistory" style="width: 100%; height: 100px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"></textarea> </div> <div class="box-footer"> <div class="pull-left"> <div class="form-group"> <label for="exampleInputFile">Image</label> <input type="file" id="exampleInputFile" name="file" accept="image/x-jpg,image/jpeg"> </div> </div> <div class="pull-right"> <button type="submit" class="btn btn-md btn-primary"><?= $this->lang->line('post') ?></button> </div> </div> </form> </div> </div> </div> <?php endif; ?> </section> <?php else: ?> <section class="content"> <div class="error-page"> <div class="error-content"> <h3><i class="fa fa-warning text-red"></i> Invalid Request</h3> </div> </div> <!-- /.error-page --></section> <?php endif; ?> </div><file_sep>/application/helpers/grid_helper.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /** * Flexigrid CodeIgniter implementation * * PHP version 5 * * @category CodeIgniter * @package Flexigrid CI * @author <NAME> (<EMAIL>) * @version 0.3 * Copyright (c) 2008 <NAME> (http://flexigrid.eyeviewdesign.com) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. */ if (!function_exists('build_datatable')) { function build_datatable($grid_id, $url, $ServerData) { //Basic propreties $grid_js = '<script type="text/javascript"> datatableUrl="' . $url . '" $(document).ready(function(){'; $grid_js .= '$("#' . $grid_id . '").DataTable({'; if (!empty($ServerData)) { $grid_js .= ' "ajax": { "url": "' . $url . '","data": Clinetdata },'; } else { $grid_js .= ' "ajax": "' . $url . '",'; } $grid_js .= ' "serverSide": true,'; // $grid_js .= ' "data": function(d){ d.mydata="data" },'; $grid_js .= ' "processing": true,"oLanguage": { "sSearch": "Search all columns:" },"sPaginationType": "full_numbers","dom": \'T<"clear">lfrtip\',"tableTools": { "sSwfPath": "' . base_url("assets/theme/js/plugins/datatables/copy_csv_xls_pdf.swf") . '" }'; $grid_js .= '}); });</script>'; return $grid_js; } } ?><file_sep>/application/models/Adminmodel.php <?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ class Adminmodel extends CI_Model { public function __construct() { parent::__construct(); $this->TableList = array("log" => "logs", "rol" => "roles", "usr" => "users", "casehis" => "casehistory", "case" => "cases", "off_mst" => "offender_master", "sts" => "states", "dist" => "district", "city" => "cities", "ca_st" => "case_status_master", "notf" => "notifications", "of_mst" => "offences_master", "pm" => "privatemessages", "fir" => "fir", "comp" => "complaints"); $this->SeqID = array("logs" => "id", "roles" => "roleid", "users" => "user_id", "casehistory" => "casehistoryid", "cases" => "caseid", "offender_master" => "offenderid", "states" => "stateid", "district" => "dist_id", "cities" => "cityid", "case_status_master" => "case_status_id", "notifications" => "noty_id", "offences_master" => "offid", "privatemessages" => "msgid", "fir" => "fir_id", "complaints" => "complaintsid"); } public function FetchData($Condition, $Select, $TableList, $SelectAll, $GroupBY, $OrderBY) { $TableName = $this->TableList[$TableList]; return $this->CSearch($Condition, $Select, $TableName, $SelectAll, $GroupBY, $OrderBY); } public function AllInsert($condition, $dataDB, $Select, $Tble) { return $this->Crud($condition, $dataDB, $Select, $Tble); } public function Crud($Condition, $DBdata, $Select, $TableList) { $IPAdress = ($this->input->ip_address() === "::1") ? "127.0.0.1" : $this->input->ip_address(); $TableName = $this->TableList[$TableList]; $CrudDetails = $this->CSearch($Condition, $Select, $TableName, null, False); $this->db->set($DBdata); if (!(empty($CrudDetails))) { $this->db->where($Condition); $this->db->set("updatedBy", $_SESSION["UserFullName"]); $this->db->set("updatedAt", "CURRENT_TIMESTAMP", false); $this->db->set("updatedIP", ip2long($IPAdress), false); $this->db->update($TableName); return $CrudDetails[$this->SeqID[$TableName]]; } else { $this->db->set($Condition); $this->db->set("createdBy", empty($_SESSION["UserFullName"]) ? NULL : $_SESSION["UserFullName"]); $this->db->set("createdAt", "CURRENT_TIMESTAMP", false); $this->db->set("createdIP", ip2long($IPAdress), false); $this->db->insert($TableName); return $this->db->insert_id(); } } public function CSearch($Condition, $Select, $TableName, $SelectAll, $JoinRequired, $JoinType, $Distinct, $Omit, $LeftJoin, $GroupBY, $orderBy) { $JoinType = NULL; $_TableName = $this->TableList[$TableName]; if (!empty($Select)) { $this->db->select($Select, FALSE); } if (!empty($_TableName)) { $TableName = $_TableName; } if ($JoinRequired) { $this->JoinData($TableName, $JoinType, $Omit, $LeftJoin); } if ($Distinct) { $this->db->distinct(); } if ($Condition) { $this->db->distinct($Condition); } if (!empty($Condition)) { $this->db->where($Condition); } if (!empty($GroupBY)) { $this->db->group_by($GroupBY); } if (!empty($orderBy)) { $this->db->order_by($orderBy, "desc"); } $Result = $this->db->get($TableName); if (empty($SelectAll)): return (empty($Result)) ? null : (array) $Result->row(); else: return (empty($Result)) ? null : (array) $Result->result_array(); endif; } protected function JoinData($TableName, $JoinType, $Omit, $LeftJoin) { switch ($TableName) { case "users": $JoinTable = array( "roles" => "roles.roleid=users.role", "cities" => "cities.cityid=users.city", "states" => "states.stateid=users.state", ); break; case "cases": $JoinTable = array( "users" => "users.user_id=cases.userid", "offences_master" => "offences_master.offid=cases.offid", "gender" => "gender.gender_id=cases.victimgender", "case_status_master" => "case_status_id=cases.casestatus", "district" => "district.dist_id=cases.victimdistrict", "cities" => "cities.cityid=cases.victimcity", "states" => "states.stateid=cases.victimstate", "offender_master" => "offender_master.offenderid=cases.offenderid", ); break; case "casehistory": $JoinTable = array( "cases" => "cases.caseid=casehistory.caseid", "users" => "users.user_id=casehistory.userid", "roles" => "roles.roleid=users.role" ); break; case "offender_master": $JoinTable = array( "gender" => "gender.gender_id=offender_master.offendergender", "states" => "states.stateid=offender_master.offenderstate", "cities" => "cities.cityid=offender_master.offendercity", "district" => "district.dist_id=offender_master.offenderdistrict", ); break; case "privatemessages": $JoinTable = array( "users" => "users.user_id=privatemessages.msgfrom", "users" => "users.user_id=privatemessages.msgto", ); break; case "complaints": $JoinTable = array( "users" => "users.user_id=complaints.comp_usr_ref", ); break; } if (!empty($JoinTable)) { foreach ($JoinTable as $key => $val) { if (!in_array($key, $Omit)) { $JoinType = (in_array($key, $LeftJoin)) ? "LEFT" : $JoinType; $this->db->join($key, $val, $JoinType); } } } } public function Delete($id, $idval, $table) { $this->db->where($id, $idval); return $this->db->delete($table); } public function DropData($condition, $table) { $TableName = $this->TableList[$table]; $this->db->where($condition); $status = $this->db->delete($TableName); return ($this->db->affected_rows() > 0) ? TRUE : FALSE; } private function _get_datatables_query($tableName, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, $JoinRequired) { if ($JoinRequired) { $this->JoinData($tableName, 'LEFT', '', ''); } $this->db->from($tableName); $this->db->where($Condition); $i = 0; foreach ($ColumnSearch as $item) { // loop column if ($_POST['search']['value']) { // if datatable send POST for search if ($i === 0) { // first loop $this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND. $this->db->like($item, $_POST['search']['value']); } else { $this->db->or_like($item, $_POST['search']['value']); } if (count($ColumnSearch) - 1 == $i) //last loop $this->db->group_end(); //close bracket } $i++; } if (isset($_POST['order'])) { // here order processing $this->db->order_by($ColumnOrder[$_POST['order']['0']['column']], $_POST['order']['0']['dir']); } else if (isset($OrderBy)) { $order = $OrderBy; $this->db->order_by(key($order)); } } function get_datatables($TableList, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, $JoinRequired) { $TableName = $this->TableList[$TableList]; $this->_get_datatables_query($TableName, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, $JoinRequired); if ($_POST['length'] != -1) { $this->db->limit($_POST['length'], $_POST['start']); } $query = $this->db->get(); return $query->result(); } function count_filtered($TableList, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, $JoinRequired) { $TableName = $this->TableList[$TableList]; $this->_get_datatables_query($TableName, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, $JoinRequired); $query = $this->db->get(); return $query->num_rows(); } public function count_all($TableList, $Condition) { $TableName = $this->TableList[$TableList]; $this->db->from($TableName); $this->db->where($Condition); return $this->db->count_all_results(); } } <file_sep>/application/views/homepage/login.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Atrocity Tracking and Management</title> <!-- Tell the browser to be responsive to screen width --> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <!-- Bootstrap 3.3.7 --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/bootstrap/dist/css/bootstrap.min.css') ?>"/> <!-- Font Awesome --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/font-awesome/css/font-awesome.min.css') ?>"/> <!-- Ionicons --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/Ionicons/css/ionicons.min.css') ?>"/> <!-- Theme style --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/css/AdminLTE.min.css') ?>"/> <!-- AdminLTE Skins. Choose a skin from the css/skins folder instead of downloading all of them to reduce the load. --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/css/skins/skin-blue-light.css') ?>"/> <!-- Morris chart --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/morris.js/morris.css') ?>"/> <!-- jvectormap --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/jvectormap/jquery-jvectormap.css') ?>"/> <!-- Date Picker --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins//bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css') ?>"/> <!-- Daterange picker --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/bootstrap-daterangepicker/daterangepicker.css') ?>"/> <!-- bootstrap wysihtml5 - text editor --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css') ?>"/> <!-- DataTables --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/datatables.net-bs/css/dataTables.bootstrap.min.css') ?>"/> <!-- Sweetalert --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/sweetalert/sweetalert.css') ?>"/> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!-- jQuery 3 --> <script src="<?= base_url('assets/plugins/jquery/dist/jquery.min.js') ?>"></script> <!-- jQuery UI 1.11.4 --> <script src="<?= base_url('assets/plugins/jquery-ui/jquery-ui.min.js') ?>"></script> <!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip --> <script> $.widget.bridge('uibutton', $.ui.button); </script> <!-- Bootstrap 3.3.7 --> <script src="<?= base_url('assets/plugins/bootstrap/dist/js/bootstrap.min.js') ?>"></script> <!-- DataTables --> <script src="<?= base_url('assets/plugins/datatables.net/js/jquery.dataTables.min.js') ?>"></script> <script src="<?= base_url('assets/plugins/datatables.net-bs/js/dataTables.bootstrap.min.js') ?>"></script> <!-- daterangepicker --> <script src="<?= base_url('assets/plugins/moment/min/moment.min.js') ?>"></script> <script src="<?= base_url('assets/plugins/bootstrap-daterangepicker/daterangepicker.js') ?>"></script> <!-- datepicker --> <script src="<?= base_url('assets/plugins/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js') ?>"></script> <!-- Bootstrap WYSIHTML5 --> <script src="<?= base_url('assets/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js') ?>"></script> <!-- Slimscroll --> <script src="<?= base_url('assets/plugins/jquery-slimscroll/jquery.slimscroll.min.js') ?>"></script> <!-- FastClick --> <script src="<?= base_url('assets/plugins/fastclick/lib/fastclick.js') ?>"></script> <!-- AdminLTE App --> <script src="<?= base_url('assets/js/adminlte.min.js') ?>"></script> <!-- Sweetalert --> <script src="<?= base_url('assets/plugins/sweetalert/sweetalert.js') ?>"></script> <!-- AdminLTE for demo purposes --> <script src="<?= base_url('assets/js/demo.js') ?>"></script> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <!-- Google Font --> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic"> <script> var Geo = ""; function GeoLocaiton(Json) { Geo = Json; } var base_url = "<?= base_url(); ?>"; var role = "<?= $this->router->fetch_class(); ?>"; </script> </head> <body class="hold-transition skin-blue-light layout-top-nav"> <!-- Notifications --> <?php if (!empty($this->session->flashdata('ME_ERROR'))) : ?> <script> var msg = "<?= $this->session->flashdata('ME_ERROR') ?>"; swal("Oops...!", msg, "error") </script> <?php elseif (!empty($this->session->flashdata('ME_SUCCESS'))) : ?> <script> var msg = "<?= $this->session->flashdata('ME_SUCCESS') ?>"; swal("SUCCESS!", msg, "success") </script> <?php endif; ?> <div class="wrapper"> <header class="main-header"> <nav class="navbar navbar-static-top"> <div class="container"> <div class="navbar-header"> <a href="<?= base_url('index.php/homepage/index') ?>" class="navbar-brand">Atrocity Case Management</a> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse"> <i class="fa fa-bars"></i> </button> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse pull-left" id="navbar-collapse"> <ul class="nav navbar-nav"> <ul class="nav navbar-nav"> <li class="active"><a href="<?= base_url('index.php/homepage/index') ?>">Home</a></li> <li><a href="#">Offences and Punishments</a></li> <li><a href="<?= base_url('index.php/homepage/login') ?>">Login</a></li> </ul> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> </header> <div class="content-wrapper"> <div class="container"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> Login </h1> </section> <!-- Main content --> <section class="content"> <div class="row"> <!-- left column --> <div class="col-md-12"> <!-- general form elements --> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title">Login Account</h3> </div> <!-- /.box-header --> <!-- form start --> <?php if ($_SESSION['formError'] != null): ?> <p><?= $_SESSION['formError']; $_SESSION['formError'] = null; ?></p> <?php endif; ?> <form role="form" method="post" action="<?= base_url('index.php/administrator/index') ?>" autocomplete="off"> <div class="box-body"> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label><?= $this->lang->line('email_id') ?></label> <input type="emailid" class="form-control" id="username" name="username" placeholder="User Name" required="true"/> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label for="exampleInputEmail1"><?= $this->lang->line('password') ?></label> <input type="<PASSWORD>" class="form-control" id="<PASSWORD>" name="<PASSWORD>" placeholder="<PASSWORD>" required="true"> </div> </div> </div> </div> <!-- /.box-body --> <div class="box-footer"> <button type="submit" class="btn btn-primary"><?= $this->lang->line('login') ?></button> <a href="<?= base_url('index.php/homepage/userregister') ?>" class="btn btn-info"><b><?= $this->lang->line('signup') ?></b></a> <a href="<?= base_url('index.php/homepage/forgotpassword') ?>" class="btn btn-danger">I forgot my password</a> </div> </form> </div> <!-- /.box --> <!--/.col (left) --> </div> <!-- /.row --> </section> <!-- /.content --> </div> <!-- /.container --> </div> <!-- /.content-wrapper --> <footer class="main-footer"> Developed by <strong>RMK Engineering College</strong> and Designed by <a href="https://adminlte.io">Almsaeed Studio</a> </footer> </div> <!-- ./wrapper --> </bodyn </html><file_sep>/application/helpers/datatable_helper.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /** * Morris Chart CodeIgniter implementation * * PHP version 5 * * @category CodeIgniter * @package Morris Chart CI * @author <NAME> * @version 0.1 * Copyright (c) 2016 <NAME> * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. */ if (!function_exists('chart_js')) { function chart_js($element, $data, $xkey, $ykeys, $labels) { $chart_js .= '<script type="text/javascript">(function (window, document, $, undefined) {'; $chart_js .= 'Morris.Bar({'; $chart_js .= "element:'" . $element . "',"; $chart_js .= "data:[{y: '2011 Q1', a: 3, b: 2, c: 3}"; $chart_js .= "],"; $chart_js .= "xkey:'" . $xkey . "',"; $chart_js .= "ykeys:[" . $ykeys . "],"; $chart_js .= "labels:[" . $labels . "],"; $chart_js .= "barColors: $('#" . $element . "').data('colors').split(',')"; $chart_js .= "});"; $chart_js .= "});(window, document, window.jQuery);</script>"; return $chart_js; } }<file_sep>/application/views/administrator/cases/fir.php <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1><?= $this->lang->line('fir_form') ?></h1> <ol class="breadcrumb"> <li><a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/index") ?>"><i class="fa fa-dashboard"></i><?= $this->lang->line('home') ?></a></li> <li class="active"><?= $this->lang->line('new_cases') ?></li> </ol> </section> <!-- Main content --> <section class="content"> <!-- Small boxes (Stat box) --> <div class="row"> <div class="col-md-12"> <div class="box box-primary"> <!-- /.box-header --> <!-- form start --> <form role="form" method="post" action="<?= base_url('index.php/' . strtolower($this->router->fetch_class()) . "/FirRegisterSave") ?> "> <div class="box-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="FIR Number"><?= $this->lang->line('fir_no') ?> </label> <input class="form-control" id="FIR Number" placeholder="Enter FIR Number" type="text" name="fir_no" required="true"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="Policestation"><?= $this->lang->line('police_station') ?> </label> <input class="form-control" id="Police Station" placeholder="Enter Police Station Name" type="text" name="police_station" required="true"> </div> </div> </div> <div class="row"> <div class="col-md-4"> <div class="form-group"> <label for="district"><?= $this->lang->line('district') ?></label> <select class="form-control" id="vdistrict" name="district" placeholder="Select District" required="true"> <option>Select District</option> <?php foreach ($this->db->where(array("districtshow" => "Y"))->order_by("districtname", "asc")->get('district')->result() as $detail) { ?> <option value="<?= $detail->dist_id ?>"> <?= strtoupper($detail->districtname) ?> </option> <?php } ?> </select> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="year"><?= $this->lang->line('year') ?></label> <input class="form-control" id="year" placeholder="Enter Year" type="number" name="year" > </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="date"><?= $this->lang->line('date') ?></label> <input type="date" class="form-control" id="date" name="date" placeholder="Enter date " required="true"> </div> </div> </div> <div class="row"> <div class="col-md-7"> <div class="form-group"> <label for="act1"><?= $this->lang->line('act1') ?></label> <input type="text" class="form-control" id="act1" name="act1" placeholder="Enter Act"> </div> </div> <div class="col-md-5"> <div class="form-group"> <label for="Section1"><?= $this->lang->line('section1') ?></label> <input type="text" class="form-control" id="Section1" name="section1" placeholder="Enter Section" required="true"> </div> </div> </div> <div class="row"> <div class="col-md-7"> <div class="form-group"> <label for="act2"><?= $this->lang->line('act2') ?></label> <input type="text" class="form-control" id="act2" name="act2" placeholder="Enter Act"> </div> </div> <div class="col-md-5"> <div class="form-group"> <label for="Section2"><?= $this->lang->line('section2') ?></label> <input type="text" class="form-control" id="Section1" name="section2" placeholder="Enter Section" required="true"> </div> </div> </div> <div class="row"> <div class="col-md-4"> <div class="form-group"> <label for="offence_day"><?= $this->lang->line('offence_day') ?></label> <input type="text" class="form-control" id="offence_day" name="offence_day" placeholder="Enter Offence Day " required="true"> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="Date_from"><?= $this->lang->line('date_from') ?></label> <input type="date" class="form-control" id="date_from" name="date_from" placeholder="Enter From Date " required="true"> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="Date_to"><?= $this->lang->line('date_to') ?></label> <input type="date" class="form-control" id="date_to" name="date_to" placeholder="Enter To Date " required="true"> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="Time_from"><?= $this->lang->line('time_from') ?></label> <input type="text" class="form-control" id="time_from" name="time_from" placeholder="Enter From Time " required="true"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="Time_to"><?= $this->lang->line('time_to') ?></label> <input type="text" class="form-control" id="time_to" name="time_to" placeholder="Enter To Time " required="true"> </div> </div> </div> <hr> <h4><?= $this->lang->line('information_received_at_police_station') ?></h4> <br> <div class="row"> <div class="col-md-4"> <div class="form-group"> <label for="date"><?= $this->lang->line('date') ?></label> <input type="date" class="form-control" id="date" name="receiveddate" placeholder="Enter Offence date " required="true"> </div></div> <div class="col-md-4"> <div class="form-group"> <label for="time"><?= $this->lang->line('time') ?></label> <input type="text" class="form-control" id="time" name="time" placeholder="Enter time " required="true"> </div></div> <div class="col-md-4"> <div class="form-group"> <label for="place_of_occurrence"><?= $this->lang->line('place_of_occurrence') ?></label> <input type="text" class="form-control" id="place_of_occurrence" name="place_of_occurrence" placeholder="Enter Of Occurrence " required="true"> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label for="type_of_information"><?= $this->lang->line('type_of_information') ?></label> <input type="text" class="form-control" id="type_of_information" name="type_of_information" placeholder="Enter Type Of Information " required="true"> </div></div> </div> <h4><?= $this->lang->line('complianant/informant') ?></h4> <br> <div class="row"> <div class="col-md-4"> <div class="form-group"> <label for="name"><?= $this->lang->line('complianantname') ?></label> <input type="text" class="form-control" id="complianantname" name="complianantname" placeholder="Enter Complianant Name " required="true"> </div></div> <div class="col-md-4"> <div class="form-group"> <label for="date"><?= $this->lang->line('complianantdob') ?></label> <input type="date" class="form-control" id="complianantdob" name="complianantdob" placeholder="Enter Date Of Birth " required="true"> </div></div> <div class="col-md-4"> <div class="form-group"> <label for="nationality"><?= $this->lang->line('nationality') ?></label> <input type="text" class="form-control" id="nationality" name="nationality" placeholder="Enter Nationality " required="true"> </div></div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="occupation "><?= $this->lang->line('occupation') ?></label> <input type="text" class="form-control" id="occupation " name="occupation" placeholder="Enter Occupation " required="true"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="address "><?= $this->lang->line('address') ?></label> <input type="text" class="form-control" id="address " name="address" placeholder="Enter Address " required="true"> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label><?= $this->lang->line('suspectparticulars') ?></label> <input class="form-control" id="others" placeholder="suspectparticulars" type="text" name="suspectparticulars"> </div> </div> </div> <div class="row"> <center><div class="form-group"> <input type="checkbox" name="send_to_sjsa" > <?= $this->lang->line('send_to_sjsa') ?> </div> </center> </div> </div> <div class="box-footer"> <center> <div class="col-md-12"> <button type="submit" class="btn btn-primary"><?= $this->lang->line('submit') ?></button> </div></center> </div> </div> </form> </div> </div> </div> </section> <!-- /.content --> </div> <script type="text/javascript"> $("#vdistrict").on("change", function (event, r) { LastUrl = ""; AjaxCall("index.php/" + role + "/FetchCities", "id=" + $(this).val(), "vcity", "id"); }); $("#odistrict").on("change", function (event, r) { LastUrl = ""; AjaxCall("index.php/" + role + "/FetchCities", "id=" + $(this).val(), "ocity", "id"); }); </script> <file_sep>/application/views/police/messages/sent.php <div class="content-wrapper"> <section class="content-header"> <h1><?= $this->lang->line('mail_box')?></h1> <ol class="breadcrumb"> <li><a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/index") ?>"><i class="fa fa-dashboard"></i> <?= $this->lang->line('home') ?></a></li> <li class="active"><?= $this->lang->line('messages') ?></li> </ol> </section> <section class="content"> <div class="row"> <div class="col-md-3"> <a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/messages/composemail") ?>" class="btn btn-primary btn-block margin-bottom">Compose</a> <div class="box box-solid"> <div class="box-header with-border"> <h3 class="box-title">Folders</h3> <div class="box-tools"> <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i> </button> </div> </div> <div class="box-body no-padding"> <ul class="nav nav-pills nav-stacked"> <li><a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/messages/show") ?>"><i class="fa fa-inbox"></i> Inbox <span class="label label-primary pull-right">12</span></a></li> <li class="active"><a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/messages/sent") ?>"><i class="fa fa-envelope-o"></i> Sent</a></li> </ul> </div> <!-- /.box-body --> </div> </div> <!-- /.col --> <div class="col-md-9"> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title">Sent</h3> </div> <!-- /.box-header --> <div class="box-body no-padding"> <div class="table-responsive mailbox-messages"> <table class="table table-hover table-striped"> <tbody> <?php foreach ($SentMessages as $email): ?> <tr> <td><div class="icheckbox_flat-blue" aria-checked="false" aria-disabled="false" style="position: relative;"><input type="checkbox" style="position: absolute; opacity: 0;"><ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%; height: 100%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"></ins></div></td> <td class="mailbox-name"><a href="#"><?= $email['SenderName'] ?></a></td> <td class="mailbox-subject"><b><?= $email['MessageSubject'] ?></b> <?= $email['Messagedetails'] ?></td> <td class=" pull-right mailbox-date"> <?= time_elapsed_string($email['CreatedOn']) ?></td> </tr> <?php endforeach; ?> </tbody> </table> <!-- /.table --> </div> <!-- /.mail-box-messages --> </div> <!-- /.box-body --> </div> <!-- /. box --> </div> <!-- /.col --> </div> </section> </div> <file_sep>/application/views/user/cases/districtcases.php <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> <th> <?= $this->lang->line('cases') ?></th> </h1> <ol class="breadcrumb"> <li><a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/index") ?>"><i class="fa fa-dashboard"></i><?= $this->lang->line('home') ?></a></li> <li class="active"><?= $this->lang->line('cases') ?></li> </ol> </section> <!-- Main content --> <section class="content"> <div class="box"> <!-- /.row --> <div class="box-body"> <div class="row"> <div class="col-md-12"> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title"><?= $this->lang->line('new_cases') ?></h3> </div> <table id="NewCase" class="table table-bordered table-striped"> <thead> <tr> <th> <?= $this->lang->line('fir_no') ?></th> <th> <?= $this->lang->line('victim_name') ?></th> <th> <?= $this->lang->line('mobile_number') ?></th> </tr> </thead> <tbody> <?php foreach ($newcase as $new): ?> <tr> <td><?= $new['FIR'] ?> </td> <td><?= $new['VictimName'] ?></td> <td><?= $new['VictimMobile'] ?></td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </div> </div> </div> </section> <br/> <section class="content"> <div class="box"> <!-- /.row --> <div class="box-body"> <div class="row"> <div class="col-md-12"> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title"><?= $this->lang->line('solved_cases') ?></h3> </div> <table id="SolvedCases" class="table table-bordered table-striped"> <thead> <tr> <th> <?= $this->lang->line('fir_no') ?></th> <th> <?= $this->lang->line('victim_name') ?></th> <th> <?= $this->lang->line('mobile_number') ?></th> <!--<th>Status</th>--> </tr> </thead> <tbody> <?php foreach ($pendingcase as $pending): ?> <tr> <td><?= $pending['FIR'] ?> </td> <td><?= $pending['VictimName'] ?></td> <td><?= $pending['VictimMobile'] ?></td> <td><span class="label label-info">Police Tracking</span></td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </div> </div> </div> </section> <br/> <section class="content"> <div class="box"> <!-- /.row --> <div class="box-body"> <div class="row"> <div class="col-md-12"> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title"><?= $this->lang->line('pending_cases') ?></h3> </div> <table id="PendingCases" class="table table-bordered table-striped"> <thead> <tr> <th> <?= $this->lang->line('fir_no') ?></th> <th> <?= $this->lang->line('victim_name') ?></th> <th> <?= $this->lang->line('mobile_number') ?></th> </tr> </thead> <tbody> <?php foreach ($solvedcase as $solved): ?> <tr> <td><?= $solved['FIR'] ?> </td> <td><?= $solved['VictimName'] ?></td> <td><?= $solved['VictimMobile'] ?></td> <td><span class="label label-info">Solved</span></td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </div> </div> </div> </section> </div> <!-- /.col --> <!-- /.content --> <script type="text/javascript"> var table; var base_url = '<?php echo base_url(); ?>'; $(document).ready(function () { //datatables table = $('#NewCase').DataTable({ "processing": true, //Feature control the processing indicator. "serverSide": true, //Feature control DataTables' server-side processing mode. "order": [], //Initial no order. // Load data for the table's content from an Ajax source "ajax": { "url": "<?= base_url('index.php/' . strtolower($this->router->fetch_class()) . '/map_ajax_list/cases/' . $districtID) ?>", "type": "POST" }, //Set column definition initialisation properties. "columnDefs": [ { "targets": [-1], //last column "orderable": false, //set not orderable }, ], }); }); </script> <script type="text/javascript"> var table; var base_url = '<?php echo base_url(); ?>'; $(document).ready(function () { //datatables table = $('#SolvedCases').DataTable({ "processing": true, //Feature control the processing indicator. "serverSide": true, //Feature control DataTables' server-side processing mode. "order": [], //Initial no order. // Load data for the table's content from an Ajax source "ajax": { "url": "<?= base_url('index.php/' . strtolower($this->router->fetch_class()) . '/map_ajax_list/solvedcases/' . $districtID) ?>", "type": "POST" }, //Set column definition initialisation properties. "columnDefs": [ { "targets": [-1], //last column "orderable": false, //set not orderable }, ], }); }); </script> <script type="text/javascript"> var table; var base_url = '<?php echo base_url(); ?>'; $(document).ready(function () { //datatables table = $('#PendingCases').DataTable({ "processing": true, //Feature control the processing indicator. "serverSide": true, //Feature control DataTables' server-side processing mode. "order": [], //Initial no order. // Load data for the table's content from an Ajax source "ajax": { "url": "<?= base_url('index.php/' . strtolower($this->router->fetch_class()) . '/map_ajax_list/pendingcases/' . $districtID) ?>", "type": "POST" }, //Set column definition initialisation properties. "columnDefs": [ { "targets": [-1], //last column "orderable": false, //set not orderable }, ], }); }); </script> <file_sep>/application/views/layout/header.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Atrocity Tracking and Management</title> <!-- Tell the browser to be responsive to screen width --> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <!-- Bootstrap 3.3.7 --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/bootstrap/dist/css/bootstrap.min.css') ?>" /> <!-- Font Awesome --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/font-awesome/css/font-awesome.min.css') ?>" /> <!-- Ionicons --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/Ionicons/css/ionicons.min.css') ?>" /> <!-- Theme style --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/css/AdminLTE.min.css') ?>" /> <!-- AdminLTE Skins. Choose a skin from the css/skins folder instead of downloading all of them to reduce the load. --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/css/skins/skin-blue-light.css') ?>" /> <!-- Morris chart --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/morris.js/morris.css') ?>" /> <!-- jvectormap --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/jvectormap/jquery-jvectormap.css') ?>" /> <!-- Date Picker --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins//bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css') ?>" /> <!-- Daterange picker --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/bootstrap-daterangepicker/daterangepicker.css') ?>" /> <!-- bootstrap wysihtml5 - text editor --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css') ?>" /> <!-- DataTables --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/datatables.net-bs/css/dataTables.bootstrap.min.css') ?>" /> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- Sweetalert --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/sweetalert/sweetalert.css') ?>" /> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!-- jQuery 3 --> <script src="<?= base_url('assets/plugins/jquery/dist/jquery.min.js') ?>"></script> <!-- jQuery UI 1.11.4 --> <script src="<?= base_url('assets/plugins/jquery-ui/jquery-ui.min.js') ?>"></script> <!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip --> <script> $.widget.bridge('uibutton', $.ui.button); </script> <!-- Bootstrap 3.3.7 --> <script src="<?= base_url('assets/plugins/bootstrap/dist/js/bootstrap.min.js') ?>"></script> <!-- DataTables --> <script src="<?= base_url('assets/plugins/datatables.net/js/jquery.dataTables.min.js') ?>"></script> <script src="<?= base_url('assets/plugins/datatables.net-bs/js/dataTables.bootstrap.min.js') ?>"></script> <!-- daterangepicker --> <script src="<?= base_url('assets/plugins/moment/min/moment.min.js') ?>"></script> <script src="<?= base_url('assets/plugins/bootstrap-daterangepicker/daterangepicker.js') ?>"></script> <!-- datepicker --> <script src="<?= base_url('assets/plugins/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js') ?>"></script> <!-- Bootstrap WYSIHTML5 --> <script src="<?= base_url('assets/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js') ?>"></script> <!-- Slimscroll --> <script src="<?= base_url('assets/plugins/jquery-slimscroll/jquery.slimscroll.min.js') ?>"></script> <script src="<?= base_url('assets/plugins/iCheck/icheck.min.js') ?>"></script> <!-- FastClick --> <script src="<?= base_url('assets/plugins/fastclick/lib/fastclick.js') ?>"></script> <!-- AdminLTE App --> <script src="<?= base_url('assets/js/adminlte.min.js') ?>"></script> <!-- Sweetalert --> <script src="<?= base_url('assets/plugins/sweetalert/sweetalert.js') ?>"></script> <!-- AdminLTE for demo purposes --> <script src="<?= base_url('assets/js/demo.js') ?>"></script> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <!-- Google Font --> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic"> <script> var Geo = ""; function GeoLocaiton(Json) { Geo = Json; } var base_url = "<?= base_url(); ?>"; var role = "<?= $this->router->fetch_class(); ?>"; </script> </head> <body class="hold-transition skin-blue-light sidebar-mini"> <div class="wrapper"> <!-- END HEADER--> <!-- Notifications --> <?php if (!empty($this->session->flashdata('ME_ERROR'))) : ?> <script> var msg = "<?= $this->session->flashdata('ME_ERROR') ?>"; swal("Oops...!", msg, "error") </script> <?php elseif (!empty($this->session->flashdata('ME_SUCCESS'))) : ?> <script> var msg = "<?= $this->session->flashdata('ME_SUCCESS') ?>"; swal("SUCCESS!", msg, "success") </script> <?php endif; ?> <!-- /Notifications --> <file_sep>/application/libraries/Deviceservice.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /** * Arugement Validation CodeIgniter implementation * * PHP version 5 * * @category CodeIgniter * @package Api Render * @author <NAME> (<EMAIL>) * @version 0.1 */ class Deviceservice { public function __construct() { $this->obj = & get_instance(); } public function DeviceUpdate($Updata = array(), $Condition = array(), $DUpdate = array()) { $Postdata = $this->obj->input->get(null, true); if ((empty($this->obj->UUid))): exit($this->obj->apirender->ThowError("Due to the Security reason this device cannot be use \n Please Try to use other device \n *Note: We are supporting only Android and IOS Devices ErrorCode:404 Email", "ResetApp()")); endif; if (0 == 0): if (empty($Condition)): $DevCondition = array("di_refer_id" => $this->obj->ReferId, "di_uuid" => $this->obj->UUid); else: $DevCondition = array("di_refer_id" => $this->obj->ReferId); endif; $DevUpdate = array( "di_device_name" => substr($Postdata['deviceName'], 0, 99), "di_os" => substr($Postdata['osVersion'], 0, 19), "di_platform" => $Postdata['platform'], "di_tran_hit" => 1, "di_uuid" => $Postdata['uuid'], "di_email" => $Postdata['deviceOwnerEmail'] ); $this->obj->db->where((array) $DevCondition + array("di_status" => "A")); $ExixtingDev = (array) $this->obj->db->get("deviceinfo")->row(); if (empty($ExixtingDev)): $this->obj->db->set(array_merge((array) $DevCondition, (array) $DUpdate, (array) $DevUpdate)); $this->obj->db->insert("deviceinfo"); else: $DevUpdate["di_tran_hit"] = $ExixtingDev['di_tran_hit'] + 1; $this->obj->db->where($DevCondition); $this->obj->db->set(array_merge((array) $DUpdate, (array) $DevUpdate)); $this->obj->db->update("deviceinfo"); endif; else: exit($this->obj->apirender->ThowError("Due to the Security reason this device cannot be use \n Please Try to use other device \n *Note: We are supporting only Android and IOS Devices ErrorCode: 404 Device", "formcheck()")); endif; return true; } public function DevVerifi($PhoneId, $Colvalue, $Colomnid, $ThrowError = null, $ReturnAll = null) { if (!empty($Colomnid)) { if (!empty($PhoneId)) { $PhoneAdd = array("di_uuid" => $PhoneId); } $Extra = array($Colomnid => $Colvalue, "du_status" => "A") + (array) $PhoneAdd; } elseif (!empty($PhoneId)) { $Extra = array("di_uuid" => $PhoneId); } else { exit($this->obj->apirender->ThowError("Due to Security Reason Your Account is cannot Acess.", "ResetApp()")); } $DevCondition = array("di_status" => "A") + (array) $Extra; $ExUser = (array) $this->obj->db->where($DevCondition)->join("deviceuser", "deviceinfo.di_refer_id=deviceuser.du_id", LEFT)->join("devicecategory","d_id=du_category")->get("deviceinfo")->row(); if (!empty($ExUser)): $ExUser = ($ExUser); $this->obj->ReferId = $ExUser["di_refer_id"]; if (empty($ReturnAll)) { return empty($ExUser["du_phone_no"]) ? $ExUser['du_email_id'] : $ExUser["du_phone_no"]; } else { return $ExUser; } else: if (empty($ThrowError)) { exit($this->obj->apirender->ThowError("This device already activated \n Note:Each account should use the unique device to login ErrorCode:Login-404.", "ResetApp()")); } else { return null; } endif; } public function randomgen($min, $max, $quantity) { $numbers = range($min, $max); shuffle($numbers); $condition = array("du_user_id" => current($numbers)); $RandomStaus = (array) $this->obj->db->where($condition)->get("deviceuser")->row(); while (!empty($RandomStaus)) { shuffle($numbers); $condition = array("du_user_id" => current($numbers)); $RandomStaus = (array) $this->obj->db->where($condition)->get("deviceuser")->row(); } return array_slice($numbers, 0, $quantity); } } <file_sep>/application/libraries/MY_Encrypt.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class MY_Encrypt extends CI_Encrypt { function encode($string, $key = "", $url_safe = TRUE) { // you may change these values to your own $secret_key = 'RMKEcSTAfF'; $secret_iv = 'ViDCsE'; $output = false; $encrypt_method = "AES-256-CBC"; $key = hash('sha256', $secret_key); $iv = substr(hash('sha256', $secret_iv), 0, 16); $output = base64_encode(openssl_encrypt($string, $encrypt_method, $key, 0, $iv)); return $output; } function decode($string, $key = "") { // you may change these values to your own $secret_key = 'RMKEcSTAfF'; $secret_iv = 'ViDCsE'; $output = false; $encrypt_method = "AES-256-CBC"; $key = hash('sha256', $secret_key); $iv = substr(hash('sha256', $secret_iv), 0, 16); $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv); return $output; } } <file_sep>/application/views/layout/nav.php <header class="main-header"> <!-- Logo --> <a href="#" class="logo"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><b>ATM</b></span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"><b><?= $this->lang->line('atrocity_tracking') ?></b></span> </a> <!-- Header Navbar: style can be found in header.less --> <nav class="navbar navbar-static-top"> <!-- Sidebar toggle button--> <a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button"> <span class="sr-only">Toggle navigation</span> </a> <div class="navbar-custom-menu"> <ul class="nav navbar-nav"> <!-- Notifications: style can be found in dropdown.less --> <li class="dropdown notifications-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-bell-o"></i> <span class="label label-warning">10</span> </a> <ul class="dropdown-menu"> <li class="header">You have 10 notifications</li> <li> <!-- inner menu: contains the actual data --> </li> <li class="footer"><a href="#">View all</a></li> </ul> </li> <!-- User Account: style can be found in dropdown.less --> <li class="dropdown user user-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <!-- <img src="dist/img/user2-160x160.jpg" class="user-image" alt="User Image"> --> <span class="hidden-xs"><?= $_SESSION['UserFullName'] ?></span> </a> <ul class="dropdown-menu"> <!-- User image --> <li class="user-header"> <?php if ($profileurl == null): $profileurl = 'user4-128x128.jpg'; endif; ?> <img src="<?= base_url("assets/img/" . $profileurl) ?>" class="img-circle" alt="User Image"> <p> <?= $_SESSION['UserFullName'] ?> </p> <p><small><?= $_SESSION['UserRoleName'] ?></small></p> </li> <!-- Menu Footer--> <li class="user-footer"> <div class="pull-right"> <a href="<?= base_url('index.php/' . $this->router->fetch_class() . '/logout') ?>" class="btn btn-default btn-flat">Sign out</a> </div> </li> </ul> </li> </ul> </div> </nav> </header> <!-- Left side column. contains the logo and sidebar --> <aside class="main-sidebar"> <!-- sidebar: style can be found in sidebar.less --> <section class="sidebar"> <!-- Sidebar user panel --> <div class="user-panel"> <div class="pull-left image"> <img src="<?= base_url("assets/img/" . $profileurl) ?>" class="img-circle" alt="User Image"> </div> <div class="pull-left info"> <p><?= $_SESSION['UserFullName'] ?></p> <a href="#"><?= $_SESSION['UserRoleName'] ?></a> </div> </div> <!-- sidebar menu: : style can be found in sidebar.less --> <ul class="sidebar-menu" data-widget="tree"> <li class="header">Navigation Menu</li> <li> <a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/index") ?>"> <i class="fa fa-dashboard"></i> <span>Dashboard</span> <span class="pull-right-container"> </span> </a> </li> <li class="treeview"> <a href="#"> <i class="fa fa-user"></i> <span><?= $this->lang->line('user_management') ?></span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li> <a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/updateprofile") ?>"><i class="fa fa-circle-o"></i><?= $this->lang->line('update_profile') ?></a></li> <li> <a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/changepassword") ?>"><i class="fa fa-circle-o"></i><?= $this->lang->line('change_password') ?></a></li> <li> <a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/offencesandcompensations") ?>"><i class="fa fa-circle-o"></i><?= $this->lang->line('offences_and_compensations') ?></a></li> <li> <a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/postcomplaints") ?>"><i class="fa fa-circle-o"></i><?= $this->lang->line('post_complaints') ?></a></li> </ul> </li> <?php if (strtoupper($_SESSION['UserRoleName']) == "ADMINISTRATOR"): ?> <?php endif; ?> <li class="treeview"> <a href="#"> <i class="fa fa-paper-plane"></i> <span><?= $this->lang->line('case_management') ?></span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <?php if (strtolower($_SESSION['UserRoleName']) != "organization" && strtolower($_SESSION['UserRoleName']) != "user"): ?> <li> <a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/cases/newcase") ?>"><i class="fa fa-circle-o"></i> <?= $this->lang->line('register_new_case')?></a></li> <?php endif; ?> <li> <a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/cases/allcases") ?>"><i class="fa fa-circle-o"></i>Show All Cases</a></li> <?php if (strtolower($_SESSION['UserRoleName']) != "user"): ?> <li> <a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/cases/alloffenders") ?>"><i class="fa fa-circle-o"></i>Show all Offenders</a></li> <?php endif; ?> <!-- <li> <a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/complaint/allcomplaints") ?>"><i class="fa fa-circle-o"></i> Show all User Complaints</a></li>--> <?php if (strtolower($_SESSION['UserRoleName']) == "user"): ?> <li> <a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/postcomplaints") ?>"><i class="fa fa-circle-o"></i>Post Complaints</a></li> <?php endif; ?> </ul> </li> <li> <a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/messages/show") ?>"> <i class="fa fa-medium"></i> <span>Messages</span> <span class="pull-right-container"> </span> </a> </li> <li> <a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/logout") ?>"> <i class="fa fa-power-off"></i> <span>Logout</span> </a> </li> <li class="header">Change Language</li> <li> <?php if (!$this->session->userdata('site_lang') == 'english'): ?> <a href="#"> <?php else: ?> <a href="<?= base_url("index.php/LanguageSwitcher/switchLang/english") ?>"> <?php endif; ?> <i class="fa fa-language"></i> <span>English</span> <span class="pull-right-container"></span> <?php if ($this->session->userdata('site_lang') == 'english'): ?> <i class="fa fa-check pull-right" style="color: green"></i> <?php endif; ?> </a> </li> <li> <?php if ($this->session->userdata('site_lang') == 'marathi'): ?> <a href="#"> <?php else: ?> <a href="<?= base_url("index.php/LanguageSwitcher/switchLang/marathi") ?>"> <?php endif; ?> <i class="fa fa-language"></i> <span> मराठी - (Marathi)</span> <span class="pull-right-container"></span> <?php if ($this->session->userdata('site_lang') == 'marathi'): ?> <i class="fa fa-check pull-right" style="color: green"></i> <?php endif; ?> </a> </li> <li> <?php if ($this->session->userdata('site_lang') == 'hindi'): ?> <a href="#"> <?php else: ?> <a href="<?= base_url("index.php/LanguageSwitcher/switchLang/hindi") ?>"> <?php endif; ?> <i class="fa fa-language"></i> <span> हिंदी - (Hindi) </span> <span class="pull-right-container"></span> <?php if ($this->session->userdata('site_lang') == 'hindi'): ?> <i class="fa fa-check pull-right" style="color: green"></i> <?php endif; ?> </a> </li> </ul> </section> <!-- /.sidebar--> </aside><file_sep>/application/libraries/Auth.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Auth { public function __construct() { $this->obj = & get_instance(); } function Authencation($FirstLogin = null, $Class = null) { $Postdata = $this->obj->input->post(); $_SESSION = $this->obj->session->userdata; $HttpRequestType = $this->obj->auth->UserRequestFrom(); $LoginData = "homepage/login"; $Class = strtolower($Class); if (!empty($_SESSION['UserId'])) { return true; } elseif (!empty($Postdata['username']) && !empty($Postdata['password'])) { $Userdetails = $this->obj->db->select(array("role as RoleID", "rolename as RoleName", "user_id as ID", "name as FullName", "username as UserName"))->where(array("username" => $Postdata['username'], "password" => $<PASSWORD>['<PASSWORD>']))->join("roles", "roleid=role")->get("users")->row_array(); if (!empty($Userdetails)): $this->obj->session->set_userdata("Auth", "Y"); $this->obj->session->set_userdata("UserName", $Userdetails['UserName']); $this->obj->session->set_userdata("UserFullName", $Userdetails['FullName']); $this->obj->session->set_userdata("UserId", $Userdetails['ID']); $this->obj->session->set_userdata("UserRoleID", $Userdetails['RoleID']); $this->obj->session->set_userdata("UserRoleName", $Userdetails['RoleName']); $this->obj->session->set_userdata('site_lang', "english"); $_SESSION = $this->obj->session->userdata; return true; else: $Error = "User Name or Password is not match"; if ($HttpRequestType) { $Error = array("Error" => $Error); exit(json_encode($Error)); } else { exit($this->obj->load->view($LoginData, get_defined_vars(), true)); } endif; } else { if (!empty($FirstLogin)): exit($this->obj->load->view($LoginData, get_defined_vars(), true)); endif; $Error = "User Name or Password is not should be empty."; if ($HttpRequestType) { $Error = array("Error" => $Error); exit(json_encode($Error)); } else { exit($this->obj->load->view($LoginData, get_defined_vars(), true)); } } } public function UserRequestFrom() { if (($_POST['Api'] == "Webview") || (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')) { return true; } else { return false; } } } <file_sep>/application/views/user/postcomplaints/postcomplaints.php <div class="content-wrapper"> <!-- Content Header (Page header) --> <!-- <section class="content"> <div class="box"> /.box-header <div class="box-body"> <div class="row"> <div class="col-sm-12"> <table id="showallcomplaints" class="table table-bordered table-striped dataTable" role="grid" aria-describedby="example1_info"> <thead> <tr role="row"> <th> <?= $this->lang->line('complaints') ?></th> </tr> </thead> <tbody></tbody> </table> </div> </div> </div> </div> </section> <script type="text/javascript"> var table; var base_url = '<?php echo base_url(); ?>'; $(document).ready(function () { //datatables table = $('#showallcomplaints').DataTable({ "processing": true, //Feature control the processing indicator. "serverSide": true, //Feature control DataTables' server-side processing mode. "order": [], //Initial no order. // Load data for the table's content from an Ajax source "ajax": { "url": "<?= base_url('index.php/' . strtolower($this->router->fetch_class()) . '/posted_complaints_ajax_list/postedcomplaints') ?>", "type": "POST" }, //Set column definition initialisation properties. "columnDefs": [ { "targets": [-1, -2, -3, -4], //last column "orderable": false, //set not orderable }, ], }); }); </script>--> <section class="content-header"> <h1><?= $this->lang->line('postcomplaints') ?></h1> </section> <br> <section class="content"> <div class="box"> <!-- /.box-header --> <div class="box-body"> <div class="row"> <div class="col-md-12"> <div class="box-header"> <h3 class="box-title"> <?= $this->lang->line('complainthere') ?> </h3> </div> <form method="post" action="<?= base_url('index.php/' . strtolower($this->router->fetch_class()) . "/PostComplaintSave") ?> " autocomplete="off"> <div class="box-body pad"> <textarea class="textarea" placeholder="<?= $this->lang->line('postyourcomplaintshere') ?>" name="comments" style="width: 100%; height: 100px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"></textarea> </div> <div class="box-footer"> <div class="pull-right"> <button type="submit" class="btn btn-md btn-primary"><?= $this->lang->line('post') ?></button> </div> </div> </form> </div> </div> </div> </div> </section> </div><file_sep>/application/views/police/complaint/viewallcomplaints.php <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1><?= $this->lang->line('view_all_complaints') ?></h1> <ol class="breadcrumb"> <li><a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/index") ?>"><i class="fa fa-dashboard"></i><?= $this->lang->line('home') ?></a></li> <li class="active"><?= $this->lang->line('view_all_complaints') ?></li> </ol> </section> <!-- Main content --> <section class="content"> <div class="box"> <!-- /.box-header --> <div class="box-body"> <div class="row"> <div class="col-sm-12"> <table id="showallcomplaints" class="table table-bordered table-striped dataTable" role="grid" aria-describedby="example1_info"> <thead> <tr role="row"> <th> <?= $this->lang->line('victim_name') ?></th> <th> <?= $this->lang->line('mobile_number') ?></th> <th> <?= $this->lang->line('city') ?></th> <th> <?= $this->lang->line('comments') ?></th> <th> <?= $this->lang->line('actions') ?></th> </tr> </thead> <tbody></tbody> </table> </div> </div> </div> </div> </section> </div> <!-- /.row --> <!-- /.content --> <script type="text/javascript"> var table; var base_url = '<?php echo base_url(); ?>'; $(document).ready(function () { //datatables table = $('#showallcomplaints').DataTable({ "processing": true, //Feature control the processing indicator. "serverSide": true, //Feature control DataTables' server-side processing mode. "order": [], //Initial no order. // Load data for the table's content from an Ajax source "ajax": { "url": "<?= base_url('index.php/' . strtolower($this->router->fetch_class()) . '/complaints_ajax_list/complaints') ?>", "type": "POST" }, //Set column definition initialisation properties. "columnDefs": [ { "targets": [-1, -2, -3, -4], //last column "orderable": false, //set not orderable }, ], }); }); </script> <file_sep>/application/language/hindi/message_lang.php <?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* hindi language */ $lang['mobile_number'] = 'मोबाइल नंबर'; $lang['submit'] = 'जमा करें'; $lang['login'] = 'लॉग इन'; $lang['signup'] = 'साइन अप करें'; $lang['select'] = 'चुनना'; $lang['name'] = 'नाम'; $lang['address1'] = 'पता 1'; $lang['address2'] = 'पता 2'; $lang['city'] = 'शहर'; $lang['state'] = 'राज्य'; $lang['country'] = 'देश'; $lang['aadhaar_number'] = 'आधार संख्या'; $lang['email_id'] = 'ईमेल आईडी'; $lang['password'] = '<PASSWORD>'; $lang['old_password'] = '<PASSWORD>'; $lang['new_password'] = '<PASSWORD>'; $lang['confirmation_password'] = '<PASSWORD>'; $lang['select'] = 'चुनते हैं'; $lang['change_password'] = '<PASSWORD>ें'; $lang['edit_password'] = '<PASSWORD>ें'; $lang['profile_change'] = 'प्रोफाइल परिवर्तन'; $lang['edit_profile'] = 'प्रोफाइल अपडेट करें'; $lang['personalinformation'] = 'व्यक्तिगत जानकारी'; $lang['user_name'] = '<NAME>'; $lang['register'] = 'रजिस्टर'; $lang['update_profile'] = 'प्रोफ़ाइल अपडेट करें'; $lang['personal_information'] = 'व्यक्तिगत जानकारी'; $lang['all_users'] = 'सभी उपयोगकर्ताओं'; $lang['cases'] = 'मामलों'; $lang['new_cases'] = 'नए मामले'; $lang['pending_cases'] = 'लंबित मामलों'; $lang['solved_cases'] = 'हल मामलों'; /* case management form */ $lang['address'] = 'पता'; $lang['fir_no'] = 'एफआईआर संख्या'; $lang['registration_form'] = 'पंजीकरण फॉर्म'; $lang['case_details'] = 'केस विवरण'; $lang['case_id']=' घटना क्रमांक'; $lang['if_others'] = 'अगर अन्य'; $lang['case_description'] = 'केस विवरण'; $lang['victim_name'] = '<NAME>'; $lang['offender_name'] = 'अपराध<NAME>'; $lang['victim_details'] = 'शिकार विवरण '; $lang['case_management'] = 'मामला प्रबंधन'; $lang['offender_details'] = 'अपराधी विवरण'; $lang['offender_address'] = 'पता'; $lang['victim_address'] = 'पता'; $lang['victimdob'] = 'जन्म की तारीख'; $lang['age'] = 'आयु'; $lang['gender'] = 'लिंग'; $lang['offence_date'] = 'अपराध की तारीख'; $lang['status'] = 'स्थिति'; $lang['actions'] = 'कार्रवाई'; $lang['all_cases'] = 'सभी मामलों'; $lang['male'] = 'नर'; $lang['female'] = 'महिला'; $lang['others'] = 'अन्य लोग'; $lang['select_gender'] = 'लिंग चुनें'; $lang['all_solvedcases'] = 'सभी हल मामलों'; $lang['all_pendingcases'] = 'सभी लंबित मामले'; $lang['offencename'] = 'अपराध नाम'; $lang['alloffenders'] = 'सभी अपराधियों'; $lang['district'] = 'जिला'; $lang['show'] = 'प्रदर्शन'; $lang['entries'] = 'प्रविष्टियों'; $lang['search'] = 'खोज'; $lang['postcomplaints'] = 'पोस्ट शिकायतें'; $lang['complainthere'] = 'शिकायत यहाँ'; $lang['postyourcomplaintshere'] = 'अपनी शिकायत यहाँ पोस्ट करें'; /* case managment Ends Here */ /* Log Managment Starts Here */ $lang['log_mgnt'] = 'लॉग प्रबंध'; $lang['more_info'] = 'अधिक माहिती'; $lang['notice'] = 'नोटिस'; /* Log Managment Ends Here */ /* case history starts here */ $lang['post'] = 'जमा करें'; $lang['casehistory'] = 'मामले का इतिहास'; $lang['postedcomments'] = 'टिप्पणियाँ'; $lang['commenthere'] = 'यहां टिप्पणी करें'; $lang['typeyourcommenthere'] = 'अपनी टिप्पणी यहां टाइप करें'; /* case history ends here */ /* Dashboard Starts Here */ $lang['dashboard'] = 'डैशबोर्ड'; $lang['control_panel'] = 'कंट्रोल पैनल'; $lang['total_users'] = 'कुल उपयोगकर्ता'; $lang['total_cases'] = 'कुल मामलों'; $lang['solved_cases'] = 'हल मामलों'; $lang['pending_cases'] = 'लंबित मामलों'; $lang['more_info'] = 'और जानकारी'; $lang['map'] = 'https://www.maharashtra.gov.in:443/Images/mapMaharashtraM.jpg'; /* dashboard ends here */ /* Fir Format starts here */ $lang['fir_no'] = 'एफ आई आर संख्या'; $lang['police_station'] = 'पुलिस स्टेशन '; $lang['year'] = 'साल'; $lang['date'] = 'तारीख'; $lang['act1'] = 'अधिनियम1'; $lang['section1'] = 'अनुभाग1'; $lang['act2'] = 'अधिनियम2'; $lang['section2'] = 'अनुभाग2'; $lang['offence_day'] = 'अपराध दिवस'; $lang['date_from'] = 'तारीख से'; $lang['date_to'] = 'की तारीख'; $lang['time_from'] = 'समय से'; $lang['time_to'] = 'करने के लिए समय'; $lang['information_received_at_police_station'] = 'पुलिस स्टेशन पर प्राप्त जानकारी'; $lang['time'] = 'पहर'; $lang['type_of_information'] = 'जानकारी का प्रकार'; $lang['place_of_occurrence'] = 'घटना की जगह'; $lang['complianant/informant'] = 'शिकायतकर्ता/सूचना देनेवाला'; $lang['complianantname'] = 'शिकायतकर्ता नाम'; $lang['complianantdob'] = 'शिकायतकर्ता डब'; $lang['nationality'] = 'राष्ट्रीयता'; $lang['occupation'] = 'कब्जे'; $lang['address'] = 'पता'; $lang['suspectparticulars'] = 'संदेह विवरण'; $lang['send_to_sjsa'] = 'सामाजिक न्याय और विशेष सहायता भेजें'; $lang['fir_form'] = 'एफ आई आर प्रपत्र'; /* fir format ends here */ /* bread crumb start */ $lang['home'] = 'होम'; $lang['dashboard'] = 'डैशबोर्ड'; $lang['cases'] = 'मामलों'; $lang['new_cases'] = 'नए मामले'; $lang['all_cases'] = 'सभी मामलों'; $lang['all_offenders'] = 'सभी अपराधियों'; $lang['all_pending_cases'] = 'सभी लंबित मामलों'; $lang['all_solved_cases'] = 'सभी हल मामलों'; $lang['logs'] = 'लॉग'; $lang['all'] = 'सब'; $lang['errors'] = 'त्रुटियों'; $lang['notices'] = 'नोटिस'; $lang['warnings'] = 'चेतावनी'; $lang['show_notices'] = 'नोटिस दिखाएं'; $lang['all_offences'] = 'सभी अपराध'; $lang['users'] = 'उपयोगकर्ताओं'; $lang['all_users'] = 'सभी उपयोगकर्ताओं'; $lang['mobile_number'] = 'मोबाइल नंबर'; /* bread crumb ends here */ $lang['offender_offence'] = 'अपराधी अपराध'; $lang['offencereport'] = 'अपराध रिपोर्ट'; $lang['act'] = 'अपराध अधिनियम'; $lang['compensation'] = 'नुकसान भरपाई'; /* email*/ $lang['mail_box'] = 'मेल बॉक्स'; $lang['compose'] = 'रचना'; $lang['folder'] = 'रचना'; $lang['inbox'] = 'रचना'; $lang['sent'] = 'रचना'; $lang['bold'] = 'बोल्ड '; $lang['italic'] = 'इटैलिक '; $lang['underline'] = 'रेखांकित '; $lang['normal_text'] = 'सामान्य पाठ'; $lang['attachment'] = 'अनुलग्नक'; $lang['compose_new_message'] = 'नया संदेश लिखें'; $lang['messages'] = ' संदेशों'; /* email */ $lang['mail_box'] = 'मेल बॉक्स'; $lang['compose'] = 'रचना'; $lang['folder'] = 'रचना'; $lang['inbox'] = 'रचना'; $lang['sent'] = 'रचना'; $lang['bold'] = 'बोल्ड '; $lang['italic'] = 'इटैलिक '; $lang['underline'] = 'रेखांकित '; $lang['normal_text'] = 'सामान्य पाठ'; $lang['attachment'] = 'अनुलग्नक'; $lang['compose_new_message'] = 'नया संदेश लिखें'; /* complaints */ $lang['complaint_action'] = 'शिकायत की कार्रवाई'; $lang['police_details'] = 'पुलिस का ब्योरा'; $lang['comments'] = 'टिप्पणियां'; $lang['complaint'] = 'शिकायत'; $lang['view_all_complaints'] = 'सभी शिकायतें देखें'; $lang['ChoosePoliceStation'] = 'पुलिस स्टेशन चुनें'; /* Offences and Punishement Language starts here */ $lang['off_one'] = "कोणत्याही अभक्ष्य किंवा खराब वस्तू [कायदा] कलम 3 (1) (अ) लावून देणे]"; /* navigator*/ $lang['atrocity_tracking'] = 'अत्याचार ट्रैकिंग'; $lang['dashboard'] = 'डैशबोर्ड'; $lang['user_management'] = 'उपयोगकर्ता प्रबंधन'; $lang['case_management'] = 'मामला प्रबंधन'; $lang['logout'] = 'लोग आउट'; $lang['message'] = 'संदेश'; $lang['update'] = 'अद्यतन करें'; $lang['change_password'] = '<PASSWORD>ें'; $lang['update_profile'] = 'प्रोफ़ाइल अपडेट करें'; $lang['offences_and_compensations'] = 'अपराध और क्षतिपूर्ति'; $lang['post_complaints'] = 'पोस्ट शिकायतें'; $lang['show_all_cases'] = 'सभी मामलों को दिखाएं'; $lang['register_new_case'] = 'नया केस दर्ज करें'; $lang['show_all_offenders'] = 'सभी अपराधियों को दिखाएं'; $lang['show_all_user_complaints'] = 'सभी उपयोगकर्ता शिकायत दिखाएं'; <file_sep>/application/views/homepage/userregister.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Atrocity Tracking and Management</title> <!-- Tell the browser to be responsive to screen width --> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <!-- Bootstrap 3.3.7 --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/bootstrap/dist/css/bootstrap.min.css') ?>"/> <!-- Font Awesome --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/font-awesome/css/font-awesome.min.css') ?>"/> <!-- Ionicons --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/Ionicons/css/ionicons.min.css') ?>"/> <!-- Theme style --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/css/AdminLTE.min.css') ?>"/> <!-- AdminLTE Skins. Choose a skin from the css/skins folder instead of downloading all of them to reduce the load. --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/css/skins/skin-blue-light.css') ?>"/> <!-- Morris chart --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/morris.js/morris.css') ?>"/> <!-- jvectormap --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/jvectormap/jquery-jvectormap.css') ?>"/> <!-- Date Picker --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins//bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css') ?>"/> <!-- Daterange picker --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/bootstrap-daterangepicker/daterangepicker.css') ?>"/> <!-- bootstrap wysihtml5 - text editor --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css') ?>"/> <!-- DataTables --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/datatables.net-bs/css/dataTables.bootstrap.min.css') ?>"/> <!-- Sweetalert --> <link type="text/css" rel="stylesheet" href="<?= base_url('assets/plugins/sweetalert/sweetalert.css') ?>"/> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!-- jQuery 3 --> <script src="<?= base_url('assets/plugins/jquery/dist/jquery.min.js') ?>"></script> <!-- jQuery UI 1.11.4 --> <script src="<?= base_url('assets/plugins/jquery-ui/jquery-ui.min.js') ?>"></script> <!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip --> <script> $.widget.bridge('uibutton', $.ui.button); </script> <!-- Bootstrap 3.3.7 --> <script src="<?= base_url('assets/plugins/bootstrap/dist/js/bootstrap.min.js') ?>"></script> <!-- DataTables --> <script src="<?= base_url('assets/plugins/datatables.net/js/jquery.dataTables.min.js') ?>"></script> <script src="<?= base_url('assets/plugins/datatables.net-bs/js/dataTables.bootstrap.min.js') ?>"></script> <!-- daterangepicker --> <script src="<?= base_url('assets/plugins/moment/min/moment.min.js') ?>"></script> <script src="<?= base_url('assets/plugins/bootstrap-daterangepicker/daterangepicker.js') ?>"></script> <!-- datepicker --> <script src="<?= base_url('assets/plugins/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js') ?>"></script> <!-- Bootstrap WYSIHTML5 --> <script src="<?= base_url('assets/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js') ?>"></script> <!-- Slimscroll --> <script src="<?= base_url('assets/plugins/jquery-slimscroll/jquery.slimscroll.min.js') ?>"></script> <!-- FastClick --> <script src="<?= base_url('assets/plugins/fastclick/lib/fastclick.js') ?>"></script> <!-- AdminLTE App --> <script src="<?= base_url('assets/js/adminlte.min.js') ?>"></script> <!-- Sweetalert --> <script src="<?= base_url('assets/plugins/sweetalert/sweetalert.js') ?>"></script> <!-- AdminLTE for demo purposes --> <script src="<?= base_url('assets/js/demo.js') ?>"></script> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <!-- Google Font --> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic"> <script> var Geo = ""; function GeoLocaiton(Json) { Geo = Json; } var base_url = "<?= base_url(); ?>"; var role = "<?= $this->router->fetch_class(); ?>"; </script> </head> <body class="hold-transition skin-blue-light layout-top-nav"> <!-- Notifications --> <?php if (!empty($this->session->flashdata('ME_ERROR'))) : ?> <script> var msg = "<?= $this->session->flashdata('ME_ERROR') ?>"; swal("Oops...!", msg, "error") </script> <?php elseif (!empty($this->session->flashdata('ME_SUCCESS'))) : ?> <script> var msg = "<?= $this->session->flashdata('ME_SUCCESS') ?>"; swal("SUCCESS!", msg, "success") </script> <?php endif; ?> <div class="wrapper"> <header class="main-header"> <nav class="navbar navbar-static-top"> <div class="container"> <div class="navbar-header"> <a href="<?= base_url('index.php/homepage/index')?>" class="navbar-brand">Atrocity Case Management</a> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse"> <i class="fa fa-bars"></i> </button> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse pull-left" id="navbar-collapse"> <ul class="nav navbar-nav"> <ul class="nav navbar-nav"> <li class="active"><a href="<?= base_url('index.php/homepage/index') ?>">Home</a></li> <li><a href="#">Offences and Punishments</a></li> <li><a href="<?= base_url('index.php/administrator') ?>">Login</a></li> </ul> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> </header> <div class="content-wrapper"> <div class="container"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> New User Registration <small>Create New Profile</small> </h1> </section> <!-- Main content --> <section class="content"> <div class="row"> <!-- left column --> <div class="col-md-12"> <!-- general form elements --> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title">Personal Information</h3> </div> <!-- /.box-header --> <!-- form start --> <?php if($_SESSION['formError']!=null): ?> <p><?= $_SESSION['formError']; $_SESSION['formError'] = null?></p> <?php endif; ?> <form role="form" method="post" action="<?= base_url('index.php/homepage/UserRegisterSave') ?>"> <div class="box-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1"><?= $this->lang->line('name') ?> <span style="color: red ">*</span></label> <input type="name" class="form-control" id="PersonName" name="PersonName" placeholder="Enter Full Name" required="true" > </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputRole"><?= $this->lang->line('select') ?><span style="color: red ">*</span></label> <select class="form-control" id="Role" name="Role" placeholder="Select Role"> <option value="">Select Role</option> <?php foreach ($this->db->where(array("roleshow" => "Y"))->order_by("rolename", "asc")->get('roles')->result() as $detail) { ?> <option value="<?= $detail->roleid ?>"> <?= strtoupper($detail->rolename) ?> </option> <?php } ?> </select> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <?php echo form_error('UserName'); ?> <label for="User Name"><?= $this->lang->line('user_name') ?><span style="color: red ">*</span></label> <input type="text" class="form-control" id="UserName" name="UserName" placeholder="Enter User Name" value="<?php echo set_value('UserName'); ?>" required="true" > </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="Email ID"><?= $this->lang->line('email_id') ?><span style="color: red ">*</span></label> <input type="text" class="form-control" id="EmailID" name="EmailID" placeholder="Enter Email Id" required="true"> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <?php echo form_error('Password'); ?> <label for="Password"><?= $this->lang->line('password') ?><span style="color: red ">*</span></label> <input type="<PASSWORD>" class="form-control" name="Password" placeholder="Enter Password" value="<?php echo set_value('password'); ?>" required="` "> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="Confirmation Password"><?= $this->lang->line('confirmation_password') ?><span style="color: red ">*</span></label> <input type="<PASSWORD>" class="form-control" name="ConfirmationPassword" placeholder="Enter Confirmation Password"> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="Address1"><?= $this->lang->line('address1') ?><span style="color: red ">*</span></label> <input type="text" class="form-control" id="Address1" name="Address1" placeholder="Enter Address1"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="Address2"><?= $this->lang->line('address2') ?></label> <input type="text" class="form-control" id="Address2" name="Address2" placeholder="Enter Address2"> </div> </div> </div> <div class="row"> <div class="col-md-4"> <div class="form-group"> <label for="City"><?= $this->lang->line('city') ?><span style="color: red ">*</span></label> <input type="text" class="form-control" id="City" name="City" placeholder="Enter City"> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="State"><?= $this->lang->line('state') ?><span style="color: red ">*</span></label> <input type="text" class="form-control" id="State" name="State" placeholder="Enter State"> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="Country"><?= $this->lang->line('country') ?></label> <input type="text" class="form-control" id="Country" name="Country" placeholder="Enter Country"> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="Mobile Number"><?= $this->lang->line('mobile_number') ?><span style="color: red ">*</span></label> <input type="number" class="form-control" id="Mobile Number" name="MobileNumber" placeholder="Enter Mobile Number"> </div> </div> <div class="col-md-6"> <div class="form-group"> <?php echo form_error('AadhaarNumber'); ?> <label for="Aadhaar Number"><?= $this->lang->line('aadhaar_number') ?></label> <input type="number" class="form-control" id="AadhaarNumber" name="AadhaarNumber" placeholder="Enter Aadhaar Number "> </div> </div> </div> </div> <!-- /.box-body --> <div class="box-footer"> <button type="submit" class="btn btn-primary"><?= $this->lang->line('register') ?></button> </div> <!-- /.box --> </div> <!--/.col (left) --> </div> <!-- /.row --> </section> <!-- /.content --> </div> <!-- /.container --> </div> <!-- /.content-wrapper --> <footer class="main-footer"> Developed by <strong>RMK Engineering College</strong> and Designed by <a href="https://adminlte.io">Almsaeed Studio</a> </footer> </div> <!-- ./wrapper --> </body> </html><file_sep>/application/views/organization/offenders/offender_offences.php <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1><?= $this->lang->line('alloffenders') ?></h1> <ol class="breadcrumb"> <li><a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/index") ?>"><i class="fa fa-dashboard"></i><?= $this->lang->line('home') ?></a></li> <li class="active"><?= $this->lang->line('all_offenders') ?></li> </ol> </section> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-md-3"> <!-- Profile Image --> <div class="box box-primary"> <div class="box-body box-profile"> <h3 class="profile-username text-center"><?= $OffenderDetails['OffenderName'] ?></h3> <p class="text-muted text-center"> <?= $OffenderDetails['OffenderMobile'] ?></p> <ul class="list-group list-group-unbordered"> <li class="list-group-item"> <b>No of Offences</b> <a class="pull-right"></a> <br/> </li> <li class="list-group-item"> <b>Offender Age</b> <div class="pull-right"><?= $OffenderDetails['OffenderAge'] ?></div> </li> <li class="list-group-item"> <b>Offender Gender</b> <div class="pull-right"><?= $OffenderDetails['GenderName'] ?></div> </li> <li class="list-group-item"> <b>Offender State</b> <div class="pull-right"><?= $OffenderDetails['State'] ?></div> </li> <li class="list-group-item"> <b>Offender District</b> <div class="pull-right"><?= $OffenderDetails['District'] ?></div> </li> <li class="list-group-item"> <b>Offender City</b> <div class="pull-right"><?= $OffenderDetails['City'] ?></div> </li> </ul> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> <!-- /.col --> <div class="col-md-9"> <div class="nav-tabs-custom"> <ul class="nav nav-tabs"> <li class="active"><a href="#activity" data-toggle="tab" aria-expanded="true">Offence History of <?= $OffenderDetails['OffenderName'] ?></a></li> </ul> <div class="tab-content"> <div class="tab-pane active" id="activity"> <!-- Post --> <div class="post"> <table id="offenderoffences1" class="table table-bordered table-striped dataTable" role="grid" aria-describedby="example1_info"> <thead> <tr> <td width="50%" style="line-height: 10px"><b><?= $this->lang->line('offencename') ?></b></td> <td width="50%" style="line-height: 10px"><b><?= $this->lang->line('offence_date') ?></b></td> <td width="50%" style="line-height: 10px"><b><?= $this->lang->line('status') ?></b></td> <td width="50%" style="line-height: 10px"><b><?= $this->lang->line('actions') ?></b></td> </tr> <?php foreach ($OffenderCaseDetails as $case): ?> <tr> <td width="80%" style="line-height: 10px"><?= $case['OffenceName'] ?></td> <td width="80%" style="line-height: 10px"><?= $case['OffenceDate'] ?></td> <td width="80%" style="line-height: 10px"><?= $case['CaseStatus'] ?></td> <td> <a class="btn btn-xs btn-primary" href="<?= base_url('index.php/' . $this->router->fetch_class() . '/casehistory/show/' . $case['CaseId']) ?>" title="Edit" target="_blank"><i class="fa fa-eye"></i> View</a> </td> </tr> <?php endforeach; ?> </thead> <tbody></tbody> </table> </div> <!-- /.post --> </div> <!-- /.tab-pane --> </div> <!-- /.tab-content --> </div> <!-- /.nav-tabs-custom --> </div> <!-- /.col --> </div> </section> </div> <!-- /.row --><file_sep>/application/helpers/photo_helper.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); function photo($nodaftar) { $Findme = 'image'; $path = "/var/www/html/isis-apps/gambar_dasar/" . $nodaftar; // set upload path $ext = array('jpg', 'png', 'gif', 'JPG', 'PNG', 'GIF'); if (SysRun == "Local"): return $photo_path = "http://dummyimage.com/600x400/000/eaebf2.jpg&text=Your+Image"; foreach ($ext as $extentions) { $MyString = implode("-", get_headers('http://isis-apps.um.edu.my/gambar_dasar/' . $nodaftar . '.' . $extentions)); $pos = strpos($MyString, $Findme); if (!($pos === false)) { return 'http://isis-apps.um.edu.my/gambar_dasar/' . $nodaftar . '.' . $extentions; break; } } else: foreach ($ext as $extentions) { if (file_exists($path . '.' . $extentions)) { $file_path = $path . '.' . $extentions; $file_name = $nodaftar . "." . $extentions; break; } } // end foreach if (!$file_path) { $photo_path = base_url('public/images/blankuser.png'); } else { $photo_path = "http://isis-apps.um.edu.my/gambar_dasar/" . $file_name; } return $photo_path; endif; } // end function ?> <file_sep>/application/views/administrator/messages/compose.php <div class="content-wrapper"> <section class="content-header"> <h1><?= $this->lang->line('mailbox') ?></h1> <h1><?= $this->lang->line('mail_box')?></h1> <ol class="breadcrumb"> <li><a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/index") ?>"><i class="fa fa-dashboard"></i> <?= $this->lang->line('home') ?></a></li> <li class="active"><?= $this->lang->line('messages') ?></li> </ol> </section> <section class="content"> <div class="row"> <div class="col-md-9"> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title"><?= $this->lang->line('compose_new_message') ?></h3> </div> <!-- /.box-header --> <form role="form" method="post" action="<?= base_url('index.php/' . strtolower($this->router->fetch_class()) . "/EmailSave") ?> "> <div class="box-body"> <div class="form-group"> <label for="Email To"><?= $this->lang->line('to') ?></label> <select class="form-control" id="email" name="emailto" placeholder="Select Mail ID" required="true"> <option>Select User Name</option> <?php foreach ($this->db->where(array("isactive" => "Y"))->order_by("username", "asc")->join("roles", "roleid=role")->get('users')->result() as $detail) { ?> <option value="<?= $detail->user_id ?>"> <?= $detail->username . " - " . $detail->rolename ?> </option> <?php } ?> </select> </div> <div class="form-group"> <label for="Subject"></label> <input class="form-control" placeholder="<?= $this->lang->line('subject') ?>" name="subject"> </div> <div class="form-group"> <ul class="wysihtml5-toolbar" style=""></ul><li class="dropdown"> <a class="btn btn-default dropdown-toggle " data-toggle="dropdown"> <span class="glyphicon glyphicon-font"></span> <span class="current-font">Normal text</span> <b class="caret"></b> </a> <ul class="dropdown-menu"> <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="p" tabindex="-1" href="javascript:;" unselectable="on">Normal text</a></li> <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h1" tabindex="-1" href="javascript:;" unselectable="on">Heading 1</a></li> <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h2" tabindex="-1" href="javascript:;" unselectable="on">Heading 2</a></li> <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h3" tabindex="-1" href="javascript:;" unselectable="on">Heading 3</a></li> <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h4" tabindex="-1" href="javascript:;" unselectable="on">Heading 4</a></li> <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h5" tabindex="-1" href="javascript:;" unselectable="on">Heading 5</a></li> <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h6" tabindex="-1" href="javascript:;" unselectable="on">Heading 6</a></li> </ul> </li> <li> <div class="btn-group"> <a class="btn btn-default" data-wysihtml5-command="bold" title="CTRL+B" tabindex="-1" href="javascript:;" unselectable="on">Bold</a> <a class="btn btn-default" data-wysihtml5-command="italic" title="CTRL+I" tabindex="-1" href="javascript:;" unselectable="on">Italic</a> <a class="btn btn-default" data-wysihtml5-command="underline" title="CTRL+U" tabindex="-1" href="javascript:;" unselectable="on">Underline</a> <a class="btn btn-default" data-wysihtml5-command="small" title="CTRL+S" tabindex="-1" href="javascript:;" unselectable="on">Small</a> </div> </li> <li> <a class="btn btn-default" data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="blockquote" data-wysihtml5-display-format-name="false" tabindex="-1" href="javascript:;" unselectable="on"> <span class="glyphicon glyphicon-quote"></span> </a> </li> <li> <div class="btn-group"> <a class="btn btn-default" data-wysihtml5-command="insertUnorderedList" title="Unordered list" tabindex="-1" href="javascript:;" unselectable="on"> <span class="glyphicon glyphicon-list"></span> </a> <a class="btn btn-default" data-wysihtml5-command="insertOrderedList" title="Ordered list" tabindex="-1" href="javascript:;" unselectable="on"> <span class="glyphicon glyphicon-th-list"></span> </a> <a class="btn btn-default" data-wysihtml5-command="Outdent" title="Outdent" tabindex="-1" href="javascript:;" unselectable="on"> <span class="glyphicon glyphicon-indent-right"></span> </a> <a class="btn btn-default" data-wysihtml5-command="Indent" title="Indent" tabindex="-1" href="javascript:;" unselectable="on"> <span class="glyphicon glyphicon-indent-left"></span> </a> </div> </li> <div class="box"> <div class="box-header"> </div> <!-- /.comment body --> <!--<form>--> <div class="box-body pad"> <textarea class="textarea" placeholder="Type your email here" name="emaildetail" style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"></textarea> </div> <!-- </form>--> </div> </div> <div class="form-group"> <div class="btn btn-default btn-file"> <i class="fa fa-paperclip"></i> <?= $this->lang->line('attachment') ?> <input type="file" name="attachment"> </div> </div> </div> <!-- /.box-body --> <div class="box-footer"> <div class="pull-right"> <button type="submit" class="btn btn-primary"><i class="fa fa-envelope-o"></i> Send</button> </div> </div> </form> <!-- /.box-footer --> </div> <!-- /. box --> </div> </div> </section> </div> <file_sep>/application/views/layout/scriptfooter.php <!-- Library Java Script Starts Here!--> <script src="<?= base_url('assets/js/ajaxfetch.js') ?>"></script> <script src="<?= base_url('assets/js/app.js') ?>" type="text/javascript"></script> <script src="<?= base_url('assets/js/sqlLite.js') ?>" type="text/javascript"></script> <script src="<?= base_url('assets/js/php.min.js') ?>" type="text/javascript"></script> <!-- Library Java Script ENDS Here!--> </body> </html><file_sep>/application/helpers/debugdata_helper.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /* * function debugdata * */ function debugdata($data, $Type, $Output = "") { $obj = & get_instance(); // create ci object $obj->ModelLoad[0]['DB'][0] = "db"; switch ($Type) { case "db": foreach (($obj->ModelLoad) as $key => $val) { foreach (($val) as $keys => $Values) { foreach (($Values) as $Lkeys => $LValues) { $Model = explode("/", $LValues); if (empty($Output)) { var_dump($Model[count($Model) - 1]); echo $echo = "<pre>"; } $_Queries = ($keys == "DB") ? $obj->$Model[count($Model) - 1]->queries : $obj->$Model[count($Model) - 1]->um->queries; $QueriesTime = ($keys == "DB") ? $obj->$Model[count($Model) - 1]->query_times : $obj->$Model[count($Model) - 1]->um->query_times; foreach ($_Queries as $keyQ => $valQ) { $Queries[$keyQ . "-><span style='color:red;'>RunTime: " . round($QueriesTime[$keyQ], 3) . "</span>"] = $valQ; } if (empty($Output)) { print_r($Queries); echo $echo .= "</pre>"; } else { $return[$Model[count($Model) - 1]] = $Queries; } } } } return $return; break; case "": echo "<pre>"; print_r($data); echo "</pre>"; break; case "array": echo "<pre>"; if (is_array($data)) { $obj->array_run($data); } else { print_r($data); } echo "</pre>"; break; case "con": case "conn": echo "<pre>"; $DBerror = (($obj->db->db_debug) == "0") ? "Not Show DB Error" : "Show Db Error"; echo "<p>UserName = <b>" . ($obj->db->username); echo "</b></p><p>Server = <b>" . ($obj->db->hostname); echo "</b></p><p>DdSelected = <b>" . ($obj->db->database); echo "</b></p><p>Dderror = <b>" . $DBerror; echo "</b></p><p>DB_char_set = <b>" . ($obj->db->char_set); echo "</b></p><p>DB_collation = <b>" . ($obj->db->dbcollat); echo "</b></p><p>BenchmarkTime = <b>" . ($obj->db->benchmark) . "</b></p>"; echo "</pre>"; break; case "last": foreach (($obj->ModelLoad) as $key => $val) { foreach (($val) as $keys => $Values) { foreach (($Values) as $Lkeys => $LValues) { $Model = explode("/", $LValues); var_dump($Model[count($Model) - 1]); echo "<pre>"; $Queries = ($keys == "DB") ? $obj->$Model[count($Model) - 1]->queries : $obj->$Model[count($Model) - 1]->um->queries; print_r($Queries[count($Queries) - 1]); echo "Total Quires= " + count($Queries); echo "</pre>"; } } } break; } } ?> <file_sep>/application/core/MY_Controller.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class MY_Controller extends CI_Controller { function __construct() { parent::__construct(); $this->lang->load('message', $this->session->userdata('site_lang')); $this->layoutfolder = $this->config->item("layoutfolder"); //$this->encrypt->set_cipher(MCRYPT_BLOWFISH); $this->UserFrom(); $config = array("question_format" => "numeric", "operation" => "addition"); $userNameCnd = array("username" => $this->session->userdata("UserName")); $this->user = current($this->Adminmodel->CSearch($userNameCnd, "username as UserName", "usr", "", "", "", "", "", "", "")); $this->userid = current($this->Adminmodel->CSearch($userNameCnd, "user_id as UserId", "usr", "", "", "", "", "", "", "")); $this->userRole = current($this->Adminmodel->CSearch($userNameCnd, "role as UserRole", "usr", "Y", "Y", "", "", "", "", "")); $profileurl = $this->ShowProfileImage($_SESSION['UserId']); date_default_timezone_set('Asia/Kolkata'); } protected function UserFrom() { if ($this->agent->is_browser()) { return $this->UserAcess = $this->agent->platform() . ' and ' . $this->agent->browser() . ' - ' . $this->agent->version(); } elseif ($this->agent->is_robot()) { return $this->UserAcess = $this->agent->robot(); } elseif ($this->agent->is_mobile()) { return $this->UserAcess = $this->agent->mobile(); } else { return $this->UserAcess = 'Unidentified User Agent'; } } public function render($Render, $RenderData = null) { $Layout = "layout/body"; $this->render = $Render; $this->load->view($Layout, $RenderData); } public function Inti($Class) { $ClassNo = array(array("register"), "homepage" => array("forgotpwd")); if (!(in_array($this->router->fetch_method(), $ClassNo[$Class]))) { if (empty($_SESSION["UserId"])) { $AuthVal = $this->auth->Authencation("Y", "error"); if (!$AuthVal) { $this->session->set_flashdata('LoginError', 'User Name or Password is not matches'); redirect("/"); } } } $CtrlRole = $this->db->where(array("user_id" => $_SESSION["UserId"]))->join("roles", "roleid=role")->get("users")->row_array(); if ((!empty($CtrlRole)) && ($CtrlRole['rolename'] == strtoupper($Class))) { if (strtoupper($_SESSION["UserRole"]) == strtoupper($Class)) { return true; } else { redirect("/index.php/" . strtolower($CtrlRole['rolename']) . "/index"); } } else { if (!empty($CtrlRole['rolename'])) { redirect("/index.php/" . strtolower($CtrlRole['rolename']) . "/index"); } else { redirect("/error/index/InitiThrought"); } } } public function logout() { $this->session->sess_destroy(); session_unset(); session_destroy(); $this->session->set_userdata("Auth", "Y"); $_SESSION = null; exit($this->load->view("homepage/login", get_defined_vars(), true)); } public function accessdeined() { $this->render("accessdeined", get_defined_vars()); } public function SendEmail($EmailTo, $Message, $ReturnData, $Subject, $EmailBcc) { try { $mail = $this->emailConfig(); $mail->setFrom('<EMAIL>', 'Atrocity Case Management'); $mail->addAddress($EmailTo); // Add a recipient $mail->isHTML(true); // Set email format to HTML $mail->Subject = $Subject; $mail->Body = $Message; if (!$mail->Send()) { return 1; } else { return 0; } } catch (phpmailerException $e) { echo $e->errorMessage(); //Pretty error messages from PHPMailer } } protected function emailConfig() { $mail = new \PHPMailer\PHPMailer\PHPMailer(); $mail->isSMTP(); $mail->Host = 'tls://smtp.gmail.com:587'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = "<EMAIL>"; // SMTP username $mail->Password = "<PASSWORD>"; return $mail; } public function forms($option) { switch (strtolower($option)): case "password_reset": $this->render(strtolower($option), get_defined_vars()); break; endswitch; } /* Form Validation Starts Here */ public function form_validation($option) { switch (strtolower($option)) { case "user": $rules = array( array('field' => 'fullname', 'label' => 'Full Name ', 'rules' => 'required'), ); break; case "casehistory": $rules = array( array('field' => 'casehistory', 'label' => 'Case History ', 'rules' => 'required|max_length[400]'), ); break; case "password": $rules = array( array('field' => 'oldpassword', 'label' => 'Old Password', 'rules' => 'required'), array('field' => 'newpassword', 'label' => 'New Password', 'rules' => 'required'), array('field' => 'confirmationpassword', 'label' => 'Confirmation Password', 'rules' => 'required'), ); break; case "login": $rules = array( array('field' => 'emailid', 'label' => 'Email ID', 'rules' => 'required|valid_email'), array('field' => 'password', 'label' => 'Password', 'rules' => 'required'), ); break; case "forgot": $rules = array( array('field' => 'emailid', 'label' => 'Email ID', 'rules' => 'required|valid_email'), array('field' => 'verificationcode', 'label' => 'Verification Code', 'rules' => 'required'), array('field' => 'newpassword', 'label' => 'New Password', 'rules' => 'required'), array('field' => 'confirmationpassword', 'label' => 'Confirmation Password', 'rules' => 'required|match[newpassword]'), array('field' => 'mobilenumber', 'label' => 'Mobile Number', 'rules' => 'required'), ); break; case "userreg": $rules = array( array('field' => 'PersonName', 'label' => 'Person Name', 'rules' => 'required|max_length[30]'), array('field' => 'EmailID', 'label' => 'Email ID', 'rules' => 'valid_email'), array('field' => 'Password', 'label' => 'Password', 'rules' => 'required|max_length[10]'), array('feild' => 'ConfirmationPassword', 'label' => 'Confirmation Password', 'rules' => 'required'), array('field' => 'Address1', 'label' => 'Address1', 'rules' => 'required'), array('feild' => 'Address2', 'label' => 'Address2', 'rules' => ''), array('field' => 'AadhaarNumber', 'label' => 'Aadhaar Number', 'rules' => ''), array('field' => 'MobileNumber', 'label' => 'Mobile Number', 'rules' => 'required|integer'), array('field' => 'City', 'label' => 'Name', 'City' => 'required'), array('field' => 'State', 'label' => 'Name', 'State' => ''), array('field' => 'UserName', 'label' => 'User Name', 'rules' => 'required|max_length[35]'), array('field' => 'Country', 'label' => 'Country', 'rules' => ''), array('field' => 'Role', 'label' => 'Role', 'rules' => 'required') ); break; case "profile": $rules = array( array('field' => 'Name', 'label' => 'Name', 'rules' => 'required|max_length[30]'), array('field' => 'EmailID', 'label' => 'Email ID', 'rules' => 'valid_email'), array('field' => 'Address1', 'label' => 'Address1', 'rules' => 'required'), array('feild' => 'Address2', 'label' => 'Address2', 'rules' => ''), array('field' => 'AadhaarNumber', 'label' => 'Aadhaar Number', 'rules' => ''), array('field' => 'MobileNumber', 'label' => 'Mobile Number', 'rules' => 'required|integer'), array('field' => 'City', 'label' => 'city', 'rules' => 'required'), array('field' => 'State', 'label' => 'State', 'rules' => ''), array('field' => 'UserName', 'label' => '<NAME>', 'rules' => 'required'), array('field' => 'Country', 'label' => 'Country', 'rules' => ''), array('field' => 'Role', 'label' => 'Role', 'rules' => 'required'), array('field' => 'Image', 'label' => 'Image', 'rules' => '') ); break; case "email": $rules = array( array('field' => 'subject', 'label' => 'Subject', 'rules' => 'required|max_length[45]'), array('field' => 'emaildetail', 'label' => 'Email Detail', 'rules' => 'required|max_length[400]'), ); break; case "cases": $rules = array( array('field' => 'victimname', 'label' => 'Name', 'rules' => 'required'), array('field' => 'victimemail', 'label' => 'Email ID', 'rules' => 'valid_email'), array('field' => 'victimaddress', 'label' => 'Address', 'rules' => 'required'), array('field' => 'victimaadhaar', 'label' => 'Aadhaar Number', 'rules' => ''), array('field' => 'victimmobile', 'label' => 'Mobile Number', 'rules' => 'required|integer'), array('field' => 'victimcity', 'label' => 'City', 'rules' => 'required'), array('field' => 'victimdistrict', 'label' => 'Victim District', 'rules' => 'required'), array('field' => 'victimstate', 'label' => 'Victim State', 'rules' => ''), array('field' => 'offendername', 'label' => 'Name', 'rules' => 'required'), array('field' => 'offenderaddress', 'label' => 'Address', 'rules' => 'required'), array('field' => 'offendermobile', 'label' => 'Mobile Number', 'rules' => 'integer'), array('field' => 'offendercity', 'label' => 'City', 'rules' => 'required'), array('field' => 'ifothers', 'label' => 'If Others', 'rules' => 'max_length[100]'), array('field' => 'offenderdistrict', 'label' => 'Offender District', 'rules' => 'required'), array('field' => 'offencedate', 'label' => 'Offence Date', 'rules' => 'required'), array('field' => 'victimgender', 'label' => 'Gender', 'rules' => 'required'), array('field' => 'casedescription', 'label' => 'Case Description', 'rules' => 'required|max_length[400]'), array('field' => 'victimdob', 'label' => 'Date Of Birth', 'rules' => 'required'), array('field' => 'victimemail', 'label' => 'Email ID', 'rules' => 'valid_email'), array('field' => 'offendergender', 'label' => 'Gender', 'rules' => 'required'), array('field' => 'offenderstate', 'label' => 'Offender State', 'rules' => ''), array('field' => 'fir_no', 'label' => 'FIR Number', 'rules' => 'required'), array('field' => 'offenderage', 'label' => 'Age', 'rules' => 'required'), ); break; case "fir": $rules = array( array('field' => 'fir_no', 'label' => 'FIR No', 'rules' => 'required'), array('field' => 'police_station', 'label' => 'Police Station', 'rules' => 'required'), array('field' => 'district', 'label' => 'District', 'rules' => 'required'), array('field' => 'year', 'label' => 'Year', 'rules' => 'required'), array('field' => 'date', 'label' => 'Date', 'rules' => 'required'), array('field' => 'act1', 'label' => 'Act 1', 'rules' => 'required'), array('field' => 'section1', 'label' => 'Section1', 'rules' => 'required'), array('field' => 'act2', 'label' => 'Act 2', 'rules' => ''), array('field' => 'section2', 'label' => 'Section2', 'rules' => ''), array('field' => 'offence_day', 'label' => 'Offence Day', 'rules' => 'required'), array('field' => 'date_from', 'label' => 'Date From', 'rules' => 'required'), array('field' => 'date_to', 'label' => 'Date To', 'rules' => 'required'), array('field' => 'time_from', 'label' => 'Time From', 'rules' => ''), array('field' => 'time_to', 'label' => 'Time To', 'rules' => ''), array('field' => 'receiveddate', 'label' => 'Received Date', 'rules' => 'required'), array('field' => 'time', 'label' => 'Time', 'rules' => 'required'), array('field' => 'place_of_occurrence', 'label' => 'Place Of Occurrence', 'rules' => 'required'), array('field' => 'type_of_information', 'label' => 'Type Of Information', 'rules' => 'required'), array('field' => 'complianantname', 'label' => 'Complianant name', 'rules' => 'required'), array('field' => 'complianantdob', 'label' => 'Complianant Dob ', 'rules' => 'required'), array('field' => 'nationality', 'label' => 'Nationality', 'rules' => 'required'), array('field' => 'occupation', 'label' => 'Occupation', 'rules' => ''), array('field' => 'address', 'label' => 'Address', 'rules' => 'required'), array('field' => 'suspectparticulars', 'label' => 'Suspect Particulars', 'rules' => 'required'), ); break; case "complaints": $rules = array( array('field' => 'policeassigned', 'label' => 'Police Assigned to', 'rules' => 'required'), array('field' => 'policecomments', 'label' => 'Police Comments', 'rules' => 'required'), ); break; case "usercomplaint": $rules = array( array('field' => 'comments', 'label' => 'User Complaint', 'rules' => 'required'), ); break; } $this->form_validation->set_rules($rules); if ($this->form_validation->run() == FALSE): return FALSE; else : return TRUE; endif; } /* Form Validation Ends Here */ /* Function for saving Cases in Database Starts here */ public function CaseRegisterSave() { $postData = $this->input->post(); if ($this->form_validation("cases")): //verify offender in offender master $condition = array("offendername" => $postData['offendername'], "offendermobile" => $postData['offendermobile']); $select = "offendername as OffenderName , offendermobile as OffenderMobile"; $response = $this->Adminmodel->CSearch($condition, $select, "off_mst", "Y", "Y", "", "", "", "", ""); if (empty($response)) { $condition1 = array("offenderid" => ""); $DBData = array( "offendername" => $postData['offendername'], "offenderaddress" => $postData['offenderaddress'], "offendergender" => $postData['offendergender'], "offendermobile" => $postData['offendermobile'], "offenderemail" => $postData['offenderemail'], "offendercity" => $postData['offendercity'], "offenderdistrict" => $postData['offenderdistrict'], "offenderage" => $postData['offenderage'], "offenderstate" => $postData['offenderstate'], ); $response1 = $this->Adminmodel->AllInsert($condition1, $DBData, "", "off_mst"); } $condition = array("offendername" => $postData['offendername'], "offendermobile" => $postData['offendermobile']); $select = "offenderid as OffenderId"; $response = $this->Adminmodel->CSearch($condition, $select, "off_mst", "", "Y", "", "", "", "", ""); $condition = array("caseid" => ""); $DBData = array( "offenderid" => $response['OffenderId'], "offid" => $postData['offenece'], "userid" => "1", "fir_no" => $postData['fir_no'], "victimname" => $postData['victimname'], "victimaddress" => $postData['victimaddress'], "vicitmdob" => $postData['victimdob'], "victimgender" => $postData['victimgender'], "victimmobile" => $postData['victimmobile'], "victimemail" => $postData['victimemail'], "victimaadhar" => $postData['victimaadhar'], "victimcity" => $postData['victimcity'], "victimdistrict" => $postData['victimdistrict'], "victimstate" => $postData['victimstate'], "casedescription" => $postData['casedescription'], "offencedate" => $postData['offencedate'], "casestatus" => "1", "policeassignedto" => $_SESSION['UserId'], "organizationassignedto" => "3" ); $response1 = $this->Adminmodel->AllInsert($condition, $DBData, "", "case"); if (!empty($response1)): $Message = $this->load->view("emaillayouts/registercase", get_defined_vars(), true); $Subject = "Atrocity Case Management - New Case Registered"; $this->SendEmail(trim('<EMAIL>'), $Message, "N", $Subject, ""); $this->session->set_flashdata('ME_SUCCESS', 'Case Registred Successfully'); else: $this->session->set_flashdata('ME_ERROR', 'Data not Saved. Kindly Re Enter'); endif; else: $_SESSION['formError'] = validation_errors(); $this->session->set_flashdata('ME_FORM', "ERROR"); endif; redirect('index.php/' . strtolower($this->router->fetch_class()) . '/cases/allcases'); } /* Function for saving Cases in Database Ends here */ public function CaseHistoryVictimShow($id) { $condition = array("cases.caseid" => $id); $select = "offname as OffenceName, offcompensation as Compensation,caseid as CaseID ,fir_no as FirNumber , victimname as VictimName, victimaddress as VictimAddress , vicitmdob as VictimDob , gender_name as VictimGender , victimmobile as VictimMobile, victimemail as VictimEmail,cityname as VictimCity,districtname as VictimDistrict,statename as VictimState,casedescription as CaseDescription,casestatus as CaseStatus,case_status_name as CaseStatusName"; return $this->Adminmodel->CSearch($condition, $select, "case", "", true); } public function CaseHistoryOffenderShow($id) { $condition = array("cases.caseid" => $id); $select = "offendername as OffenderName , offenderaddress as OffenderAddress , gender_name as OffenderGender,cityname as OffenderCity,districtname as OffenderDistrict,statename as OffenderState"; return $this->Adminmodel->CSearch($condition, $select, "case", "", true); } public function CaseHistoryComments($id) { $condition = array("casehistory.caseid" => $id); $select = "casehistorydesc as CaseHistoryDesc,casehistory.createdat as CreatedOn,users.name as CreatedBy,users.imageurl as ImageURL,rolename as RoleName,casehistory.imageurl as Attachment"; return $this->Adminmodel->CSearch($condition, $select, "casehis", "Y", true, "", "", "", "", "", "casehistoryid"); } /* Maps Ajax Cases list statrs from here */ public function map_ajax_list($options = "", $id = "") { switch (strtolower($options)) { case "cases": $Condition = array("casestatus" => '1', "victimdistrict" => $id); $TableListname = "case"; $ColumnOrder = array('fir_no', 'victimname', 'victimmobile', 'casestatus'); $ColumnSearch = array('fir_no', 'victimname', 'victimmobile'); $OrderBy = array('caseid' => 'desc'); break; case "solvedcases": $Condition = array("casestatus" => '2', "victimdistrict" => $id); $TableListname = "case"; $ColumnOrder = array('fir_no', 'victimname', 'victimmobile', 'casestatus'); $ColumnSearch = array('fir_no', 'victimname', 'victimmobile'); $OrderBy = array('caseid' => 'desc'); break; case "pendingcases": $Condition = array("casestatus" => '3', "victimdistrict" => $id); $TableListname = "case"; $ColumnOrder = array('fir_no', 'victimname', 'victimmobile', 'casestatus'); $ColumnSearch = array('fir_no', 'victimname', 'victimmobile'); $OrderBy = array('caseid' => 'desc'); break; default: $Condition = array(); break; } $list = $this->Adminmodel->get_datatables($TableListname, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, false); $data = array(); $no = $_POST['start']; foreach ($list as $logNotice) { $no++; $row = array(); $row[] = $logNotice->fir_no; $row[] = $logNotice->victimname; $row[] = $logNotice->victimmobile; //add html for action $data[] = $row; } $output = array( "draw" => $_POST['draw'], "recordsTotal" => $this->Adminmodel->count_all($TableListname, $Condition), "recordsFiltered" => $this->Adminmodel->count_filtered($TableListname, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, "N"), "data" => $data, ); //output to json format echo json_encode($output); } /* Maps Ajax Cases list ends from here */ /* Function for saving Case History in Database Starts here */ public function CaseHistorySave() { $postData = $this->input->post(); $condition = array("casehistoryid" => ""); if ($this->form_validation("casehistory")): if (($_FILES['file']['name']) != null): $imageName = "attachment_" . rand(1000, 99999999999) . "." . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION); if ($this->uploadAttachment($imageName) == false): $this->session->set_flashdata('ME_ERROR', 'File Upload Failed'); else: $DBData = array( "casehistorydesc" => $postData['casehistory'], "userid" => $_SESSION['UserId'], "caseid" => $postData['caseid'], "imageurl" => $imageName ); $response = $this->Adminmodel->AllInsert($condition, $DBData, "", "casehis"); endif; else: $DBData = array( "casehistorydesc" => $postData['casehistory'], "userid" => $_SESSION['UserId'], "caseid" => $postData['caseid'], ); $response = $this->Adminmodel->AllInsert($condition, $DBData, "", "casehis"); endif; if (!empty($response)): if (strtolower($_SESSION['UserRoleName']) == 'police'): $EmailAddress = $this->fetchorganisationemail($postData['caseid']); else: $EmailAddress = $this->fetchpoliceemail($postData['caseid']); endif; $Message = $this->load->view("emaillayouts/commentupdate", get_defined_vars(), true); $Subject = "Atrocity Case Management - New Comment Updated"; $this->SendEmail($EmailAddress['EmailId'], $Message, "N", $Subject, ""); $this->session->set_flashdata('ME_SUCCESS', 'Comment updated successfully'); else: $this->session->set_flashdata('ME_ERROR', 'Data not Saved. Kindly Re Enter'); endif; else: $_SESSION['formError'] = validation_errors(); $this->session->set_flashdata('ME_FORM', "ERROR"); endif; redirect($_SERVER['HTTP_REFERER']); } /* Function for saving Case History in Database Ends here */ private function fetchorganisationemail($caseid) { $condition = array("cases.caseid" => $caseid); $select = "organizationassignedto as orgid"; $id = $this->Adminmodel->CSearch($condition, $select, "case", "", true); if (!empty($id)): $condition = array("users.user_id" => $id['orgid']); $select = "email as EmailId"; return $this->Adminmodel->CSearch($condition, $select, "usr", "", true); else: return NULL; endif; } private function fetchpoliceemail() { $condition = array("cases.caseid" => $caseid); $select = "policeassignedto as policeid"; $id = $this->Adminmodel->CSearch($condition, $select, "case", "", true); if (!empty($id)): $condition = array("users.user_id" => $id['policeid']); $select = "email as EmailId"; return $this->Adminmodel->CSearch($condition, $select, "usr", "", true); else: return NULL; endif; } /* Function for fetching cases files from views starts here */ public function cases($options = null, $id = "") { $render = ""; switch (strtolower($options)) { case "newcase"; $render = "showregistercase"; break; case "allcases"; $render = "showallcases"; break; case "allsolvedcases"; $render = "showallsolvedcases"; break; case "allpendingcases"; $render = "showallpendingcases"; break; case "districtcases"; $render = "districtcases"; $districtID = $id; break; case "alloffenders"; $render = "showalloffenders"; break; case "firshow"; $render = "fir"; break; default: $caseregister = $this->getcase_register(); $caseallcases = $this->getcase_allcases(); $casehistory = $this->getcase_casehistory(); $render = "cases"; break; } $this->render($render, get_defined_vars()); } /* Function for fetching cases files from views ends here */ /* Function for fetching offender's offences file from views starts here */ public function offenders($options = null, $id = null) { $render = ""; switch (strtolower($options)) { case "alloffences"; $render = "offender_offences"; $OffenderDetails = $this->OffenderDetail($id); $OffenderCaseDetails = $this->OffenderCaseDetail($id); break; default: $caseregister = $this->getcase_register(); $caseallcases = $this->getcase_allcases(); $casehistory = $this->getcase_casehistory(); $render = "cases"; break; } $this->render($render, get_defined_vars()); } /* Function for fetching offender's offences file from views ends here */ private function OffenderDetail($id) { $condition = array("cases.offenderid" => $id); $select = "offendername as OffenderName,offendermobile as OffenderMobile,case_status_name as CaseStatus,offenderage as OffenderAge,cityname as City,districtname as District,statename as State,gender_name as GenderName"; return $this->Adminmodel->CSearch($condition, $select, "case", "", true, "", "", "", "", ""); } private function OffenderCaseDetail($id) { $condition = array("cases.offenderid" => $id); $select = "offname as OffenceName,offencedate as OffenceDate,case_status_name as CaseStatus,cases.caseid as CaseId"; return $this->Adminmodel->CSearch($condition, $select, "case", "Y", true, "", "", "", "", ""); } /* Function for fetching allusers file from views starts here */ public function user($options = null) { $render = ""; switch (strtolower($options)) { case "allusers"; $render = "showallusers"; break; default: $caseregister = $this->getcase_register(); $caseallcases = $this->getcase_allcases(); $casehistory = $this->getcase_casehistory(); $render = "cases"; break; } $this->render($render, get_defined_vars()); } /* Function for fetching allusers file from views ends here */ /* Function for fetching casehistory file from views starts here */ public function casehistory($options = null, $id = null) { $render = ""; switch (strtolower($options)) { case "show"; $render = "casehistory"; $casevictimdatabase = $this->CaseHistoryVictimShow($id); $caseoffenderdatabase = $this->CaseHistoryOffenderShow($id); $casecomments = $this->CaseHistoryComments($id); break; default: $caseregister = $this->getcase_register(); $caseallcases = $this->getcase_allcases(); $casehistory = $this->getcase_casehistory(); $render = "cases"; break; } $this->render($render, get_defined_vars()); } /* Function for fetching casehistory file from views ends here */ /* Function for fetching Messages files from views starts here */ public function messages($options = null, $id = "") { $render = ""; switch (strtolower($options)) { case "show"; $render = "inbox"; $inboxMessages = $this->Emailinbox(); break; case "composemail"; $render = "compose"; break; case "sent"; $render = "sent"; $SentMessages = $this->Emailsent(); break; default: $caseregister = $this->getcase_register(); $caseallcases = $this->getcase_allcases(); $casehistory = $this->getcase_casehistory(); $render = "cases"; break; } $this->render($render, get_defined_vars()); } /* Function for fetching email files from views ends here */ public function profileshow($id) { $condition = array("user_id" => $id); $select = "name as Name ,role as Role ,username as Username , email as EmailID ,address1 as Address1,address2 as Address2,city as City,state as State,country as Country,mobilenumber as Mobilenumber,aadhar as Aadhaarnumber"; return $this->Adminmodel->CSearch($condition, $select, "usr", "", "", "", "", "", "", ""); } /* Ajax Function for fetching users starts here */ public function users_ajax_list($options = null) { switch (strtolower($options)) { case "users": $Condition = array(); $TableListname = "usr"; $ColumnOrder = array('name', 'username', 'mobilenumber', 'address1'); $ColumnSearch = array('name', 'username', 'mobilenumber', 'address1'); $OrderBy = array('user_id' => 'desc'); break; default: $Condition = array(); break; } $list = $this->Adminmodel->get_datatables($TableListname, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, true); $data = array(); $no = $_POST['start']; foreach ($list as $UserNotice) { $no++; $row = array(); $row[] = $UserNotice->name; $row[] = $UserNotice->username; $row[] = $UserNotice->mobilenumber; $row[] = $UserNotice->address1; $row[] = $UserNotice->cityname; //add html for action // $row[] = '<a class="btn btn-xs btn-primary" href="' . base_url('index.php/' . $this->router->fetch_class() . '/allusers' . $UserNotice->userid) . '" title="Edit" target="_blank"><i class="fa fa-eye"></i> View</a>'; $data[] = $row; } $output = array( "draw" => $_POST['draw'], "recordsTotal" => $this->Adminmodel->count_all($TableListname, $Condition), "recordsFiltered" => $this->Adminmodel->count_filtered($TableListname, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, d), "data" => $data, ); //output to json format echo json_encode($output); } /* Ajax Function for fetching users ends here */ /* Ajax function for fetching Cities from District Starts Here */ public function FetchCities() { // Ajaxcall Fetch Board $DistrictID = $this->input->post('id', TRUE); $condition = array("districtref" => $DistrictID); $select = "cityid as CityID ,cityname as Cityname"; $CityDetails = $this->Adminmodel->CSearch($condition, $select, "city", "Y", "", "", "", "", "", ""); $output = "<option value=''>Select City</option>"; foreach ($CityDetails as $row) { $output .= "<option value='" . $row['CityID'] . "'>" . strtoupper($row['Cityname']) . "</option>"; } echo $output; } /* Ajax function for fetching Cities from District Ends Here */ /* Function for count of Users,Cases Starts Here */ public function TotalUserCount() { $condition = array(); $response = $this->Adminmodel->count_all("usr", $condition); return $response; } public function TotalCaseCount() { $condition = array(); $response = $this->Adminmodel->count_all("case", $condition); return $response; } public function PendingCaseCount() { $condition = array("casestatus" => '3'); $response = $this->Adminmodel->count_all("case", $condition); return $response; } public function SolvedCaseCount() { $condition = array("casestatus" => '2'); $response = $this->Adminmodel->count_all("case", $condition); return $response; } /* Function for count of Users,Cases Ends Here */ public function NewCaseShow() { $condition = array("casestatus" => '1'); $select = "fir_no as FIR,victimname as VictimName , victimmobile as VictimMobile "; return $this->Adminmodel->CSearch($condition, $select, "case", "Y", "", "", "", "", "", ""); } public function SolvedCaseShow() { $condition = array("casestatus" => '2'); $select = "fir_no as FIR,victimname as VictimName , victimmobile as VictimMobile "; return $this->Adminmodel->CSearch($condition, $select, "case", "Y", "", "", "", "", "", ""); } public function PendingCaseShow() { $condition = array("casestatus" => '3'); $select = "fir_no as FIR,victimname as VictimName , victimmobile as VictimMobile "; return $this->Adminmodel->CSearch($condition, $select, "case", "Y", "", "", "", "", "", ""); } public function passwordchange() { $postData = $this->input->post(); if ($this->form_validation("password")): echo "<pre>"; print_r($postData); exit(); else: $this->session->set_flashdata('ME_ERROR', 'Form Validation Failed'); endif; redirect($_SERVER['HTTP_REFERER']); } public function forgotsave() { $postData = $this->input->post(); if ($this->form_validation("forgot")): echo "<pre>"; print_r($postData); exit(); else: $this->session->set_flashdata('ME_ERROR', 'Form Validation Failed'); endif; redirect($_SERVER['HTTP_REFERER']); } /* Ajax Function for fetching offenders starts here */ public function offenders_ajax_list($options = null) { switch (strtolower($options)) { case "offenders": $Condition = array(); $TableListname = "off_mst"; $ColumnOrder = array('offenderid', 'offendername', 'gender_name', 'offendermobile', 'cityname', 'districtname'); $ColumnSearch = array('offendername'); $OrderBy = array('offenderid' => 'desc'); break; default: $Condition = array(); break; } $list = $this->Adminmodel->get_datatables($TableListname, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, true); $data = array(); $no = $_POST['start']; foreach ($list as $logNotice) { $no++; $row = array(); $row[] = $logNotice->offendername; $row[] = $logNotice->gender_name; $row[] = $logNotice->offendermobile; $row[] = $logNotice->cityname; $row[] = $logNotice->districtname; //add html for action $row[] = '<a class="btn btn-xs btn-primary" href="' . base_url('index.php/' . $this->router->fetch_class() . '/offenders/alloffences/' . $logNotice->offenderid) . '" title="Edit" target="_blank"><i class="fa fa-eye"></i> View</a>'; $data[] = $row; } $output = array( "draw" => $_POST['draw'], "recordsTotal" => $this->Adminmodel->count_all($TableListname, $Condition), "recordsFiltered" => $this->Adminmodel->count_filtered($TableListname, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, true), "data" => $data, ); //output to json format echo json_encode($output); } /* Ajax Function for fetching offenders ends here */ public function loginsave() { $postData = $this->input->post(); if ($this->form_validation("login")): echo "<pre>"; print_r($postData); exit(); else: $this->session->set_flashdata('ME_ERROR', 'Form Validation Failed'); endif; redirect($_SERVER['HTTP_REFERER']); } public function userregister() { $postData = $this->input->post(); if ($this->form_validation("userreg")): echo "<pre>"; print_r($postData); exit(); else: $this->session->set_flashdata('ME_ERROR', 'Form Validation Failed'); endif; redirect($_SERVER['HTTP_REFERER']); } public function profilesave() { $postData = $this->input->post(); if ($this->form_validation("profile")): echo "<pre>"; print_r($postData); exit(); else: $this->session->set_flashdata('ME_ERROR', 'Form Validation Failed'); endif; redirect($_SERVER['HTTP_REFERER']); } public function EmailSave() { $postData = $this->input->post(); if ($this->form_validation("email")): $condition1 = array("msgid" => ""); $DBData = array( "msgfrom" => $_SESSION['UserId'], "msgto" => $postData['emailto'], "msgdetails" => $postData['emaildetail'], // "subject" => $postData['subject'], ); $response1 = $this->Adminmodel->AllInsert($condition1, $DBData, "", "pm"); $this->session->set_flashdata('ME_SUCCESS', 'Form Validation Successfully'); else: $this->session->set_flashdata('ME_ERROR', 'Form Validation Failed'); endif; redirect($_SERVER['HTTP_REFERER']); } public function Emailsent() { $condition = array("msgfrom" => $_SESSION['UserId'],); $select = "name as SenderName,msgfrom as MessageFrom,msgto as MessageTo,msgsubject as MessageSubject,msgdetails as Messagedetails,privatemessages.createdat as CreatedOn"; return $this->Adminmodel->CSearch($condition, $select, "pm", "Y", true); } public function Emailinbox() { $condition = array("msgto" => $_SESSION['UserId'],); $select = "name as SenderName,msgfrom as MessageFrom,msgto as MessageTo,msgsubject as MessageSubject,msgdetails as Messagedetails,privatemessages.createdat as CreatedOn"; return $this->Adminmodel->CSearch($condition, $select, "pm", "Y", "Y", "", "", "", "", ""); } public function showallusers() { $this->render("showallusers", get_defined_vars()); } public function updateprofile() { $render = ""; $userdatabase = $this->profileshow($_SESSION['UserId']); $render = "updateprofile"; $this->render($render, get_defined_vars()); } public function offencesandcompensations() { $render = ""; $userdatabase = $this->profileshow($id); $render = "offencesandcompensations"; $this->render($render, get_defined_vars()); } public function changepassword() { $render = ""; $userdatabase = $this->profileshow($id); $render = "changepassword"; $this->render($render, get_defined_vars()); } public function FirRegisterSave() { $postData = $this->input->post(); if ($this->form_validation("fir")): $condition = array("fir_id" => ""); $DBData = array( "district" => $postData['district'], "policestation" => $postData['police_station'], "year" => $postData['year'], "date" => $postData['date'], "firno" => $postData['fir_no'], "act1" => $postData['act1'], "act2" => $postData['act2'], "section1" => $postData['section1'], "section2" => $postData['section2'], "offenceday" => $postData['offence_day'], "offencedatefrom" => $postData['date_from'], "offencedateto" => $postData['date_to'], "timefrom" => $postData['time_from'], "timeto" => $postData['time_to'], "inforecvddate" => $postData['receiveddate'], "infoerecvdtime" => $postData['time'], "infotype" => $postData['type_of_information'], "offenceplace" => $postData['place_of_occurrence'], "complianantname" => $postData['complianantname'], "complianantdob" => $postData['complianantdob'], "nationality" => $postData['nationality'], "occupation" => $postData['occupation'], "address" => $postData['address'], "suspectparticulars" => $postData['suspectparticulars'], ); $response = $this->Adminmodel->AllInsert($condition, $DBData, "", "fir"); endif; } /* Ajax Function for fetching all cases */ public function cases_ajax_list($options = null) { switch (strtolower($options)) { case "cases": $Condition = array(); $TableListname = "case"; $ColumnOrder = array('fir_no', 'victimname', 'victimmobile', 'offendername', 'offencedate', 'case_status_name'); $ColumnSearch = array('fir_no', 'victimname', 'victimmobile'); $OrderBy = array('caseid' => 'desc'); break; case "solvedcases": $Condition = array("casestatus" => '2'); $TableListname = "case"; $ColumnOrder = array('fir_no', 'victimname', 'victimmobile', 'offendername', 'offencedate', 'case_status_name'); $ColumnSearch = array('fir_no', 'victimname', 'victimmobile', 'case_status_name'); $OrderBy = array('caseid' => 'desc'); break; case "pendingcases": $Condition = array("casestatus" => '3'); $TableListname = "case"; $ColumnOrder = array('fir_no', 'victimname', 'victimmobile', 'offendername', 'offencedate', 'case_status_name'); $ColumnSearch = array('fir_no', 'victimname', 'victimmobile', 'case_status_name'); $OrderBy = array('caseid' => 'desc'); break; default: $Condition = array(); break; } $list = $this->Adminmodel->get_datatables($TableListname, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, true); $data = array(); $no = $_POST['start']; foreach ($list as $logNotice) { $no++; $row = array(); $row[] = $logNotice->fir_no; $row[] = $logNotice->victimname; $row[] = $logNotice->victimmobile; $row[] = $logNotice->offendername; $row[] = $logNotice->offencedate; $row[] = $logNotice->case_status_name; //add html for action $row[] = '<a class="btn btn-xs btn-primary" href="' . base_url('index.php/' . $this->router->fetch_class() . '/casehistory/show/' . $logNotice->caseid) . '" title="Edit" target="_blank"><i class="fa fa-eye"></i> View</a>'; $data[] = $row; } $output = array( "draw" => $_POST['draw'], "recordsTotal" => $this->Adminmodel->count_all($TableListname, $Condition), "recordsFiltered" => $this->Adminmodel->count_filtered($TableListname, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, true), "data" => $data, ); //output to json format echo json_encode($output); } public function upload($filename) { $config['allowed_types'] = 'jpg|jpeg'; $config['file_name'] = $filename; $config['max_size'] = '1024'; $config['encrypt_name'] = FALSE; $config['overwrite'] = true; $config['upload_path'] = './assets/img/'; $this->load->library('upload', $config); if (!$this->upload->do_upload("file")): return false; else: return true; endif; } public function uploadAttachment($filename) { $config['allowed_types'] = 'pdf|jpg|jpeg'; $config['file_name'] = $filename; $config['max_size'] = '1024'; $config['encrypt_name'] = FALSE; $config['overwrite'] = true; $config['upload_path'] = './assets/attachment/'; $this->load->library('upload', $config); if (!$this->upload->do_upload("file")): return false; else: return true; endif; } public function UpdateProfileSave() { $postData = $this->input->post(); if ($this->form_validation("profile")): $Condition = array("user_id" => $_SESSION['UserId']); $imagename = current($this->Adminmodel->CSearch($Condition, "imageurl as imagename", "usr", "", TRUE)); if ($imagename == null): $imageName = "profile_" . rand(1000, 99999999999) . "." . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION); else: $imageName = $imagename; endif; if ($this->upload($imageName) == false): $this->session->set_flashdata('ME_ERROR', 'File Upload Failed'); else: $condition = array("user_id" => $_SESSION['UserId']); $DBData = array( "name" => $postData['Name'], "username" => $postData['UserName'], "address1" => $postData['Address1'], "address2" => $postData['Address2'], "city" => $postData['City'], "state" => $postData['State'], "country" => $postData['Country'], "mobilenumber" => $postData['MobileNumber'], "aadhar" => $postData['AadhaarNumber'], "email" => $postData['EmailID'], "imageurl" => $imageName ); $response = $this->Adminmodel->AllInsert($condition, $DBData, "", "usr"); endif; if (!empty($response)): $Message = $this->load->view("emaillayouts/userprofileupdate", get_defined_vars(), true); $Subject = "Atrocity Case Management - Your profile has been updated."; // $this->SendEmail(trim($result['EmailID']), $Message, "N", $Subject, ""); $this->session->set_flashdata('ME_SUCCESS', 'Profile Changed Successfully'); else: $this->session->set_flashdata('ME_ERROR', 'Data not Saved. Kindly Re Enter'); endif; endif; $this->load->view('homepage/dashboard'); } /* function to show profile Image starts here */ public function ShowProfileImage($id) { $condition = array("user_id" => $id); $select = "imageurl as ImageURL"; $url = $this->Adminmodel->CSearch($condition, $select, "usr", "", "", "", "", "", "", ""); if ($url != null): return $url['ImageURL']; else: return 'user2-160x160.jpg'; endif; } /* function to show profile Image ends here */ /* Case Status Save Starts Here */ public function CaseStatusSave() { $postData = $this->input->post(); $condition = array("caseid" => $postData['caseid']); $DBData = array( "casestatus" => $postData['casestatus']); $response = $this->Adminmodel->AllInsert($condition, $DBData, "", "case"); if (!empty($response)): $this->session->set_flashdata('ME_SUCCESS', 'Case Status Changed Successfully'); else: $this->session->set_flashdata('ME_ERROR', 'Data not Saved. Kindly Recheck'); endif; redirect($_SERVER['HTTP_REFERER']); } public function ComplaintCommentsSave() { $postData = $this->input->post(); if ($this->form_validation("complaints")): $condition = array("complaintsid" => $postData['id']); $DBData = array( "comp_assignedto" => $postData['policeassigned'], "comp_police_comments" => $postData['policecomments'], "isassignedto" => "Y" ); $response = $this->Adminmodel->AllInsert($condition, $DBData, "", "comp"); if (!empty($response)): $this->session->set_flashdata('ME_SUCCESS', 'Case Status Changed Successfully'); else: $this->session->set_flashdata('ME_ERROR', 'Data not Savedsdsd. Kindly Recheck'); endif; else: $this->session->set_flashdata('ME_ERROR', 'Form Validation Failed'); endif; redirect('index.php/' . strtolower($this->router->fetch_class()) . '/complaint/allcomplaints'); } } <file_sep>/application/language/english/message_lang.php <?php /* english language */ $lang['mobile_number'] = 'Mobile Number'; $lang['submit'] = 'Submit'; $lang['login'] = 'Log In'; $lang['name'] = 'Name'; $lang['select'] = 'Select'; $lang['email_id'] = 'Email ID'; $lang['user_name'] = 'User Name'; $lang['address2'] = 'Address2'; $lang['address1'] = 'Address1'; $lang['city'] = 'City'; $lang['state'] = 'State'; $lang['aadhaar_number'] = 'Aadhaar Number'; $lang['country'] = 'Country'; $lang['old_password'] = '<PASSWORD>'; $lang['password'] = '<PASSWORD>'; $lang['new_password'] = '<PASSWORD>'; $lang['change_password'] = '<PASSWORD>'; $lang['edit_password'] = '<PASSWORD>'; $lang['profile_change'] = 'Profile Change'; $lang['edit_profile'] = 'Edit Profile'; $lang['personal_information'] = 'Personal Information'; $lang['confirmation_password'] = '<PASSWORD>'; $lang['register'] = 'Register'; $lang['update_profile'] = 'Update Profile'; $lang['signup'] = 'SignUp'; $lang['all_users']='All Users'; $lang['cases']='Cases'; $lang['new_cases']='New Cases'; $lang['pending_cases']='Pending Cases'; $lang['solved_cases']='Solved Cases'; /*Case Management Starts*/ $lang['case_management']='Case Management'; $lang['registeration_form']='Registration Form'; $lang['fir_no']='FIR Number'; $lang['victim_details']='Victim Details'; $lang['offender_details']='Offender Details'; $lang['case_details']='Case Details'; $lang['case_id']='Case Id'; $lang['if_others']='If Others'; $lang['case_description']='Case Description'; $lang['all_users'] = 'All Users'; $lang['cases'] = 'Cases'; $lang['new_cases'] = 'New Cases'; $lang['pending_cases'] = 'Pending Cases'; $lang['solved_cases'] = 'Solved Cases'; $lang['postcomplaints'] = 'Post Complaints'; $lang['complainthere'] = 'Complaint Here'; $lang['postyourcomplaintshere'] = 'Post Your Complaints Here'; /* Case Management Starts */ $lang['case_management'] = 'Case Management'; $lang['registeration_form'] = 'Registration Form'; $lang['fir_no'] = 'FIR Number'; $lang['victim_details'] = 'Victim Details'; $lang['offender_details'] = 'Offender Details'; $lang['case_details'] = 'Case Details'; $lang['if_others'] = 'If Others'; $lang['case_description'] = 'Case Description'; $lang['offender_address'] = 'Address'; $lang['victim_address'] = 'Address'; $lang['gender'] = 'Gender'; $lang['offence_date'] = 'Offence Date'; $lang['victim_name'] = '<NAME>'; $lang['victimdob'] = 'Date Of Birth'; $lang['age'] = 'Age'; $lang['offender_name'] = 'Offender Name'; $lang['status'] = 'Status'; $lang['actions'] = 'Actions'; $lang['all_cases'] = 'All Cases'; $lang['offencename'] = 'Offence Name'; $lang['alloffenders'] = 'All Offenders'; $lang['offendermobile'] = 'Offender Mobile'; $lang['male'] = 'Male'; $lang['female'] = 'Female'; $lang['others'] = 'Others'; $lang['select_gender'] = 'Select gender'; $lang['all_solvedcases'] = 'All Solved Cases'; $lang['all_pendingcases'] = 'All Pending Cases'; $lang['district'] = 'District'; $lang['show'] = 'Show'; $lang['entries'] = 'entries'; $lang['search'] = 'Search'; /* Case Management Ends Here */ /* Log Managment Starts Here */ $lang['log_mgnt'] = 'Log Managment'; $lang['more_info'] = 'More Info'; $lang['notice'] = 'Notice'; /* Log Managment Ends Here */ /* case history starts here */ $lang['post'] = 'Post'; $lang['casehistory'] = 'Case History'; $lang['postedcomments'] = 'Posted Comments'; $lang['commenthere'] = 'Please enter your comment here'; $lang['typeyourcommenthere'] = 'Type your comment here'; /* case history ends here */ /* Dashboard Starts Here */ $lang['dashboard'] = 'Dashboard'; $lang['control_panel'] = 'Control Panel'; $lang['total_users'] = 'Total Users'; $lang['total_cases'] = 'Total Cases'; $lang['solved_cases'] = 'Solved Cases'; $lang['pending_cases'] = 'Pending Cases'; $lang['map'] = 'https://www.maharashtra.gov.in:443/Images/mapMaharashtraB.jpg'; /* Fir Format starts here */ $lang['fir_form'] = 'FIR Form'; $lang['fir_no'] = 'Fir No.'; $lang['police_station'] = 'Police Station'; $lang['year'] = 'Year'; $lang['date'] = 'Date'; $lang['act1'] = 'Act1'; $lang['section1'] = 'Section1'; $lang['act2'] = 'Act2'; $lang['section2'] = 'Section2'; $lang['offence_day'] = 'Offence Day'; $lang['date_from'] = 'Date From'; $lang['date_to'] = 'Date To'; $lang['time_from'] = 'Time From'; $lang['time_to'] = 'Time To'; $lang['information_received_at_police_station'] = 'Information Received At Police Station'; $lang['time'] = 'Time'; $lang['type_of_information'] = 'Type Of Information'; $lang['place_of_occurrence'] = 'Place Of Occurrence'; $lang['complianant/informant'] = 'Complianant/Informant'; $lang['complianantname'] = 'Complianant Name'; $lang['complianantdob'] = 'Complianant DOB'; $lang['nationality'] = 'Nationality'; $lang['occupation'] = 'Occupation'; $lang['address'] = 'Address'; $lang['suspectparticulars'] = 'Suspect Particulars'; $lang['send_to_sjsa'] = 'Send to Social Justice And Special Assitance'; /* fir format ends here */ /* bread crumb */ $lang['home'] = 'Home'; $lang['dashboard'] = 'Dashboard'; $lang['cases'] = 'Cases'; $lang['new_cases'] = 'New Cases'; $lang['all_cases'] = 'All Cases'; $lang['all_offenders'] = 'All Offenders'; $lang['all_pending_cases'] = 'All Pending Cases'; $lang['all_solved_cases'] = 'All Solved Cases'; $lang['logs'] = 'Logs'; $lang['all'] = 'All'; $lang['errors'] = 'Errors'; $lang['notices'] = 'Notices'; $lang['warnings'] = 'Warnings'; $lang['show_notices'] = 'Show Notices'; $lang['all_offences'] = 'All Offences'; $lang['users'] = 'Users'; $lang['all_users'] = 'All Users'; $lang['mobile_number'] = 'Mobile Number'; $lang['offender_offence'] = 'Offender Offences'; $lang['offencereport'] = 'Offence Report'; $lang['to'] = 'To:'; $lang['subject'] = 'Subject:'; $lang['compose_new_message'] = 'Compose New Message'; $lang['type_your_email_here'] = 'Type your email here'; $lang['act'] = 'Offence Act'; $lang['compensation'] = 'Compensation'; $lang['mail_box'] = 'Mail Box'; $lang['compose'] = 'Compose'; $lang['folder'] = 'Folder'; $lang['inbox'] = 'Inbox'; $lang['sent'] = 'Sent'; $lang['bold'] = 'Bold'; $lang['italic'] = 'Italic'; $lang['underline'] = 'Underline'; $lang['normal_text'] = 'Normal Text'; $lang['attachment'] = 'Attachment'; $lang['compose_new_message'] = 'Compose New Message'; $lang['police_details'] = 'Police Details'; $lang['organisation_details'] = 'Organisation Deatils'; /* complaints */ $lang['complaint_action'] = 'Complaint Action'; $lang['police_details'] = 'Police Details'; $lang['comments'] = 'Comments'; $lang['ChoosePoliceStation'] = 'Choose Police Station'; /* navigator*/ $lang['atrocity_tracking'] = 'Atrocity Tracking'; $lang['dashboard'] = 'Dashboard'; $lang['user_management'] = 'User Management'; $lang['case_management'] = 'Case Management'; $lang['logout'] = 'Logout'; $lang['message'] = 'Message'; $lang['update'] = 'Update'; $lang['change_password'] = 'Change Password'; $lang['update_profile'] = 'Update Profile'; $lang['offences_and_compensations'] = 'Offences and Compensations'; $lang['post_complaints'] = 'Post Complaints'; $lang['show_all_cases'] = 'Show all Cases'; $lang['register_new_case'] = 'Register New Case'; $lang['show_all_offenders'] = 'Show all Offenders'; $lang['show_all_user_complaints'] = 'Show all User Complaints'; /* Offences and Punishement Language starts here*/ $lang['off_one']="Putting any inedible or obnoxious substance [Section 3(1)(a) of the Act]"; /* Offences and Punishement Language ends here*/<file_sep>/application/views/organization/updateprofile/updateprofile.php <div class="content-wrapper" style="min-height: 990px;"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> <?= $this->lang->line('update_profile') ?> <small> <?= $this->lang->line('edit_profile') ?></small> </h1> </section> <!-- Main content --> <section class="content"> <div class="row"> <!-- left column --> <div class="col-md-12"> <!-- general form elements --> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title"><?= $this->lang->line('personal_information') ?></h3> </div> <!-- /.box-header --> <!-- form start --> <form role="form" method="post" action="<?= base_url('index.php/' . strtolower($this->router->fetch_class()) . "/UpdateProfileSave") ?> " autocomplete="off" enctype="multipart/form-data"> <div class="box-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1"><?= $this->lang->line('name') ?></label> <input type="name" class="form-control" id="Name" name="Name" placeholder="" value="<?php echo $userdatabase['Name']; ?>" </div> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputRole"><?= $this->lang->line('select') ?></label> <select class="form-control" id="Role" name="Role" placeholder="Select Role" > <option>Select Role</option> <option>Police</option> <option>Victim</option> <option>Organisation</option> </select> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="User Name"><?= $this->lang->line('user_name') ?></label> <input type="text" class="form-control" id="UserName" name="UserName" placeholder="" value="<?php echo $userdatabase['Username']; ?>" > </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="Email ID"><?= $this->lang->line('email_id') ?></label> <input type="text" class="form-control" id="Email ID" name="EmailID" data-rule-required="true" data-rule-email="true" placeholder="" value="<?php echo $userdatabase['EmailID']; ?>"> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="Address1"><?= $this->lang->line('address1') ?></label> <input type="text" class="form-control" id="Address1" name="Address1" placeholder="" value="<?php echo $userdatabase['Address1']; ?>"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="Address2"><?= $this->lang->line('address2') ?></label> <input type="text" class="form-control" id="Address2" name="Address2" placeholder="" value="<?php echo $userdatabase['Address2']; ?>"> </div> </div> </div> <div class="row"> <div class="col-md-4"> <div class="form-group"> <label for="City"><?= $this->lang->line('city') ?></label> <input type="text" class="form-control" id="City" name="City" placeholder="" value="<?php echo $userdatabase['City']; ?>"> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="State"><?= $this->lang->line('state') ?></label> <input type="text" class="form-control" id="State" name="State" placeholder="" value="<?php echo $userdatabase['State']; ?>"> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="Country"><?= $this->lang->line('country') ?></label> <input type="text" class="form-control" id="Country" name="Country" placeholder="" value="<?php echo $userdatabase['Country']; ?>"> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="Mobile Number"><?= $this->lang->line('mobile_number') ?></label> <input type="number" class="form-control" id="Mobile Number" name="MobileNumber" placeholder="" value="<?php echo $userdatabase['Mobilenumber']; ?>"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="Aadhaar Number"><?= $this->lang->line('aadhaar_number') ?></label> <input type="number" class="form-control" id="Aadhaar Number" name="AadhaarNumber" placeholder="" value="<?php echo $userdatabase['Aadhaarnumber']; ?>"> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputFile">Image</label> <input type="file" id="exampleInputFile" name="file" accept="image/x-jpg,image/jpeg"> </div> </div> </div> </div> <!-- /.box-body --> <div class="box-footer"> <button type="submit" class="btn btn-primary"><?= $this->lang->line('submit') ?></button> </div> </form> <!-- /.box --> </div> <!--/.col (left) --> </div> <!-- /.row --> </section> <!-- /.content --> </div><file_sep>/application/libraries/Errorreport.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /** * Arugement Validation CodeIgniter implementation * * PHP version 5 * * @category CodeIgniter * @package Bug Tracker CI * @author <NAME> (<EMAIL>) * @version 0.1 */ class Errorreport { public function __construct() { $this->obj = & get_instance(); } public function Bug($message, $UserInfo = null, $RetunInfo = null) { $OutSideUrlAccess = curl_init("http://smart-ip.net/geoip-json"); if (empty($UserInfo)): $OutSideUrlAccess = curl_init("http://www.telize.com/geoip"); curl_setopt($OutSideUrlAccess, CURLOPT_RETURNTRANSFER, true); curl_setopt($OutSideUrlAccess, CURLOPT_REFERER, "http://www.telize.com/geoip"); $UserInfo = curl_exec($OutSideUrlAccess); $UserInfo = (array) (json_decode($UserInfo)); if (!empty($RetunInfo)): return $UserInfo; endif; endif; $Bug = $this->obj->load->database('default', TRUE); $Condition = array("ae_al_ref_id" => $this->obj->AuditRefID, "ae_message" => $message); $Bug->where($Condition); $ReturnData = $Bug->get("audit_error"); $ReturnData = $ReturnData->result_array(); $DBData = array( "ae_server_ip" => $_SERVER['SERVER_ADDR'], "ae_lang" => $UserInfo['latitude'], "ae_long" => $UserInfo['longitude'], "ae_isp" => $UserInfo['isp'], "ae_city" => $UserInfo['city'], "ae_ip" => $UserInfo['ip'] ); $Bug->set($DBData); if (empty($ReturnData)) { $Bug->set($Condition); $Bug->insert("audit_error"); } else { $Bug->where($Condition); $Bug->update("audit_error"); } } function GetIpAdd() { $OutSideUrlAccess = curl_init("http://www.telize.com/geoip"); curl_setopt($OutSideUrlAccess, CURLOPT_RETURNTRANSFER, true); curl_setopt($OutSideUrlAccess, CURLOPT_REFERER, "http://www.telize.com/geoip"); $UserInfo = curl_exec($OutSideUrlAccess); $UserInfo = (json_decode($UserInfo)); return $UserInfo->ip; } } <file_sep>/application/views/user/offencesandpunishments/offencesandpunishments.php <div class="content-wrapper" style="min-height: 990px;"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> Offences and Punishments <small>List of Offences and Punishments</small> </h1> </section> <!-- Main content --> <section class="content"> <div class="row"> <!-- left column --> <div class="col-md-12"> <!-- general form elements --> <div class="box box-primary"> <!-- /.box-header --> <div class="box-body"> <table class="table table-bordered"> <tbody> <tr> <th style="width: 10px">S.No</th> <th>NAME OF THE OFFENCE</th> <th>PUNISHMENT</th> </tr> <tr> <td>1.</td> <td><?= $this->lang->line('off_one') ?> </td> <td rowspan="5">One lakh rupees to the victim. Payment to then victim be made as follows: (i) 10 per cent. at First Information Report (FIR) stage for serial numbers (2) and (3) and 25 percent at FIR stage for serial numbers (1), (4) and (5); (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 40 per cent. when the accused are convicted by the lower court for serial numbers (2) and (3) and likewise 25 percent for serial numbers (1), (4) and (5). </td> </tr> <tr> <td>2.</td> <td>Dumping excreta, sewage, carcasses or any other obnoxious substance [Section 3(1)(b) of the Act] </td> </tr> <tr> <td>3.</td> <td>Dumping excreta, waste matter, carcasses with intent to cause injury, insult or annoyance [Section 3(1)(c) of the Act] </td> </tr> <tr> <td>4.</td> <td>Garlanding with footwear or parading naked or semi-naked[Section 3(1)(d) of the Act] </td> </tr> <tr> <td>5.</td> <td>Forcibly commiting acts such as removing clothes, forcible tonsuring of head, removing moustaches, painting face or body [Section 3(1)(e) of the Act] </td> </tr> <tr> <td>6.</td> <td>Wrongful occupation or cultivation of land [Section 3(1)(f) of the Act]  </td> <td rowspan="6"> One lakh rupees to the victim.  Payment to be made as follows: (i) Payment of 25 per cent. First Information Report (FIR) stage; (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. when the accused are convicted by the lower court. </td> </tr> <tr> <td>7.</td> <td>Wrongful dispossession of land or premises or interfering with the rights, including forest rights. [Section 3(1)(g) of the Act]  </tr> <tr> <td>8.</td> <td> Begar or other forms of forced or bonded labour [Section 3(1)(h) of the Act] </td> </tr> <tr> <td>9.</td> <td>Compelling  to dispose or carry human or animal carcasses, or to dig graves [Section 3(1)(i) of the Act]  </td> </tr> <tr> <td>10.</td> <td>Making a member of the Scheduled Castes or the Scheduled Tribes to do manual scavenging or employing him for such purpose [Section 3(1)(j) of the Act]  </td> </tr> <tr> <td>11.</td> <td>Performing, or promoting dedication of a Scheduled Caste or a Scheduled Tribe woman as  a devadasi [Section 3(1)(k) of the  Act]  </td> </tr> <tr> <td>12.</td> <td>Prevention from voting, filing nomination [Section 3(1)( l ) of the Act]  </td> <td rowspan="4">Eighty-five thousand rupees to the victim. Payment to be made as follows: (i) 25 per cent. at First Information Report (FIR) stage; (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. when the accused are convicted by the lower court. </td> </tr> <tr> <td>13.</td> <td>Forcing, intimidating or obstructing a holder of office of Panchayat or Municipality from performing duties [Section 3(1)(m) of the Act]  </td> </tr> <tr> <td>14.</td> <td>After poll violence and imposition of social and economic boycott [Section 3(1)(n) of the Act]  </td> </tr> <tr> <td>15.</td> <td> Committing any  offence  under  this Act  for having voted or not having voted for a particular candidate [Section 3(1)(o) of the Act]  </td> </tr> <tr> <td>16.</td> <td>Instituting false, malicious or vexatious legal proceedings [Section 3(1)(p) of the Act]    </td> <td>Eighty-five thousand rupees to the victim or reimbursement of actual legal expenses and damages, whichever is less.  Payment to be made as follows: (i)  25 per cent. at First Information Report (FIR) stage; (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. when the accused are convicted by the lower court. </td> </tr> <tr> <td>17.</td> <td>Giving false and frivolous information to a public servant [Section 3(1)(q) of the Act]    </td> <td>One lakh rupees to the victim or reimbursement of actual legal expenses and damages, whichever is less.  Payment to be made as follows: (i) 25 per cent.  at First Information Report (FIR) stage; (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. when the accused are convicted by the lower court. </td> </tr> <tr> <td>18.</td> <td>Intentional insult or intimidation to humiliate in any place within public view [Section 3(1)(r) of the Act]    </td> <td rowspan="5">One lakh rupees to the victim. Payment to be made as follows: (i) 25 per cent. at First Information Report (FIR) stage; (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. when the accused are convicted by the lower court. </td> </tr> <tr> <td>19.</td> <td>Abusing by caste name in any place within public view [Section 3(1)(s) of the Act]    </td> </tr> <tr> <td>20.</td> <td>Destroying, damaging or defiling any object held sacred or in high esteem [ Section 3(1)(t} of the Act] </td> </tr> <tr> <td>21.</td> <td>Promoting feelings of enmity, hatred or ill-will [ Section 3(1)(u) of the Act]    </td> </tr> <tr> <td>22.</td> <td>Disrespecting by words or any other means of any late person held in high esteem [ Section 3(1)(v) of the Act]     </td> </tr> <tr> <td>23.</td> <td>Intentionally touching a Scheduled Caste or a Scheduled Tribe woman without consent, using acts or gestures,   as an act of sexual nature, [ Section 3(1)(w) of the Act]     </td> <td>Two lakh rupees to the victim. Payment to be made as follows: (i) 25 per cent. at First Information Report (FIR) stage; (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. when the accused are convicted by the lower court. </td> </tr> <tr> <td>24.</td> <td>Section 326B of the Indian Penal Code (45 of 1860)--Voluntarily throwing or attempting to throw acid. [Section 3(2)(va)  read with Schedule to the Act]     </td> <td>(a) Eight lakh and twenty-five thousand rupees to the victim with burns exceeding and 2 per cent and above burns on face or in case of functional impairment of eye, ear, nose and mouth and or burn injury on body exceeding 30 per cent; (b) four lakh and fifteen thousand rupees  to the victim with burns between 10 per cent.  to 30 per cent. on the body; (c) eighty-five thousand rupees to the victim with burns less than 10 per cent. on the body other than on face.    In addition, the State Government or Union territory Administration shall take full responsibility for the treatment of the victim of acid attack.     The  payment in terms of items (a) to (c) are to be made as follows: (i) 50 per cent. at First Information Report (FIR) stage; (ii) 50 per cent.  after receipt of medical report. </td> </tr> <tr> <td>25.</td> <td>Section 354 of the Indian Penal Code (45 of 1860) -- Assault or criminal force to woman with intent to outrage her modesty. [Section 3(2) (va) read with Schedule to the Act] </td> <td>Two lakh rupees to the victim. Payment to be made as follows: (i) 50 per cent. at First Information Report (FIR) stage; (ii) 25 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. on conclusion of trial by the lower court. </td> </tr> <tr> <td>26.</td> <td>Section 354A of the Indian Penal Code (45 of 1860)--Sexual harassment and punishment for sexual harassment. [Section 32) (va) read with Schedule to the Act] </td> <td>Two lakh rupees to the victim.  Payment to be made as follows:  (i) 50 per cent. at First Information Report (FIR) stage; (ii) 25 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. on conclusion of trial by the lower court. </td> </tr> <tr> <td>27.</td> <td>Section 354 B of the Indian Penal Code (45 of 1860)-- Assault or use of criminal force to woman with intent to disrobe [ Section 3(2)(va) read with Schedule to the Act] </td> <td>Two lakh rupees to the victim. Payment to be made as follows:  (i) 50 per cent. at First Information Report (FIR) stage; (ii) 25 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. on conclusion of trial by the lower court. </td> </tr> <tr> <td>28.</td> <td>Section 354 C of the Indian Penal Code (45 of 1860)-- Voyeurism. [Section 3(2)(va) read with Schedule to the Act] </td> <td>Two lakh rupees to the victim. Payment to be made as follows: (i) 10 per cent. at First Information Report (FIR) stage (ii) 50 per cent. when the charge sheet is sent to the court. (iii) 40 per cent. when the accused are convicted by the lower court. </td> </tr> <tr> <td>29.</td> <td>Section 354 D of the Indian Penal Code (45 of 1860) -- Stalking.   [Section 3(2)(va) read with Schedule to the Act] </td> <td>Two lakh rupees to the victim. Payment to be made as follows: (i) 10 per cent. at First Information Report (FIR) stage; (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 40 per cent. when the accused are convicted by the lower court. </td> </tr> <tr> <td>30.</td> <td>Section 376B of the Indian Penal Code (45 of 1860)-- Sexual intercourse by husband upon his wife during separation. [Section 3(2)(va) read with Schedule to the Act] </td> <td>Two lakh rupees to the victim. Payment to be made as follows: (i) 50 per cent. after medical examination and confirmatory medical report; (ii) 25 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. when the accused are convicted by the lower court. </td> </tr> <tr> <td>31.</td> <td>Section 376C of the Indian Penal Code (45 of 1860) -- Sexual intercourse by a person in authority. [Section 3(2)(va) read with Schedule to the Act] </td> <td>Four lakh rupees to the victim. Payment to be made as follows: (i) 50 per cent. after medical examination and confirmatory medical report; (ii) 25 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. on conclusion of trial by the lower court. </td> </tr> <tr> <td>32.</td> <td>Section 509 of the Indian Penal Code (45 of 1860)-- Word, gesture or act intended to insult the modesty of a woman. [Section 3(2)(va) read with Schedule to the Act] </td> <td>Two lakh rupees to the victim. Payment to be made as follows: (i) 25 per cent. at First Information Report (FIR) stage; (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. when the accused are convicted by the lower court. </td> </tr> <tr> <td>33.</td> <td>Fouling or corrupting of water [ Section 3(1)(x) of the Act]   </td> <td>Full cost of restoration of normal facility, including cleaning when the water is fouled, to be borne by the concerned State Government or Union territory Administration. In addition, an amount of eight lakh twenty-five thousand rupees shall be deposited with the District Magistrate for creating community assets of the nature to be decided by the District Authority in consultation with the Local Body.  </td> </tr> <tr> <td>34.</td> <td> Denial of customary right of passage to a place of public resort or obstruction from using or accessing  public resort  [ Section 3(1)(y) of the Act]    </td> <td>Four lakh twenty-five thousand rupees to the victim and cost of restoration of right of passage by the concerned State Government or Union territory Administration.  Payment to be made as follows: (i) 25 per cent. at First Information Report (FIR) stage; (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. when the accused are convicted by the lower court. </td> </tr> <tr> <td>35.</td> <td>Forcing of causing to leave house, village, residence  desert  place of residence [Section 3(1)(z) of the Act]    </td> <td>Restoration of the site or right to stay in house, village or other place of residence by the concerned State Government or Union territory Administration  and relief  of one lakh rupees to the victim and reconstruction of the house at Government cost, if destroyed. Payment to be made as follows: (i) 25 per cent. at First Information Report (FIR) stage; (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. when the accused are convicted by the lower court. </td> </tr> <tr> <td>36.</td> <td>A. using common property resources of an area, or burial or cremation ground equally with others or using any river, stream, spring, well, tank, cistern, water-tap or other watering place, or any bathing ghat, any public conveyance, any road, or passage [Section 3(1)(za)(A) of the Act] (B) mounting or riding bicycles or motor cycles or wearing footwear or new clothes in public places or taking out wedding procession, or mounting a horse or any other vehicle during wedding processions [Section 3(1)(za)(B) of the Act] (C) entering any place of worship which is open to the public or other persons professing the same religion or taking part in, or taking out, any religious, social or cultural processions including jatras [Section 3(1)(za)(C) of the Act] (D) entering any educational institution, hospital, dispensary, primary health centre, shop or place of public entertainment or any other public place; or using any utensils or articles meant for public use in any place open to the public[Section 3(1)(za)(D) of the Act] (E) practicing any profession or the carrying on of any occupation, trade or business or employment in any job which other members of the public, or any section thereof, have a right to use or have access to [Section 3(1)(za)(E) of the Act] </td> <td>(A):  Restoration of the right using common property resources of an area, or burial or cremation ground equally with others or using any river, stream, spring, well, tank, cistern, water-tap or other watering place, or any bathing ghat, any public conveyance, any road, or passage equally with others, by the concerned State Government or Union Territory Administration and relief of one lakh rupees to the victim. Payment to be made as follows: (i) 25 per cent. at First Information Report (FIR) stage; (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. when the accused are convicted by the lower court. (B):  Restoration of the right of mounting or riding bicycles or motor cycles or wearing footwear or new clothes in public places or taking out wedding procession, or mounting a horse or any other vehicle during wedding processions, equally with others by the concerned State Government or Union territory Administration and relief of one lakh rupees to the victim. Payment to be made as follows: (i) Payment of 25 per cent. at First Information Report (FIR) stage; (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. when the accused are convicted by the lower court;  (C):  Restoration of the right of entering any place of worship which is open to the public or other persons professing the same religion or taking part in, or taking out any religious procession or jatras, as is open to the public or other persons professing the same religion, social or cultural processions including jatras, equally with other persons, by the concerned State Government or Union territory Administration and relief of one lakh rupees to the victim. Payment to be made as follows: (i) 25 per cent. at First Information Report (FIR) stage (ii) 50 per cent. when the charge sheet is sent to the court. (iii) 25 per cent. when the accused are convicted by the lower court.  (D):  Restoration of the right of entering any educational institution, hospital, dispensary, primary health centre, shop or place of public entertainment or any other public place; or using any utensils or articles meant for public use in any place open to the public, equally with other persons by the concerned State Government or Union territory Administration and relief of one lakh rupees to the victim. Payment to be made as follows: (i) 25 per cent. at First Information Report (FIR) stage; (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. when the accused are convicted by the lower court.  (E):  Restoration of the right of practicing any profession or the carrying on of any occupation, trade or business or employment in any job which other members of the public, or any section thereof, have a right to use or have access to, by the concerned State Government/Union territory Administration and relief of one lakh rupees to the victim. Payment to be made as follows: (i) 25 per cent.  at First Information Report (FIR) stage; (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. when the accused are convicted by the lower court. </td> </tr> <tr> <td>37.</td> <td>Causing physical harm or mental agony on the allegation of being a witch or practicing witchcraft or being a witch [Section 3(1)(zb) of the Act] </td> <td>One lakh rupees to the victim and also commensurate with the indignity, insult, injury and defamation suffered by the victim. Payment to be made as follows: (i) 25 per cent. at First Information Report (FIR) stage; (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. when the accused are convicted by the lower court. </td> </tr> <tr> <td>38.</td> <td>Imposing or threatening a social or economic boycott. [Section 3(1)(zc) of the Act] </td> <td>Restoration of provision of all economic and social services equally with other persons, by the concerned State Government or Union territory Administration and relief of one lakh rupees to the victim. To be paid in full when charge sheet is sent to the lower court. </td> </tr> <tr> <td>39.</td> <td>Giving or fabricating false evidence [Section 3(2)(i) and  (ii)  of the Act] </td> <td> Four lakh fifteen thousand rupees to the victim. Payment to be made as follows: (i) 25 per cent. at First Information Report (FIR) stage; (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. when the accused are convicted by the lower court. </td> </tr> <tr> <td>40.</td> <td>Committing offences under the Indian Penal Code (45 of 1860) punishable with imprisonment for a term of ten years or more [Section 3(2) of the Act] </td> <td>Four lakh rupees to the victim and or his dependents. The amount would vary, if specifically otherwise provided in this Schedule. Payment to be made as follows: (i) 25 per cent. at First Information Report (FIR) stage; (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. when the accused are convicted by the lower court. </td> </tr> <tr> <td>41.</td> <td>Committing offences under the Indian Penal Code (45 of 1860) specified in the Schedule to the Act punishable with such punishment as specified under the Indian Penal Code for such offences[ Section 3(2) (va)  read with the  Schedule to the Act] </td> <td>Two lakh rupees to the victim and or his dependents. The amount would vary if specifically otherwise provided in this Schedule. Payment to be made as follows: (i) 25 per cent. at First Information Report (FIR) stage; (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. when the accused are convicted by the lower court; </td> </tr> <tr> <td>42.</td> <td>Victimisation at the hands of a public servant[ Section 3(2) (vii)  of the Act] </td> <td>  Two lakh rupees to the victim and or his dependents. Payment to be made as follows: (i) 25 per cent. at First Information Report (FIR) stage; (ii) 50 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. when the accused are convicted by the lower court. </td> </tr> <tr> <td>43.</td> <td>Disability.  Guidelines for evaluation of various disabilities and procedure for certification as contained in the Ministry of Social Justice and Empowerment Notification No. 16-18/97-NI, dated the 1st June, 2001. A copy of the notification is at Annexure-II. (a) 100 per cent. incapacitation (b) where incapacitation is less than 100  per cent. but more than 50 per cent. (c) where incapacitation is less than 50 per cent. </td> <td>Eight lakh and twenty-five thousand rupees to the victim. Payment to be made as follows: (i) 50 per cent. after medical examination and confirmatory medical report; (ii) 50 per cent. when the charge sheet is sent to the court; Four lakh and fifty thousand rupees to the victim. Payment to be made as follows:  (i) 50 per cent. after medical examination and confirmatory medical report; (ii) 50 per cent.  when the charge sheet is sent to the court; Two lakh and fifty thousand rupees to the victim. Payment to be made as follows:  (i) 50 per cent. after medical examination and confirmatory medical report;  (ii) 50 per cent. when the charge sheet is sent to the court. </td> </tr> <tr> <td>44.</td> <td>Rape or Gang rape. (i)  Rape[Section 375 of the Indian Penal Code(45 of 1860)]   (ii) Gang rape [Section 376D of the Indian Penal Code( 45 of 1860)] </td> <td>Five lakh rupees to the victim. Payment to be made as follows: (i) 50 per cent. after medical examination and confirmatory medical report; (ii) 25 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. on conclusion of trial by the lower court. Eight lakh and twenty-five thousand rupees to the victim.  Payment to be made as follows: (i) 50 per cent. after medical examination and confirmatory medical report; (ii) 25 per cent. when the charge sheet is sent to the court; (iii) 25 per cent. on conclusion of trial by the lower court. </td> </tr> <tr> <td>45.</td> <td>Murder or Death. </td> <td>Eight lakh and twenty-five thousand rupees to the victim. Payment to be made as follows: (i) 50 per cent. after post mortem report; (ii) 50 per cent. when the charge sheet is sent to the court. </td> </tr> <tr> <td>46.</td> <td>Additional relief to victims of murder, death, massacre, rape, gang rape, permanent incapacitation and dacoity. </td> <td>In addition to relief amounts paid under above items, relief may be arranged within three months of date of atrocity as follows:- (i) Basic Pension to the widow or other dependents of deceased persons belonging to a Scheduled Caste or a Scheduled Tribe amounting to five thousand rupees per month, as applicable to a Government servant of the concerned State Government or Union territory Administration, with admissible dearness allowance  and employment to one member of the family of the deceased, and provision of agricultural land, an house, if necessary by outright purchase; (ii) Full cost of the education up to graduation level and maintenance of the children of the victims. Children may be admitted to Ashram schools or residential schools, fully funded by the Government; (iii) Provision of utensils, rice, wheat, dals, pulses, etc., for a period of three months. </td> </tr> <tr> <td>47.</td> <td>Complete destruction or burnt houses.</td> <td>Brick or stone masonary house to be constructed or provided at Government cost where it has been burnt or destroyed.” </td> </tr> </tbody> </table> </div> </div> </div> </section> <!-- /.content --> </div><file_sep>/application/libraries/Apirender.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /** * Arugement Validation CodeIgniter implementation * * PHP version 5 * * @category CodeIgniter * @package Api Render * @author <NAME> (<EMAIL>) * @version 0.2 */ class Apirender { public function __construct() { $this->obj = & get_instance(); } public function ThowError($Error, $Script) { $Script = $this->obj->apirender->ScriptModify($Script); $Error = array("Userinfo" => $this->obj->UserAcess, "Script" => $Script, "StatusCode" => 500, "Error" => str_replace(array("<div>", "</div>"), "", $Error)); header('Access-Control-Allow-Origin: *'); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); header('Content-Type: text/javascript'); // if ($this->obj->Browser == "Y") { // debugdata("", "db"); // debugdata(get_defined_vars()); // } $this->obj->apirender->FinialRender($Error); } public function RenderData($AddEle = null) { $Render = array("Userinfo" => $this->obj->UserAcess, "StatusCode" => 200, "Adddata" => $AddEle, "form" => $_GET['form'], "restore" => $AddEle["restore"]); header('Access-Control-Allow-Origin: *'); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); header('Content-Type: text/javascript'); $this->obj->apirender->FinialRender($Render); } public function RenderHtml($Data, $AddHtml = null, $Submit) { $Render = array("submit" => $Submit, "Userinfo" => $this->obj->UserAcess, "StatusCode" => "HTML", "Data" => $Data, "htmlrender" => $AddHtml, "form" => $_GET['form']); header('Access-Control-Allow-Origin: *'); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); header('Content-Type: text/javascript'); $this->obj->apirender->FinialRender($Render); } public function HttpAthu() { return true; if ((!isset($_SERVER['PHP_AUTH_USER'])) || (empty($_SERVER['PHP_AUTH_USER']) || (empty($_SERVER['PHP_AUTH_PW'])))) { $HttpRequestType = $this->obj->input->is_ajax_request(); if (!$HttpRequestType) { $this->obj->apirender->ThowError("API REQUEST KEY."); } else { header('WWW-Authenticate: Digest realm="API_REQUEST_LOGIN", qop="auth", nonce="' . null . '", opaque="' . md5("API") . '"'); header('HTTP/1.0 401 Unauthorized'); $this->obj->apirender->ThowError("User restrictions(File Not Found)."); } } else { return true; } } public function FinialRender($Render) { if (!empty($_GET['callback'])) { exit($_GET['callback'] . "(" . json_encode($Render) . ")"); } else { exit(json_encode($Render)); } } public function ScriptModify($Script) { switch ($_GET['version']): case "1": if (!empty($Script)): $ScriptArray = (explode(")", $Script)); foreach ($ScriptArray as $key => $val) { $ReturnScript.=str_replace("(", "-", $val); } endif; return $ReturnScript; break; default : return $Script; break; endswitch; } } ?><file_sep>/application/views/police/complaint/complaintaction.php <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1><?= $this->lang->line('complaint_action') ?></h1> <ol class="breadcrumb"> <li><a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/index") ?>"><i class="fa fa-dashboard"></i> <?= $this->lang->line('home') ?></a></li> <li><a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/complaint/allcomplaints") ?>"><?= $this->lang->line('view_all_complaints') ?></a></li> <li class="active"><?= $this->lang->line('view_all_complaints') ?></li> </ol> </section> <?php if ($VerifyStatus['AssignedTo'] == 'N'): ?> <form role="form" method="post" action="<?= base_url('index.php/' . strtolower($this->router->fetch_class()) . "/ComplaintCommentsSave") ?> "> <input type="hidden" name="id" value="<?= $id ?>"/> <section class="content"> <div class="box"> <!-- /.box-header --> <div class="box-body"> <div class="row"> <div class="col-md-4"> <div class="form-group"> <label><?= $this->lang->line('police_details') ?><span style="color: red ">*</span></label> <select class="form-control" id="police" name="policeassigned" placeholder="Choose Police Station" required="true"> <option>Choose Police Station</option> <?php foreach ($this->db->where(array("isactive" => "Y", "rolename" => "Police"))->order_by("username", "asc")->join("roles", "roleid=role")->get('users')->result() as $detail) { ?> <option value="<?= $detail->user_id ?>"> <?= $detail->username . " - " . $detail->rolename ?> </option> <?php } ?> </select> </div> </div> <div class="col-md-8"> <div class="form-group"> <label><?= $this->lang->line('comments') ?><span style="color: red ">*</span></label> <textarea class="textarea" placeholder="Type your comments here" name="policecomments" style="width: 100%; height: 100px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"></textarea> </div> </div> </div> <br> </div> <div class="box-footer"> <center> <div class="col-md-12"> <button type="submit" class="btn btn-primary"><?= $this->lang->line('submit') ?></button> </div></center> </div> </div> </section> <?php else: ?> <div class="error-page"> <div class="error-content"> <h3><i class="fa fa-warning text-red"></i> Already Complaint Assgined</h3> </div> </div> <?php endif; ?> </div><file_sep>/application/views/user/index/dashboard.php <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> Dashboard <small>Control panel</small> </h1> <ol class="breadcrumb"> <li><a href="#"><i class="fa fa-dashboard"></i> <?= $this->lang->line('home') ?></a></li> <li class="active"><?= $this->lang->line('dashboard') ?></li> </ol> </section> <!-- Main content <section class="content"> Small boxes (Stat box) /.row <div class="row"> <div class="col-md-12"> Custom Tabs <div class="nav-tabs-custom"> <ul class="nav nav-tabs"> <li class="active"><a href="#tab_1" data-toggle="tab" aria-expanded="true">New Cases</a></li> <li class=""><a href="#tab_2" data-toggle="tab" aria-expanded="false">Pending Cases</a></li> <li class=""><a href="#tab_3" data-toggle="tab" aria-expanded="false">Solved Cases</a></li> </ul> <div class="tab-content"> <div class="tab-pane active" id="tab_1"> <br/> <table id="example1" class="table table-bordered table-striped"> <thead> <tr> <th> <?= $this->lang->line('case_id') ?></th> <th> <?= $this->lang->line('victim_name') ?></th> <th> <?= $this->lang->line('mobile_number') ?></th> <th> <?= $this->lang->line('status') ?></th> </tr> </thead> <tbody> <tr> <td>Trident</td> <td>Internet Explorer 4.0</td> <td>9876543219</td> <td><span class="label label-info">Submitted</span></td> </tr> <tr> <td>Trident</td> <td>Internet Explorer 5.0 </td> <td>7566432189</td> <td><span class="label label-warning">Police Tracking</span></td> </tr> <tr> <td>Trident</td> <td>Internet Explorer 5.5 </td> <td>8597654387</td> <td><span class="label label-success">Solved</span></td> </tr> </tbody> </table> </div> /.tab-pane <div class="tab-pane" id="tab_2"> The European languages are members of the same family. Their separate existence is a myth. For science, music, sport, etc, Europe uses the same vocabulary. The languages only differ in their grammar, their pronunciation and their most common words. Everyone realizes why a new common language would be desirable: one could refuse to pay expensive translators. To achieve this, it would be necessary to have uniform grammar, pronunciation and more common words. If several languages coalesce, the grammar of the resulting language is more simple and regular than that of the individual languages. </div> /.tab-pane <div class="tab-pane" id="tab_3"> 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. </div> /.tab-pane </div> /.tab-content </div> nav-tabs-custom </div> /.col </div> </section> /.content --> </div><file_sep>/application/views/layout/body.php <?php $this->layoutfolder = $this->config->item("layoutfolder"); $this->load->view($this->layoutfolder . "/header"); $this->load->view($this->layoutfolder . "/nav"); $this->load->view(strtolower($this->router->fetch_class()) . "/" . strtolower($this->router->fetch_method()) . "/" . $this->render); $this->load->view($this->layoutfolder . "/footer"); $this->load->view($this->layoutfolder . "/right"); $this->load->view($this->layoutfolder . "/scriptfooter"); <file_sep>/application/controllers/Homepage.php <?php if (!defined('BASEPATH')) { exit('No direct script access allowed'); } class Homepage extends MY_Controller { public function __construct() { parent::__construct(); $FunctionS = array("index", "forgotpassword", "userregister" ); if (!in_array($this->router->fetch_method(), $FunctionS)): if (strtolower($_SESSION["UserRoleName"]) != strtolower(__CLASS__)) { $this->Inti(__CLASS__); } endif; $userNameCnd = array("username" => $this->session->userdata("UserName")); $this->user = current($this->Adminmodel->CSearch($userNameCnd, "username as UserName", "usr", "", "", "", "", "", "", "")); $this->userid = current($this->Adminmodel->CSearch($userNameCnd, "user_id as UserId", "usr", "", "", "", "", "", "", "")); $this->userRole = current($this->Adminmodel->CSearch($userNameCnd, "role as UserRole", "usr", "Y", "Y", "", "", "", "", "")); } public function index() { $casecount = $this->TotalCaseCount(); $pendingcount = $this->PendingCaseCount(); $solvedcount = $this->SolvedCaseCount(); // echo "<pre>"; // print_r(get_defined_vars());exit(); $this->load->view('homepage/dashboard', get_defined_vars()); } public function email() { $Message = $this->load->view("emaillayouts/usersignup", get_defined_vars(), true); $Subject = "Atrocity Case Management - New Account Created"; $this->SendEmail(trim("<EMAIL>"), $Message, "N", $Subject, ""); } public function userregister() { $this->load->view('homepage/userregister'); } public function UserRegisterSave() { $postData = $this->input->post(); // echo "<pre>"; // print_r(get_defined_vars()); // exit(); if (true): //add to database // echo "<pre>"; // print_r(get_defined_vars()); // exit(); $condition = array("user_id" => ""); $DBData = array( "role" => $postData['Role'], "name" => $postData['PersonName'], "username" => $postData['UserName'], "password" => $postData['<PASSWORD>'], "address1" => $postData['Address1'], "address2" => $postData['Address2'], "city" => $postData['City'], "state" => $postData['State'], "country" => $postData['Country'], "mobilenumber" => $postData['MobileNumber'], "email" => $postData['EmailID'], "aadhar" => $postData['AadhaarNumber'], ); $response = $this->Adminmodel->AllInsert($condition, $DBData, "", "usr"); if (!empty($response)): $Message = $this->load->view("emaillayouts/usersignup", get_defined_vars(), true); $Subject = "Atrocity Case Management - New Account Created"; // $this->SendEmail(trim($postData['EmailID']), $Message, "N", $Subject, ""); $this->session->set_flashdata('ME_SUCCESS', 'User Registered Successfully'); else: $this->session->set_flashdata('ME_ERROR', 'Data not Saved. Kindly Re Enter'); endif; else: $_SESSION['formError'] = validation_errors(); $this->session->set_flashdata('ME_FORM', "ERROR"); endif; $this->load->view('homepage/userregister'); } public function ForgotPasswordSave() { $postData = $this->input->post(); if ($this->form_validation("forgot")): //add to database $condition = array("email" => $postData['emailid'], "mobilenumber" => $postData['mobilenumber']); $select = "mobilenumber as MobileNumber,email as EmailID,user_id as UID"; $result = $this->Adminmodel->CSearch($condition, $select, "usr", "", "", "", "", "", "", ""); if (!empty($result)): $RandomPassword = <PASSWORD>gen(100000, 999999, 1); $condition = array("user_id" => $result['UID']); $DBData = array("password" => $<PASSWORD>[0]); $response = $this->Adminmodel->AllInsert($condition, $DBData, "", "usr"); if (!empty($response)): $Message = $this->load->view("emaillayouts/forgotpass", get_defined_vars(), true); $Subject = "Atrocity Case Managment - Password Reset"; //$this->SendEmail(trim($result['EmailID']), $Message, "N", $Subject, ""); $this->session->set_flashdata('ME_SUCCESS', 'Password Changed Successfully'); else: $this->session->set_flashdata('ME_ERROR', 'Data not Saved. Kindly Contact Adminsitrator'); endif; else: $this->session->set_flashdata('ME_ERROR', 'Your data not matched with our records'); endif; else: $_SESSION['formError'] = validation_errors(); $this->session->set_flashdata('ME_FORM', "ERROR"); endif; $this->load->view('homepage/dashboard'); } public function login() { $this->load->view('homepage/login'); } public function forgotpassword() { $this->load->view('homepage/forgotpassword'); } } <file_sep>/application/libraries/Flexigrid_library.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /** * Flexigrid CodeIgniter implementation * * PHP version 5 * * @category CodeIgniter * @package Flexigrid CI * @author <NAME> (<EMAIL>) * @version 0.1 * Copyright (c) 2008 <NAME> (http://flexigrid.eyeviewdesign.com) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. */ class Flexigrid_library { //Validated $_POST data var $post_info = array(); //Json code var $json_build; /** * Constructor * * @access public */ public function Flexigrid() { $CI =& get_instance(); //Load config $CI->config->load('flexigrid'); log_message('debug', "EVD CMS Flexigrid Class Initialized"); } /** * Validate Post data * * @access public * @param default sort name * @param default sort order * @param List of all fields that can be sortable/searchable * @return void */ public function validate_post($d_sortname,$d_sortorder,$valid_fields = NULL,$post_data=NULL) { // echo $d_sortname; // echo $d_sortorder; // exit; // print_r($post_data['rp']); $CI =& get_instance(); //Validate page number if ($post_data['page'] != FALSE && is_numeric($post_data['page'])) $this->post_info['page'] =$post_data['page']; else $this->post_info['page'] = $CI->config->item('page_number'); //Validate records per page if ($post_data['rp'] != FALSE && is_numeric($post_data['rp'])) $this->post_info['rp'] = $post_data['rp']; else $this->post_info['rp'] = $CI->config->item('per_page'); //Calculate limit start based on page and rp $this->post_info['limitstart'] = (($this->post_info['page']-1) * $this->post_info['rp']); //Validate page sort if ($this->record_sorter_validator($post_data['sortname'],$post_data['sortorder'])) { if (is_array($valid_fields)) { if (in_array($post_data['sortname'],$valid_fields)) { $this->post_info['sortname'] =$post_data['sortname']; $this->post_info['sortorder'] = $post_data['sortorder']; } else { $this->post_info['sortname'] = $d_sortname; $this->post_info['sortorder'] = $d_sortorder; } } else { $this->post_info['sortname'] = $post_data['sortname']; $this->post_info['sortorder'] =$post_data['sortorder']; } } else { $this->post_info['sortname'] = $d_sortname; $this->post_info['sortorder'] = $d_sortorder; } //Validate search query if ($post_data['query'] != FALSE && $post_data['query'] != "" && $post_data['qtype'] != FALSE && $post_data['qtype'] != "" ) if (is_array($valid_fields)) if (in_array($post_data['qtype'],$valid_fields)) $this->post_info['swhere'] = $this->searchstr_validator($post_data['query'],$post_data['qtype']); else $this->post_info['swhere'] = FALSE; else $this->post_info['swhere'] = $this->searchstr_validator($post_data['query'],$post_data['qtype']); else $this->post_info['swhere'] = FALSE; // print_r($this->post_info); // exit; return $this->post_info; } /** * Sort Validator * * @access private * @param sort name * @param sort order * @return boolean */ private function record_sorter_validator($sortname,$sortorder) { if ($sortname == FALSE || $sortorder == FALSE) { return FALSE; } else { $sortorder = strtoupper($sortorder); if (($sortorder == "ASC" || $sortorder == "DESC")) return TRUE; } return FALSE; } /** * Search Validator * * @access private * @param search string * @param search by * @return string/boolean */ private function searchstr_validator($searchstr,$searchby) { if ($searchstr == FALSE || $searchby == FALSE) { return FALSE; } else { if (trim($searchstr) != "" && $searchby != "") { $searchstr_split = explode(" ",$searchstr); $searchstr_final = ""; foreach ($searchstr_split as $key => $value) { if (trim($value) != "") if ($key == 0) $searchstr_final .= $searchby.' LIKE "%'.$value.'%"'; else $searchstr_final .= ' OR '.$searchby.' LIKE "%'.$value.'%"'; } return $searchstr_final; } } return FALSE; } /** * OLD (DEPRECATED) Query builder. Takes the striped query and adds sort, search and limit * * @access public * @param stripped query * @param Use WHERE or AND, depending if there allready is a WHERE or not in the query: * TRUE: use WHERE * FALSE: use AND * @return array */ public function build_querys($querys,$use_where = TRUE) { //Build querys if ($this->post_info['swhere'] == FALSE) { $return['main_query'] = str_replace('{SEARCH_STR}','',$querys['main_query']).' ORDER BY '.$this->post_info['sortname'].' '.$this->post_info['sortorder'].' LIMIT '.$this->post_info['limitstart'].','.$this->post_info['rp']; $return['count_query'] = str_replace('{SEARCH_STR}','',$querys['count_query']); return $return; } else { $return['main_query'] = str_replace('{SEARCH_STR}',($use_where == TRUE ? ' WHERE ' : ' AND ').$this->post_info['swhere'],$querys['main_query']).' ORDER BY '.$this->post_info['sortname'].' '.$this->post_info['sortorder'].' LIMIT '.$this->post_info['limitstart'].','.$this->post_info['rp']; $return['count_query'] = str_replace('{SEARCH_STR}',($use_where == TRUE ? ' WHERE ' : ' AND ').$this->post_info['swhere'],$querys['count_query']); return $return; } } /** * Query builder. Adds sort, search and limit to the query * * @access public * @param insert LIMIT in the query, true by default. This is used to strip the count query from LIMIT * @return nothing */ public function build_query($limit = TRUE) { if ($this->post_info['swhere']) $CI->db->where($this->post_info['swhere']); $CI->db->order_by($this->post_info['sortname'], $this->post_info['sortorder']); if ($limit) $CI->db->limit($this->post_info['rp'], $this->post_info['limitstart']); } /** * Starts the json code (Do not use if you have json_encode) * * @access public * @param number of records in the table * @return boolean */ public function init_json_build($record_count) { $this->post_info['record_count'] = $record_count; if ($this->post_info['record_count'] > 0) { $this->json_build = "{"; $this->json_build .= "page: ".$this->post_info['page'].","; $this->json_build .= "total: ".$this->post_info['record_count'].","; $this->json_build .= "rows: ["; //Records exist! return TRUE; } else { $this->json_build = "{"; $this->json_build .= "page: ".$this->post_info['page'].","; $this->json_build .= "total: ".$this->post_info['record_count'].","; $this->json_build .= "rows: [ ]}"; //No records. return FALSE; } } /** * Adds items to json code (Do not use if you have json_encode) * * @access public * @param item data * @return void */ public function json_add_item ($item_data = NULL) { if ($item_data != NULL) { $this->json_build .= "{"; //First array index is the ID $this->json_build .= "id:'".$item_data[0]."',cell:["; foreach ($item_data as $key => $value) { if ($key != 0) { $this->json_build .= "'".addslashes($value)."',"; } } $this->json_build = substr($this->json_build,0,-1); $this->json_build .= "]},"; } else { if ($this->post_info['record_count'] > 0) { $this->json_build = substr($this->json_build,0,-1); $this->json_build .= "]}"; } } } /** * Builds JSON code with the data and returns it * * @access public * @param total number of records * @param processed data that is going to the grid * @return json formated data */ public function json_build($record_count,$data) { // Creates new Data Set and sends all the information $fg_data_set = new Fg_data_set($record_count,$_POST['page'],$data); echo json_encode($fg_data_set); exit; //Builds and returns JSON return $fg_data_set->build_json(); } } /* * This is a helper object. It retains a row as object for JSON format purposes. * Based on gpasq's (<EMAIL>) PHP Flexigrid Class */ class Fg_set_row { public $id; public $cell = array(); } /* * This is the data grid's Data Set object * Based on gpasq's (<EMAIL>) PHP Flexigrid Class */ /** * This is the data grid's Data Set object */ class Fg_data_set { public $page; public $total; public $rows = array(); /** * Class constructor * * @param total number of records * @param page number * @param processed data that is going to the grid */ public function Fg_data_set($record_count,$page,&$data) { //Set initial params $this->total = $record_count; $this->page = $page; //Prepare data for json encoding $this->load($data); } /** * Loads the data into row objects and into the rows array * * @param processed data that is going to the grid */ public function load(&$data) { foreach ($data as $row) { $obj = new Fg_set_row(); //Helper Object, for JSON format purposes. $obj->id = array_shift($row); //Remove first element, and save it. Its the ID of the row. $obj->cell = $row; array_push($this->rows, $obj); //Adds the row object to the rows array } } /** * Json Encodes de data * * @return json formated data */ public function build_json() { //Encodes and returns JSON return json_encode($this); } } ?><file_sep>/application/controllers/LanguageSwitcher.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /** * This help to switch language */ class LanguageSwitcher extends CI_Controller { public function __construct() { parent::__construct(); } function switchLang($language = "") { $language = ($language != "") ? $language : "english"; $this->session->set_userdata('site_lang', $language); if ($language != null): $this->session->set_flashdata('ME_SUCCESS', ucfirst($language).' Language Changed Successfully'); else: $this->session->set_flashdata('ME_ERROR', 'Something went wrong'); endif; redirect($_SERVER['HTTP_REFERER']); } }<file_sep>/application/libraries/Arg_validate.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /** * Arugement Validation CodeIgniter implementation * * PHP version 5 * * @category CodeIgniter * @package Arugement validation CI * @author <NAME> (<EMAIL>) * @version 0.1 */ class Arg_validate { public function __construct() { $this->obj = & get_instance(); } function ValidateData($Method, $CheckData = null, $Runtype = null) { if (empty($CheckData)) { $_POST = $_REQUEST; } else { $_POST = $_REQUEST; $_POST = (!empty($_POST)) ? array_merge($_POST, $CheckData) : $CheckData; } $NoValiarray = array("ShowError", "RunTime", "TypeRun"); $Rules = ($this->obj->config->item("ValidationArray")); $RulesM[$Method] = (empty($Rules[$Method][$Runtype])) ? $Rules[$Method] : $Rules[$Method][$Runtype]; unset($Rules); if (!empty($Rules[$Method])): $Keys = array_keys($Rules[$Method]); endif; $Rules[$Method] = ($Keys[0] == $Runtype) ? $RulesM[$Method] : null; if (!empty($Rules[$Method])) { foreach ($Rules[$Method] as $key => $val) { if (!in_array($key, $NoValiarray)) { $this->obj->form_validation->set_rules($key, $val['Message'], $val['validate']); if (!empty($val['Default'])) { foreach ($val['Default'] as $MeKey => $Meval) { $this->obj->form_validation->set_message($MeKey, $Meval); } } } } $FormValidateStatus = $this->obj->form_validation->run(); $HttpRequestType = $this->obj->input->is_ajax_request(); if ($FormValidateStatus == false) { if ($Rules[$Method]['RunTime'] == "ajax") { $message = validation_errors("(-)<div>", '<div>'); } else { $message = validation_errors("(-)", ''); } $this->obj->FormError = (!empty($message)) ? explode("(-)", $message) : null; } //ajax call if (($Rules[$Method]['RunTime'] == "ajax") && ($HttpRequestType)) { if ($Rules[$Method]['ShowError'] == "Y") { $this->obj->FormError = (empty($this->obj->FormError)) ? null : (array_filter($this->obj->FormError)); } else { $this->obj->FormError = array("Access Denied"); } //http call } elseif (($Rules[$Method]['RunTime'] != "ajax") && (!$HttpRequestType)) { if ($Rules[$Method]['ShowError'] == "Y") { $this->obj->FormError = (empty($this->obj->FormError)) ? null : (array_filter($this->obj->FormError)); } else { $this->obj->FormError = array("Access Denied"); } } elseif (($Rules[$Method]['RunTime'] == "api")) { if ($Rules[$Method]['ShowError'] == "Y") { $this->obj->FormError = (empty($this->obj->FormError)) ? null : (array_filter($this->obj->FormError)); } else { $this->obj->FormError = array("Access Denied"); } } else { if (SysRun == "Local") { $this->obj->FormError = (empty($this->obj->FormError)) ? null : (array_filter($this->obj->FormError)); } else { show_error("ERROR", 500); } } return $FormValidateStatus; } else { return true; } } } ?><file_sep>/application/views/user/changepassword/changepassword.php <div class="content-wrapper" style="min-height: 990px;"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> <?= $this->lang->line('change_password') ?> <small><?= $this->lang->line('edit_password') ?></small> </h1> <ol class="breadcrumb"> <li><a href="<?= base_url("index.php/" . strtolower($this->router->fetch_class()) . "/index") ?>"><i class="fa fa-dashboard"></i><?= $this->lang->line('home') ?></a></li> <li><a href="#"><?= $this->lang->line('users') ?></a></li> </ol> </section> <!-- Main content --> <section class="content"> <div class="row"> <!-- left column --> <div class="col-md-12"> <!-- general form elements --> <div class="box box-primary"> <div class="box-header with-border"> </div> <!-- /.box-header --> <!-- form start --> <form role="form" method="post" action="<?= base_url('index.php/user/UpdatePassword') ?> "> <div class="box-body"> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label for="Exampleinputoldpassword"><?= $this->lang->line('old_password') ?></label> <input type="<PASSWORD>" class="form-control" id="oldpassword" name="oldpassword" placeholder="Enter Old <PASSWORD>"> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label for="password"><?= $this->lang->line('new_password') ?></label> <input type="<PASSWORD>" class="form-control" id="newpassword" name="newpassword" placeholder="Enter New <PASSWORD>"> </div> </div> <div class="col-md-12"> <div class="form-group"> <label for="ConfirmationPassword"><?= $this->lang->line('confirmation_password') ?></label> <input type="password" class="form-control" id="confirmationpassword" name="confirmationpassword" placeholder="Enter Confirmation Password"> </div> </div> </div> </div> <!-- /.box-body --> <div class="box-footer"> <button type="submit" class="btn btn-primary"><?= $this->lang->line('submit') ?></button> </div> </form> </div> <!-- /.box --> </div> <!--/.col (left) --> </div> <!-- /.row --> </section> <!-- /.content --> </div><file_sep>/application/controllers/Administrator.php <?php if (!defined('BASEPATH')) { exit('No direct script access allowed'); } class Administrator extends MY_Controller { public function __construct() { parent::__construct(); $FunctionS = array(""); if (!in_array($this->router->fetch_method(), $FunctionS)): if (strtolower($_SESSION["UserRoleName"]) != strtolower(__CLASS__)) { $this->Inti(__CLASS__); } endif; $userNameCnd = array("username" => $this->session->userdata("UserName")); $this->user = current($this->Adminmodel->CSearch($userNameCnd, "username as UserName", "usr", "", "", "", "", "", "", "")); $this->userid = current($this->Adminmodel->CSearch($userNameCnd, "user_id as UserId", "usr", "", "", "", "", "", "", "")); $this->userRole = current($this->Adminmodel->CSearch($userNameCnd, "role as UserRole", "usr", "Y", "Y", "", "", "", "", "")); } public function index() { $usercount = $this->TotalUserCount(); $casecount = $this->TotalCaseCount(); $pendingcount = $this->PendingCaseCount(); $solvedcount = $this->SolvedCaseCount(); $newcase = $this->NewCaseShow(); $solvedcase = $this->SolvedCaseShow(); $pendingcase = $this->PendingCaseShow(); $profileurl = $this->ShowProfileImage($_SESSION['UserId']); $profileimage = $this->render("dashboard", get_defined_vars()); } public function logs($options = null, $id = null) { $render = ""; switch (strtolower($options)) { case "notices"; $render = "showallnotices"; break; case "warnings"; $render = "showallwarnings"; break; case "errors"; $render = "showallerrors"; break; case "shownotice": $render = "shownotice"; $noticeinformation = $this->shownotice($id); break; case "all"; $render = "showall"; break; default: $logsNotice = $this->getlogs_notices(); $logsWarning = $this->getlogs_warning(); $logsError = $this->getlogs_error(); $logsAll = $this->getlogs_all(); $render = "logs"; break; } $this->render($render, get_defined_vars()); } public function logs_ajax_list($options = null) { switch (strtolower($options)) { case "notices": $Condition = array("errtype" => "Notice"); $TableListname = "log"; $ColumnOrder = array('errstr', 'errfile', 'errline', 'time'); $ColumnSearch = array('errstr', 'errfile', 'errline', 'time'); $OrderBy = array('id' => 'desc'); break; case "warnings": $Condition = array("errtype" => "Warning"); $TableListname = "log"; $ColumnOrder = array('errstr', 'errfile', 'errline', 'time'); $ColumnSearch = array('errstr', 'errfile', 'errline', 'time'); $OrderBy = array('id' => 'desc'); break; case "errors": $Condition = array("errtype" => "Error"); $TableListname = "log"; $ColumnOrder = array('errstr', 'errfile', 'errline', 'time'); $ColumnSearch = array('errstr', 'errfile', 'errline', 'time'); $OrderBy = array('id' => 'desc'); break; case "all": $Condition = array(); $TableListname = "log"; $ColumnOrder = array('errstr', 'errfile', 'errline', 'time'); $ColumnSearch = array('errstr', 'errfile', 'errline', 'time'); $OrderBy = array('id' => 'desc'); break; default: $Condition = array(); break; } $list = $this->Adminmodel->get_datatables($TableListname, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, false); $data = array(); $no = $_POST['start']; foreach ($list as $logNotice) { $no++; $row = array(); $row[] = $logNotice->errstr; $row[] = $logNotice->errfile; $row[] = $logNotice->errline; $row[] = $logNotice->time; //add html for action $row[] = '<a class="btn btn-xs btn-primary" href="' . base_url('index.php/' . $this->router->fetch_class() . '/logs/shownotice/' . $logNotice->id) . '" title="Edit" target="_blank"><i class="fa fa-eye"></i> View</a>'; $data[] = $row; } $output = array( "draw" => $_POST['draw'], "recordsTotal" => $this->Adminmodel->count_all($TableListname, $Condition), "recordsFiltered" => $this->Adminmodel->count_filtered($TableListname, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, false), "data" => $data, ); //output to json format echo json_encode($output); } public function users_ajax_list($options = null) { switch (strtolower($options)) { case "users": $Condition = array(); $TableListname = "usr"; $ColumnOrder = array('name', 'username', 'mobilenumber', 'address1', 'city'); $ColumnSearch = array('name', 'username', 'mobilenumber', 'address1', 'city'); $OrderBy = array('user_id' => 'desc'); break; default: $Condition = array(); break; } $list = $this->Adminmodel->get_datatables($TableListname, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, false); $data = array(); $no = $_POST['start']; foreach ($list as $UserNotice) { $no++; $row = array(); $row[] = $UserNotice->name; $row[] = $UserNotice->username; $row[] = $UserNotice->mobilenumber; $row[] = $UserNotice->address1; $row[] = $UserNotice->city; //add html for action $row[] = '<a class="btn btn-xs btn-primary" href="' . base_url('index.php/' . $this->router->fetch_class() . 'user/allusers' . $UserNotice->userid) . '" title="Edit" target="_blank"><i class="fa fa-eye"></i> View</a>'; $data[] = $row; } $output = array( "draw" => $_POST['draw'], "recordsTotal" => $this->Adminmodel->count_all($TableListname, $Condition), "recordsFiltered" => $this->Adminmodel->count_filtered($TableListname, $Condition, $ColumnOrder, $ColumnSearch, $OrderBy, "N"), "data" => $data, ); //output to json format echo json_encode($output); } protected function shownotice($id) { $condition = array("id" => $id); $select = "errstr as ErrorString, errfile as ErrorFilename, errline as ErrorLine,time as Time"; return $this->Adminmodel->CSearch($condition, $select, "log", "", "", "", "", "", "", ""); } protected function getlogs_notices() { $condition = array("errtype" => "Notice"); $select = "id as ID, errstr as ErrorString, time as Time"; return $this->Adminmodel->CSearch($condition, $select, "log", "Y", "Y", "", "", "", "", ""); } protected function getlogs_warning() { $condition = array("errtype" => "Warning"); $select = "id as ID, errstr as ErrorString, time as Time"; return $this->Adminmodel->CSearch($condition, $select, "log", "Y", "Y", "", "", "", "", ""); } protected function getlogs_error() { $condition = array("errtype" => "Error"); $select = "id as ID, errstr as ErrorString, time as Time"; return $this->Adminmodel->CSearch($condition, $select, "log", "Y", "Y", "", "", "", "", ""); } protected function getlogs_all() { $condition = array(""); $select = "id as ID, errstr as ErrorString, time as Time"; return $this->Adminmodel->CSearch($condition, $select, "log", "Y", "Y", "", "", "", "", ""); } // }
27468041d025045e5f91cb10bdd15800131f165b
[ "Markdown", "SQL", "PHP" ]
47
PHP
narmadha1998/atmm
95751c3b3218fa88186f92f90d779cf80bcbcf72
25fb84b7a8f4c9b286535a96a40f236fe65a776f
refs/heads/master
<repo_name>MrDanCoelho/NetSimpleAuth-Backend<file_sep>/NetSimpleAuth.Backend.API/Controllers/v1/AccountController.cs using System; using System.ComponentModel.DataAnnotations; using System.Security.Authentication; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using NetSimpleAuth.Backend.Domain.Dto; using NetSimpleAuth.Backend.Domain.Interfaces.IServices; using NetSimpleAuth.Backend.Domain.Response; // ReSharper disable RouteTemplates.MethodMissingRouteParameters // ReSharper disable RouteTemplates.ControllerRouteParameterIsNotPassedToMethods namespace NetSimpleAuth.Backend.API.Controllers.v1 { /// <summary> /// Controller for Account operations /// </summary> [ApiVersion("1.0")] [ApiController] [Route("api/v{version:apiVersion}/[controller]")] public class AccountController : ControllerBase { private readonly ILogger<AccountController> _logger; private readonly IAccountService _accountService; /// <summary> /// Controller for Account operations /// </summary> /// <param name="logger">The app's logger</param> /// <param name="accountService">Service with account operations</param> public AccountController( ILogger<AccountController> logger, IAccountService accountService ) { _logger = logger; _accountService = accountService; } /// <summary> /// Authenticates user in the service /// </summary> /// <param name="user">The user to authenticate</param> /// <returns>The authenticated user</returns> // POST: api/v1/account/login [HttpPost("login")] public async Task<ActionResult<AuthUserResponse>> Login([Required] AuthUserDto user) { try { var authUser = await _accountService.Authenticate(user); return Ok(authUser); } catch (AuthenticationException e) { _logger.LogError(e, "Wrong username and/or password"); return Unauthorized(e.Message); } catch (Exception e) { _logger.LogError(e, "Unable to authenticate due to an unknown error"); return BadRequest("Unable to authenticate user"); } } } }<file_sep>/NetSimpleAuth.Backend.Domain/Response/AuthUserResponse.cs namespace NetSimpleAuth.Backend.Domain.Response { public class AuthUserResponse { public string Username { get; set; } public string JwtToken { get; set; } public string RefreshToken { get; set; } } }<file_sep>/NetSimpleAuth.Backend.Domain/Interfaces/IRepositories/IRefreshTokenRepository.cs using NetSimpleAuth.Backend.Domain.Entities; namespace NetSimpleAuth.Backend.Domain.Interfaces.IRepositories { /// <summary> /// Repository with methods for token refreshing /// </summary> public interface IRefreshTokenRepository : ICrudRepository<RefreshTokenEntity> { } }<file_sep>/NetSimpleAuth.Backend.Domain/Enums/FlagsEscolaridade.cs using System; namespace NetSimpleAuth.Backend.Domain.Enums { [Flags] public enum FlagEscolaridade { Infantil = 1, Fundamental = 2, Médio = 3, Superior = 4 } }<file_sep>/NetSimpleAuth.Backend.Domain/Entities/LogEntity.cs using System; using System.ComponentModel.DataAnnotations; using System.Net; namespace NetSimpleAuth.Backend.Domain.Entities { public class LogEntity { [Key] public int Id { get; set; } public string Ip { get; set; } public string App { get; set; } public string User { get; set; } public DateTime Date { get; set; } public string RequestType { get; set; } public string RequestUrl { get; set; } public string RequestProtocol { get; set; } public HttpStatusCode StatusCode { get; set; } public int? ContentSize { get; set; } public string ResponseUrl { get; set; } public string UserAgent { get; set; } } }<file_sep>/NetSimpleAuth.Backend.Infra/Repositories/LogRepository.cs using System; using System.Linq; using System.Threading.Tasks; using Dapper; using Microsoft.Extensions.Logging; using NetSimpleAuth.Backend.Domain.Dto; using NetSimpleAuth.Backend.Domain.Entities; using NetSimpleAuth.Backend.Domain.Interfaces.IRepositories; using NetSimpleAuth.Backend.Domain.Response; namespace NetSimpleAuth.Backend.Infra.Repositories { /// <inheritdoc cref="ILogRepository" /> public class LogRepository : CrudRepository<LogEntity>, ILogRepository { private readonly ILogger<LogRepository> _logger; private readonly IUnitOfWork _unitOfWork; /// <summary> /// <see cref="LogEntity"/> repository /// </summary> /// <param name="logger"><see cref="ILogger{LogRepository}"/> logger</param> /// <param name="unitOfWork"><see cref="UnitOfWork"/> for the repository</param> public LogRepository(ILogger<LogRepository> logger, IUnitOfWork unitOfWork) : base(logger, unitOfWork) { _logger = logger; _unitOfWork = unitOfWork; } public async Task<SelectPaginatedResponse<LogEntity>> SelectPaginated(LogFilterDto filter, int pageNumber, int pageSize) { var query = ""; try { query = $@"SELECT * FROM public.""Log"" WHERE ""Ip"" like '%{filter.Ip}%' AND ""UserAgent"" like '%{filter.UserAgent}%'"; if(filter.Hour != null) query += $@" AND extract(hour from ""Date"") = {filter.Hour}"; if (filter.Order != null) query += $@" ORDER BY ""{filter.Order}"" {filter.Direction}"; query += $@" OFFSET {(pageNumber -1) * pageSize} ROWS FETCH NEXT {pageSize} ROWS ONLY"; var countQuery = $@"SELECT count(*) FROM public.""Log"" WHERE ""Ip"" like '%{filter.Ip}%' AND ""UserAgent"" like '%{filter.UserAgent}%'"; if(filter.Hour != null) countQuery += $@" AND extract(hour from ""Date"") = {filter.Hour}"; var result = new SelectPaginatedResponse<LogEntity> { Obj = await _unitOfWork.DbConnection.QueryAsync<LogEntity>(query), Count = (await _unitOfWork.DbConnection.QueryAsync<int>(countQuery)).First() }; return result; } catch (Exception e) { _logger.LogError(e, "Pagination failed for query = {$Query}", query); throw; } } } }<file_sep>/NetSimpleAuth.Backend.API/Controllers/v1/LogController.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using NetSimpleAuth.Backend.API.CustomValidation; using NetSimpleAuth.Backend.Domain.Dto; using NetSimpleAuth.Backend.Domain.Entities; using NetSimpleAuth.Backend.Domain.Interfaces.IServices; // ReSharper disable RouteTemplates.ControllerRouteParameterIsNotPassedToMethods // ReSharper disable RouteTemplates.MethodMissingRouteParameters namespace NetSimpleAuth.Backend.API.Controllers.v1 { /// <summary> /// Controller for Log requests /// </summary> //[Authorize] [ApiVersion("1.0")] [ApiController] [Route("api/v{version:apiVersion}/[controller]")] public class LogController : CrudControllerBase<LogEntity> { private readonly ILogger<LogController> _logger; private readonly ILogService _logService; /// <summary> /// Controller for Log requests /// </summary> /// <param name="logger">The app's logger</param> /// <param name="logService">Service with Log methods</param> public LogController(ILogger<LogController> logger, ILogService logService) : base(logger, logService) { _logger = logger; _logService = logService; } /// <summary> /// Insert a batch of logs contained in a file /// </summary> /// <param name="logFile">A file containing a batch of logs</param> /// <returns>Result of the operation</returns> [HttpPost("batch")] public async Task<ActionResult<string>> InsertBatch( [Required(ErrorMessage = "Choose a file to be uploaded"), AllowedExtensions(new[] { ".log", ".txt" }, ErrorMessage = "Wrong file format")] IFormFile logFile) { try { using (var file = new StreamReader(logFile.OpenReadStream())) { await _logService.InsertBatch(file); } return Ok("Batch inserted successfully"); } catch (Exception e) { _logger.LogError(e, "Batch insertion failed"); return BadRequest("Unable to read data. Check if file has the right format. If the problem persists, contact the administrator"); } } /// <summary> /// Gets all objects in the database paginated /// </summary> /// <param name="filter">The filter to be used</param> /// <param name="page">The current page</param> /// <param name="pageSize">The page size</param> /// <returns>The list of objects paginated</returns> [HttpPost("{page:int}/{pageSize:int}")] public async Task<ActionResult<IEnumerable<LogEntity>>> SelectPaginated([FromBody]LogFilterDto filter, int page, int pageSize) { try { var result = await _logService.SelectPaginated(filter, page, pageSize); return Ok(result); } catch (Exception e) { _logger.LogError(e, "Log pagination failed for filters={@Filter}, page={$Page} and page size={$PageSize}", filter, page, pageSize); return BadRequest("Unable to get data. If problem persists, contact an administrator"); } } } }<file_sep>/NetSimpleAuth.Backend.Domain/Interfaces/IServices/ILogService.cs using System.IO; using System.Threading.Tasks; using NetSimpleAuth.Backend.Domain.Dto; using NetSimpleAuth.Backend.Domain.Entities; using NetSimpleAuth.Backend.Domain.Response; namespace NetSimpleAuth.Backend.Domain.Interfaces.IServices { public interface ILogService : ICrudService<LogEntity> { /// <summary> /// Service to insert a batch of logs from a file /// </summary> /// <param name="file">The file with the logs to be inserted</param> Task InsertBatch(StreamReader file); /// <summary> /// Service to collect all objects paginated according to their indicated type and predicate /// </summary> /// <param name="filter">The filter to be applied</param> /// <param name="pageNumber">The current page number</param> /// <param name="pageSize">The page size</param> /// <returns>List of the objects found and paginated</returns> Task<SelectPaginatedResponse<LogEntity>> SelectPaginated(LogFilterDto filter, int pageNumber, int pageSize); } }<file_sep>/NetSimpleAuth.Backend.Infra/Repositories/UserRepository.cs using Microsoft.Extensions.Logging; using NetSimpleAuth.Backend.Domain.Entities; using NetSimpleAuth.Backend.Domain.Interfaces.IRepositories; namespace NetSimpleAuth.Backend.Infra.Repositories { public class UserRepository : CrudRepository<UserEntity>, IUserRepository { private readonly ILogger<UserRepository> _logger; private readonly IUnitOfWork _unitOfWork; public UserRepository( ILogger<UserRepository> logger, IUnitOfWork unitOfWork ) : base(logger, unitOfWork) { _logger = logger; _unitOfWork = unitOfWork; } } }<file_sep>/NetSimpleAuth.Backend.API/CustomValidation/AllowedExtensionsAttributeValidation.cs using System.Collections; using System.ComponentModel.DataAnnotations; using System.IO; using Microsoft.AspNetCore.Http; namespace NetSimpleAuth.Backend.API.CustomValidation { /// <summary> /// Attribute that checks for extensions in the submitted file /// </summary> public class AllowedExtensionsAttribute:ValidationAttribute { private readonly string[] _extensions; /// <summary> /// Attribute that checks for extensions in the submitted file /// </summary> /// <param name="extensions">The allowed extensions</param> public AllowedExtensionsAttribute(string[] extensions) { _extensions = extensions; } /// <summary> /// Checks whether or not the file has the valid extensions /// </summary> /// <param name="value">The value to be validated</param> /// <param name="validationContext">The validation context</param> /// <returns>The <see cref="ValidationResult"/> of the operation</returns> protected override ValidationResult IsValid( object value, ValidationContext validationContext) { if (!(value is IFormFile file)) return ValidationResult.Success; var extension = Path.GetExtension(file.FileName); return extension != null && !((IList) _extensions).Contains(extension.ToLower()) ? new ValidationResult(ErrorMessage) : ValidationResult.Success; } } }<file_sep>/NetSimpleAuth.Backend.Test/Services/CrudServiceTest.cs using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Moq; using NetSimpleAuth.Backend.Application.Services; using NetSimpleAuth.Backend.Domain.Entities; using NetSimpleAuth.Backend.Domain.Interfaces.IRepositories; using Xunit; namespace NetSimpleAuth.Backend.Test.Services { public class CrudServiceTest { private readonly Mock<ILogger<LogService>> _logger; private readonly Mock<ILogRepository> _crudRepository; public CrudServiceTest() { _logger = new Mock<ILogger<LogService>>(); _crudRepository = new Mock<ILogRepository>(); } [Fact] public async Task GetAll() { // Arrange _crudRepository.Setup(x => x.GetAll()) .Returns(Task.FromResult<IEnumerable<LogEntity>>(new List<LogEntity>())); // Act var service = new LogService(_logger.Object, _crudRepository.Object); var result = await service.GetAll(); // Assert Assert.NotNull(result); } [Fact] public async Task GetById() { // Arrange _crudRepository.Setup(x => x.GetById(1)) .Returns(Task.FromResult(new LogEntity())); // Act var service = new LogService(_logger.Object, _crudRepository.Object); var result = await service.GetById(1); // Assert Assert.NotNull(result); } [Fact] public async Task Select() { // Arrange _crudRepository.Setup(x => x.Select(a => a.Id == 1)) .Returns(Task.FromResult<IEnumerable<LogEntity>>(new List<LogEntity>())); // Act var service = new LogService(_logger.Object, _crudRepository.Object); var result = await service.Select(a => a.Id == 1); // Assert Assert.NotNull(result); } [Fact] public async Task Insert() { // Arrange var log = new LogEntity(); // Act var service = new LogService(_logger.Object, _crudRepository.Object); var result = await Record.ExceptionAsync(async () => await service.Insert(log)); // Assert Assert.Null(result); } [Fact] public async Task InsertAll() { // Act var service = new LogService(_logger.Object, _crudRepository.Object); var result = await Record.ExceptionAsync(async () => await service.InsertAll(new List<LogEntity>())); // Assert Assert.Null(result); } [Fact] public async Task Update() { // Arrange var log = new LogEntity(); // Act var service = new LogService(_logger.Object, _crudRepository.Object); var result = await Record.ExceptionAsync(() => service.Update(log)); // Assert Assert.Null(result); } [Fact] public async Task Delete() { // Arrange var log = new LogEntity(); // Act var service = new LogService(_logger.Object, _crudRepository.Object); var result = await Record.ExceptionAsync(() => service.Delete(log)); // Assert Assert.Null(result); } } }<file_sep>/NetSimpleAuth.Backend.Test/Controllers/LogControllerTest.cs using System.IO; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Moq; using NetSimpleAuth.Backend.API.Controllers.v1; using NetSimpleAuth.Backend.Domain.Dto; using NetSimpleAuth.Backend.Domain.Entities; using NetSimpleAuth.Backend.Domain.Interfaces.IServices; using NetSimpleAuth.Backend.Domain.Response; using Xunit; namespace NetPOC.Backend.Test.Controllers { public class LogControllerTest { private readonly Mock<ILogger<LogController>> _logger; private readonly Mock<ILogService> _logService; public LogControllerTest() { _logger = new Mock<ILogger<LogController>>(); _logService = new Mock<ILogService>(); } [Fact] public async Task InsertBatch() { // Arrange var ms = new MemoryStream(Encoding.UTF8.GetBytes("")); // Act var controller = new LogController(_logger.Object, _logService.Object); var result = await controller.InsertBatch(new FormFile(ms, 0, 0, "", "")); // Assert Assert.IsType<OkObjectResult>(result.Result); } [Fact] public async Task SelectPaginated() { // Arrange var logFilterDto = new LogFilterDto(); _logService.Setup(a => a.SelectPaginated(logFilterDto, 0, 0)) .ReturnsAsync(new SelectPaginatedResponse<LogEntity>()); // Act var controller = new LogController(_logger.Object, _logService.Object); var result = await controller.SelectPaginated(logFilterDto, 0, 0); // Assert Assert.IsType<OkObjectResult>(result.Result); } } }<file_sep>/NetSimpleAuth.Backend.Domain/Interfaces/IServices/IAccountService.cs using System.Threading.Tasks; using NetSimpleAuth.Backend.Domain.Dto; using NetSimpleAuth.Backend.Domain.Response; namespace NetSimpleAuth.Backend.Domain.Interfaces.IServices { /// <summary> /// Service with account methods /// </summary> public interface IAccountService { /// <summary> /// Authenticates user /// </summary> /// <param name="authUserDto">DTO with user information</param> /// <returns>Authenticated user</returns> Task<AuthUserResponse> Authenticate(AuthUserDto authUserDto); } }<file_sep>/NetSimpleAuth.Backend.Application/Services/LogService.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using NetSimpleAuth.Backend.Domain.Dto; using NetSimpleAuth.Backend.Domain.Entities; using NetSimpleAuth.Backend.Domain.Interfaces.IRepositories; using NetSimpleAuth.Backend.Domain.Interfaces.IServices; using NetSimpleAuth.Backend.Domain.Response; namespace NetSimpleAuth.Backend.Application.Services { /// <inheritdoc cref="ILogService" /> public class LogService : CrudService<LogEntity>, ILogService { private readonly ILogger<LogService> _logger; private readonly ILogRepository _logRepository; public LogService(ILogger<LogService> logger, ILogRepository logRepository) : base(logger, logRepository) { _logger = logger; _logRepository = logRepository; } public async Task InsertBatch(StreamReader file) { try { string line; var logList = new List<LogEntity>(); while ((line = await file.ReadLineAsync()) != null) { _logger.LogDebug("Current line: {$Line}", line); var values = line.Split(null).Select(a => a == "-"? null : a).ToArray(); Enum.TryParse(values[8], out HttpStatusCode parsedStatusCode); int.TryParse(values[9], out var parsedContentSize); var logModel = new LogEntity { Ip = values[0], App = values[1], User = values[2], Date = DateTime.ParseExact(values[3].TrimStart('[') + values[4].TrimEnd(']'), "dd/MMM/yyyy:HH:mm:sszzz", null), RequestType = values[5].TrimStart('"'), RequestUrl = values[6], RequestProtocol = values[7].TrimEnd('"'), StatusCode = parsedStatusCode, ContentSize = parsedContentSize, }; if (values.Length > 10) { logModel.ResponseUrl = values[10]; logModel.UserAgent = values[11].TrimStart('"'); var index = 11; while (index ++ < values.Length - 1) { logModel.UserAgent += " "; logModel.UserAgent += values[index]; } logModel.UserAgent = logModel.UserAgent.TrimEnd('"'); } logList.Add(logModel); } await _logRepository.InsertAll(logList); _logRepository.Save(); } catch (Exception e) { _logger.LogError(e, "Error during batch insertion"); throw; } } public async Task<SelectPaginatedResponse<LogEntity>> SelectPaginated(LogFilterDto filter, int pageNumber, int pageSize) { try { var result = await _logRepository.SelectPaginated(filter, pageNumber, pageSize); return result; } catch (Exception e) { _logger.LogError(e, "Pagination failed for filter = {@Filter}, page number = {$PageNumber} and page size = {$PageSize}", filter, pageNumber, pageSize); throw; } } } }<file_sep>/NetSimpleAuth.Backend.Test/Controllers/CrudControllerBaseTest.cs using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Moq; using NetSimpleAuth.Backend.API.Controllers.v1; using NetSimpleAuth.Backend.Domain.Entities; using NetSimpleAuth.Backend.Domain.Interfaces.IServices; using Xunit; namespace NetSimpleAuth.Backend.Test.Controllers { public class CrudControllerBaseTest { private readonly Mock<ILogger<LogController>> _logger; private readonly Mock<ILogService> _crudService; public CrudControllerBaseTest() { _logger = new Mock<ILogger<LogController>>(); _crudService = new Mock<ILogService>(); } [Fact] public async Task GetAll() { // Arrange var logs = new LogEntity[] { new LogEntity() }; _crudService.Setup(x => x.GetAll()) .Returns(Task.FromResult<IEnumerable<LogEntity>>(logs)); // Act var controller = new LogController(_logger.Object, _crudService.Object); var result = await controller.GetAll(); // Assert Assert.IsType<OkObjectResult>(result.Result); } [Fact] public async Task GetById() { // Arrange _crudService.Setup(x => x.GetById(1)) .Returns(Task.FromResult(new LogEntity())); // Act var controller = new LogController(_logger.Object, _crudService.Object); var result = await controller.GetById(1); // Assert Assert.IsType<OkObjectResult>(result.Result); } [Fact] public async Task Insert() { // Arrange var log = new LogEntity(); // Act var controller = new LogController(_logger.Object, _crudService.Object); var result = await Record.ExceptionAsync(async () => await controller.Insert(log)); // Assert Assert.Null(result); } [Fact] public async Task Update() { // Arrange var log = new LogEntity(); // Act var controller = new LogController(_logger.Object, _crudService.Object); var result = await Record.ExceptionAsync(() => controller.Update(log)); // Assert Assert.Null(result); } [Fact] public async Task Delete() { // Act var controller = new LogController(_logger.Object, _crudService.Object); var result = await Record.ExceptionAsync(() => controller.Delete(1)); // Assert Assert.Null(result); } } }<file_sep>/NetSimpleAuth.Backend.Infra/Maps/LogMap.cs using Dapper.FluentMap.Dommel.Mapping; using NetSimpleAuth.Backend.Domain.Entities; namespace NetSimpleAuth.Backend.Infra.Maps { public class LogMap : DommelEntityMap<LogEntity> { public LogMap() { ToTable("Log"); Map(p => p.Id).IsKey(); } } }<file_sep>/NetSimpleAuth.Backend.Domain/Dto/LogFilterDto.cs namespace NetSimpleAuth.Backend.Domain.Dto { public class LogFilterDto { public string Ip { get; set; } public int? Hour { get; set; } public string UserAgent { get; set; } public string Order { get; set; } public string Direction { get; set; } } }<file_sep>/NetSimpleAuth.Backend.Test/Services/LogServiceTest.cs using System.IO; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Moq; using NetSimpleAuth.Backend.Application.Services; using NetSimpleAuth.Backend.Domain.Dto; using NetSimpleAuth.Backend.Domain.Entities; using NetSimpleAuth.Backend.Domain.Interfaces.IRepositories; using NetSimpleAuth.Backend.Domain.Response; using Xunit; namespace NetSimpleAuth.Backend.Test.Services { public class LogServiceTest { private readonly Mock<ILogger<LogService>> _logger; private readonly Mock<ILogRepository> _logRepository; public LogServiceTest() { _logger = new Mock<ILogger<LogService>>(); _logRepository = new Mock<ILogRepository>(); } [Fact] public async Task InsertBatch() { // Arrange const string content = "172.16.17.32 test - [04/Nov/2020:12:16:04 -1000] \"PUT http://test.com HTTP/1.0\" 422 1 \"http://test2.com\" \"Mozilla/5.0\"\n" + "172.16.31.10 - - [20/Aug/2019:20:24:09 -1200] \"POST http://teste3.com/ HTTP/1.1\" 200 884"; var ms = new MemoryStream(Encoding.UTF8.GetBytes(content)); // Act var service = new LogService(_logger.Object, _logRepository.Object); var result = await Record.ExceptionAsync(async () => await service.InsertBatch(new StreamReader(ms))); // Assert Assert.Null(result); } [Fact] public async Task SelectPaginated() { // Arrange var logFilter = new LogFilterDto(); _logRepository.Setup(a => a.SelectPaginated(logFilter, 0, 0)) .ReturnsAsync(new SelectPaginatedResponse<LogEntity>()); // Act var service = new LogService(_logger.Object, _logRepository.Object); var result = await service.SelectPaginated(logFilter, 0, 0); // Assert Assert.NotNull(result); } } }<file_sep>/NetSimpleAuth.Backend.Domain/Interfaces/IRepositories/IUserRepository.cs using NetSimpleAuth.Backend.Domain.Entities; namespace NetSimpleAuth.Backend.Domain.Interfaces.IRepositories { public interface IUserRepository : ICrudRepository<UserEntity> { } }<file_sep>/NetSimpleAuth.Backend.Domain/Response/SelectPaginatedResponse.cs using System.Collections.Generic; namespace NetSimpleAuth.Backend.Domain.Response { public class SelectPaginatedResponse<T> where T : class { public IEnumerable<T> Obj { get; set; } public int Count { get; set; } } }<file_sep>/NetSimpleAuth.Backend.Infra/Maps/UserMap.cs using Dapper.FluentMap.Dommel.Mapping; using NetSimpleAuth.Backend.Domain.Entities; namespace NetSimpleAuth.Backend.Infra.Maps { public class UserMap: DommelEntityMap<UserEntity> { public UserMap() { ToTable("User"); Map(p => p.Id).IsKey(); } } }<file_sep>/NetSimpleAuth.Backend.Infra/Migrations/TestMigration.cs using FluentMigrator; using NetSimpleAuth.Backend.Application.Helpers; namespace NetSimpleAuth.Backend.Infra.Migrations { [Migration(1)] public class TestMigration : Migration { public override void Up() { const string defaultUser = "admin"; const string defaultPassword = "<PASSWORD>"; Create.Table("Log") .WithColumn("Id").AsInt32().PrimaryKey().Identity() .WithColumn("Ip").AsString(19) .WithColumn("App").AsString(50).Nullable() .WithColumn("User").AsString(50).Nullable() .WithColumn("Date").AsDateTime() .WithColumn("RequestType").AsString(25) .WithColumn("RequestUrl").AsString(100) .WithColumn("RequestProtocol").AsString(10) .WithColumn("StatusCode").AsInt32() .WithColumn("ContentSize").AsInt32().Nullable() .WithColumn("ResponseUrl").AsString(200).Nullable() .WithColumn("UserAgent").AsString(200).Nullable(); Create.Table("User") .WithColumn("Id").AsInt32().PrimaryKey().Identity() .WithColumn("FirstName").AsString(100) .WithColumn("LastName").AsString(100) .WithColumn("Email").AsString(100) .WithColumn("UserName").AsString(100) .WithColumn("Password").AsString(300) .WithColumn("PasswordSalt").AsString(100); var salt = CryptographyService.CreateSalt(64); var password = CryptographyService.HashPassword(defaultPassword + salt); Insert.IntoTable("User") .Row(new { FirstName = "Dan", LastName = "Coelho", Email = "<EMAIL>", UserName = defaultUser, Password = <PASSWORD>, PasswordSalt = salt }); Create.Table("RefreshToken") .WithColumn("Id").AsInt32().PrimaryKey().Identity() .WithColumn("UserId").AsInt32().ForeignKey("User", "Id") .WithColumn("Token").AsString(200) .WithColumn("Expires").AsDateTime() .WithColumn("Created").AsDateTime() .WithColumn("CreatedByIp").AsString(19) .WithColumn("Revoked").AsDateTime().Nullable() .WithColumn("RevokedByIp").AsString(19).Nullable() .WithColumn("ReplacedByToken").AsString(200).Nullable() .WithColumn("IsActive").AsBoolean(); } public override void Down() { Delete.Table("Log"); Delete.Table("RefreshToken"); Delete.Table("User"); } } }<file_sep>/NetSimpleAuth.Backend.Domain/Interfaces/IRepositories/ILogRepository.cs using System.Threading.Tasks; using NetSimpleAuth.Backend.Domain.Dto; using NetSimpleAuth.Backend.Domain.Entities; using NetSimpleAuth.Backend.Domain.Response; namespace NetSimpleAuth.Backend.Domain.Interfaces.IRepositories { public interface ILogRepository : ICrudRepository<LogEntity> { /// <summary> /// Repository service to search for a list of objects paginated according to an expression /// </summary> /// <param name="filter">The predicate of the objects to be searched</param> /// <param name="pageNumber">The page number</param> /// <param name="pageSize">The size of the pages</param> /// <returns></returns> Task<SelectPaginatedResponse<LogEntity>> SelectPaginated(LogFilterDto filter, int pageNumber, int pageSize); } }
df8cc8fa538bef49bc2cfaa433907cc14c889f24
[ "C#" ]
23
C#
MrDanCoelho/NetSimpleAuth-Backend
d10eaf2463381e4828faa660decb11f3614718dc
30c761f899c304197ce1f4499787ef7504d459a8
refs/heads/master
<repo_name>isgasho/Asgard<file_sep>/constants/master.go package constants import "time" var ( MASTER_IP = "127.0.0.1" MASTER_PORT = "9527" MASTER_MONITER = 10 MASTER_NOTIFY = false MASTER_RECEIVER = "" MASTER_TICKER *time.Ticker MASTER_TTL = int64(10) MASTER_SCHEMA = "Asgard" ) <file_sep>/registry/registry.go package registry import ( "context" "fmt" "time" "github.com/coreos/etcd/clientv3" "github.com/dalonghahaha/avenger/components/logger" "Asgard/constants" "Asgard/runtimes" ) var r *etcdRegistry type etcdRegistry struct { ttl int64 schema string exitSingel chan bool ticker *time.Ticker client *clientv3.Client } func RegisterRegistry(Endpoints []string) error { config := clientv3.Config{ Endpoints: Endpoints, } client, err := clientv3.New(config) if err != nil { return err } r = &etcdRegistry{ ttl: constants.MASTER_TTL, schema: constants.MASTER_SCHEMA, client: client, ticker: time.NewTicker(time.Second * time.Duration(constants.MASTER_TTL)), } return nil } func Register(name, id, ip, port string) { go r.keepAlive(name, id, fmt.Sprintf("%s:%s", ip, port)) } func UnRegister(name, id string) { r.ticker.Stop() _, err := r.client.Delete(context.Background(), "/"+r.schema+"/"+name+"/"+id) if err != nil { logger.Errorf("Etcd Delete failed:%+v", err) } } func (r *etcdRegistry) keepAlive(name, id, addr string) { logger.Debugf("keepAlive ticker start!") runtimes.SubscribeExit(r.exitSingel) for { select { case <-r.exitSingel: logger.Debugf("keepAlive monitor ticker stop!") r.ticker.Stop() break case <-r.ticker.C: getResp, err := r.client.Get(context.Background(), "/"+r.schema+"/"+name+"/"+id) if err != nil { logger.Errorf("Etcd Get failed:%+v", err) } else if getResp.Count == 0 { err = r.withAlive(name, id, addr, r.ttl) if err != nil { logger.Errorf("withAlive failed:%+v", err) } } } } } func (r *etcdRegistry) withAlive(name, id, addr string, ttl int64) error { leaseResp, err := r.client.Grant(context.Background(), ttl) if err != nil { return err } _, err = r.client.Put(context.Background(), "/"+r.schema+"/"+name+"/"+id, addr, clientv3.WithLease(leaseResp.ID)) if err != nil { return err } _, err = r.client.KeepAlive(context.Background(), leaseResp.ID) if err != nil { return err } return nil }
a0e6e7abc5cef94bbc75022fb96be3704794569d
[ "Go" ]
2
Go
isgasho/Asgard
15540ac8f9bc4c16cd78ce6e86282ec8fe785c0f
d6794c2428a2d2999a5ff64f29fbe0ef3b729b13
refs/heads/master
<file_sep>// // Created by anselme on 2021-07-24. // #ifndef TASKPAD_NEW_TODO_H #define TASKPAD_NEW_TODO_H void newTodo(const string& todo){ std::cout << "New tod " ; } #endif //TASKPAD_NEW_TODO_H <file_sep>#include "app/header.h" #include "functions/app-introduction.h" #include "functions/print-help.h" #include "functions/handle-command.h" #include "functions/new-todo.h" #include "functions/all-todos.h" int main(int argc, char *argv[]) { // print application introduction ... const vector<string> args(argv+1,argv+argc); printAppIntroduction(); if(argc > 1) { Commands request = handleCommand(args[0]); switch (request) { case NEW_TODO: newTodo(argv[1]); break; case SHOW_ALL: allTodos(); break; default: printHelp(); } }else { printHelp(); } return 0; } <file_sep>// // Created by anselme on 2021-07-24. // Commands handleCommand(const string& command) { cout << command << endl; if (command == "--new") { cout << "New todo ... "; return NEW_TODO; } else if (command == "--all") return SHOW_ALL; else return SHOW_HELP; }<file_sep>// // Created by anselme on 2021-07-24. // enum Commands { SHOW_ALL, NEW_TODO, SHOW_HELP }; <file_sep>// // Created by anselme on 2021-07-24. // #include <iostream> #include <vector> #include <cstring> using namespace std; #include "../constants/commands.h" #define color_blue 9<file_sep>// // Created by anselme on 2021-07-24. // void printHelp(){ cout << " Help : " << endl; cout << " --new [Todo name] : Create a new todo" << endl; cout << " --all : Show all todos" << endl << endl; }<file_sep>// // Created by anselme on 2021-07-25. // #include "Todo.h" <file_sep>// // Created by anselme on 2021-07-25. // #ifndef TASKPAD_TODO_H #define TASKPAD_TODO_H class Todo { }; #endif //TASKPAD_TODO_H <file_sep>// // Created by anselme on 2021-07-24. // #ifndef TASKPAD_ALL_TODOS_H #define TASKPAD_ALL_TODOS_H void allTodos(){ std::cout << "All todos "; } #endif //TASKPAD_ALL_TODOS_H
a86144fe17893efe3294fe2d2530f53a917fc055
[ "C", "C++" ]
9
C++
irumvanselme/taskpad
f971c1ea05b17d6bc085bb1068c66549e276ec18
f161604db6dde1bf3645d354c903ce110698f948
refs/heads/master
<file_sep>import json from pathlib import Path EPSILONS = [0.25] DISCOUNTS = [0.7, 0.9] LRS = [0.0003] POLICIES = ['IANN'] TEMPERATURES = [0.4, 0.7, 0.9] def main(): with open(Path('default_hyper_parameters.json')) as f: default = json.load(f) for policy in POLICIES: tmp = default if policy == 'SOFTMAX': for temp in TEMPERATURES: for discount in DISCOUNTS: for lr in LRS: tmp['discount'] = discount tmp['learning_rate'] = lr tmp['policy'] = policy tmp['temperature'] = temp with open(Path(f"./configs/rew5_{policy}_temp{temp}_disc{discount}_lr{lr}.json"), 'w') as f: json.dump(tmp, f) elif policy == 'IANN': for eps in EPSILONS: for temp in TEMPERATURES: for discount in DISCOUNTS: for lr in LRS: tmp['epsilon'] = eps tmp['discount'] = discount tmp['learning_rate'] = lr tmp['policy'] = policy tmp['temperature'] = temp with open(Path(f"./configs/rew5_{policy}_eps{eps}_temp{temp}_disc{discount}_lr{lr}.json"), 'w') as f: json.dump(tmp, f) if __name__ == '__main__': main() <file_sep>import os import subprocess import sys from datetime import datetime from pathlib import Path from sys import stdout from time import sleep ROUNDS = 300000 MODEL_ROOT_DIR = "./models/opponents" CONFIGS_DIR = "./configs" MAX_PARALLEL = 30 class Scheduler: def __init__(self): self.processes = [(None, None)] * MAX_PARALLEL self.next_free = 0 def wait_for_free(self): while True: for index, process in enumerate(self.processes): if process[0] is None: self.next_free = index return if process[0].poll() is not None: self.next_free = index self.processes[index] = (None, None) return sleep(30) def execute(self, path: Path): if self.next_free is None: raise Exception("No free slot") current = Path(".") p = subprocess.Popen( [sys.executable, "./main.py", "play", "--my-agent", "auto_bomber", "--train", "1", "--n-rounds", f"{ROUNDS}", "--no-gui"], env=dict(os.environ, MODEL_DIR=MODEL_ROOT_DIR + path.relative_to(current).__str__(), CONFIG_FILE=path.absolute()), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) print(f"[{datetime.now(tz=None).strftime('%m/%d/%Y, %H:%M:%S')}] Started: {path.__str__()} - pid: {p.pid}") self.processes[self.next_free] = (p, path.stem) self.next_free = None def terminate(self, name): for index, process in enumerate(self.processes): if process[1] == name: process[0].terminate() self.processes[index] = (None, None) def wait(self): for p, n in self.processes: if p is not None: p.wait() if __name__ == '__main__': scheduler = Scheduler() configs_to_process = Path(CONFIGS_DIR).glob("**/*.json") for config in configs_to_process: scheduler.wait_for_free() scheduler.execute(config) stdout.flush() scheduler.wait() <file_sep>import numpy as np class Transitions: def __init__(self, feature_extractor): self.states = [] self.actions = [] self.next_states = [] self.rewards = [] self.feature_extractor = feature_extractor def add_transition(self, old_game_state, action, new_game_state, rewards): self.states.append(self.feature_extractor(old_game_state)) self.actions.append(action) self.next_states.append(self.feature_extractor(new_game_state)) self.rewards.append(rewards) def to_numpy_transitions(self, hyper_parameters): return NumpyTransitions(self, hyper_parameters) def clear(self): self.states.clear() self.actions.clear() self.next_states.clear() self.rewards.clear() class NumpyTransitions: # todo add hyperparam for batch size to support TD-n-step and monte-carlo def __init__(self, transitions, hyper_parameters): self.states = np.asarray(transitions.states, dtype=np.float32) self.actions = np.asarray(transitions.actions) self.next_states = np.asarray(transitions.next_states, dtype=np.float32) self.rewards = np.asarray(transitions.rewards, dtype=np.float32) self.hyper_parameters = hyper_parameters def get_time_steps_for_action(self, action): return np.argwhere(self.actions == action) def get_features_and_value_estimates(self, action): relevant_indices = self.get_time_steps_for_action(action) value_estimations = np.zeros((len(relevant_indices),), dtype=np.float32) for i in range(len(relevant_indices)): value_estimations[i] = self.monte_carlo_value_estimation(np.asscalar(relevant_indices[i])) return np.take(self.states, relevant_indices, axis=0).squeeze(axis=1), value_estimations def monte_carlo_value_estimation(self, time_step_start: int): relevant_rewards = self.rewards[time_step_start:] discounts = np.fromfunction(lambda i: self.hyper_parameters["discount"] ** i, shape=(len(relevant_rewards),), dtype=np.float32) return np.sum(discounts * relevant_rewards) <file_sep>#!/usr/bin/env bash python3 main.py play --agents auto_bomber --train 1 --n-rounds 100000 --no-gui <file_sep>import numpy as np from scipy.special import softmax from scipy.spatial.distance import cdist def state_to_features(game_state: dict) -> np.array: """ Converts the game state to the input of your model, i.e. a feature vector. You can find out about the state of the game environment via game_state, which is a dictionary. Consult 'get_state_for_agent' in environment.py to see what it contains. :param game_state: A dictionary describing the current game board. :return: np.array """ if game_state is None: return np.random.rand(21) field_width, field_height = game_state['field'].shape assert field_width == field_height, "Field is not rectangular, some assumptions do not hold. Abort!" agent_position = np.asarray(game_state['self'][3], dtype='int') agent_bomb_action = np.asarray(game_state['self'][2], dtype='int') bombs_position = np.atleast_2d(np.asarray([list(bomb[0]) for bomb in game_state['bombs']], dtype='int')) explosions_position = np.argwhere(game_state['explosion_map'] > 0) coins_position = np.atleast_2d(np.array(game_state['coins'], dtype='int')) relevant_coins_position = coins_position[~np.isin(coins_position, agent_position).all(axis=1)] crates_position = np.argwhere(game_state['field'] == 1) walls_position = np.argwhere(game_state['field'] == -1) weight_opponents_with_bomb = 0.8 opponents_position = np.atleast_2d(np.asarray([list(player[3]) for player in game_state['others']], dtype='int')) opponents_bomb_action = np.asarray([player[2] for player in game_state['others']]) opponents_bomb_action = np.where(opponents_bomb_action, weight_opponents_with_bomb, 1.0) ############################################# # DISCARDED # # Bombs zones logic: # # Due to bad performance in empirical tests # ############################################# # # # bombs_zones = _compute_zones_heatmap(agent_position, bombs_position, 0.0, # lambda v, w: np.where(v > 0., v[(3 + w) - v >= 0] ** w[(3 + w) - v >= 0], 0.0), # bombs_countdown, # lambda v: np.mean(v[v != 0.0]) if v[v != 0.0].size != 0 else 0.0, # lambda v: -1 * np.divide(1, v, out=np.zeros_like(v), where=v != 0)) coins_zones = _compute_zones_heatmap(agent_position, relevant_coins_position, 0.0, aggregation_func=lambda v: np.mean(v) if v.size != 0 else 0.0, normalization_func=lambda v: np.divide(1, v, out=np.zeros_like(v), where=v != 0)) crates_zones = _compute_zones_heatmap(agent_position, crates_position, 0.0, aggregation_func=lambda v: np.mean(v) if v.size != 0 else 0.0, normalization_func=lambda v: np.divide(1, v, out=np.zeros_like(v), where=v != 0)) opponents_zones = _compute_zones_heatmap(agent_position, opponents_position, 0.0, weighting_func=lambda v, w: v * w, weights=opponents_bomb_action, aggregation_func=lambda v: np.mean(v) if v.size != 0 else 0.0, normalization_func=lambda v: np.divide(1, v, out=np.zeros_like(v), where=v != 0)) bombs_field_of_view = _object_in_field_of_view(agent_position, bombs_position, 0.0, lambda v, w: -1 * np.divide(1, v, out=np.zeros_like(v), where=v != 0), None) explosion_field_of_view = _object_in_field_of_view(agent_position, explosions_position, 0.0) coins_field_of_view = _object_in_field_of_view(agent_position, relevant_coins_position, 0.0, lambda v, w: np.divide(1, v, out=np.zeros_like(v), where=v != 0), None) crates_field_of_view = _object_in_field_of_view(agent_position, crates_position, 0.0, lambda v, w: np.divide(1, v, out=np.zeros_like(v), where=v != 0), None) opponents_field_of_view = _object_in_field_of_view(agent_position, opponents_position, 0.0, lambda v, w: np.divide(1, v, out=np.zeros_like(v), where=v != 0), None) walls_field_of_view = _object_in_field_of_view(agent_position, walls_position, 0.0) f_obstacles = np.zeros((4,)) f_obstacles[walls_field_of_view == 1.] = -1. f_obstacles[explosion_field_of_view == 1.] = -1. f_obstacles[bombs_field_of_view == -1.] = -1. f_obstacles[crates_field_of_view == 1.] = -1. new_bombs_field_of_view = np.copy(bombs_field_of_view) if bombs_position.size != 0 and np.isin(bombs_position, agent_position).all(axis=1).any(): new_bombs_field_of_view = np.array([0.25, 0.25, 0.25, 0.25]) else: for i in range(4): new_bombs_field_of_view[i] += np.sum(-1 * np.delete(bombs_field_of_view / 3., i)) new_bombs_field_of_view[bombs_field_of_view == -1.] = -1. f_bombs = new_bombs_field_of_view f_coins = np.sum(np.vstack((coins_zones, 5 * coins_field_of_view)), axis=0) f_coins[walls_field_of_view == 1.] = 0. if not np.all((f_coins == 0.)): f_coins = np.where(f_coins == 0., -np.inf, f_coins) f_coins = softmax(f_coins) f_crates = np.sum(np.vstack((crates_zones, 5 * crates_field_of_view)), axis=0) f_crates[walls_field_of_view == 1.] = 0. if not np.all((f_crates == 0.)): f_crates = np.where(f_crates == 0., -np.inf, f_crates) f_crates = softmax(f_crates) f_crates[crates_field_of_view == 1.] = -1. f_opponents = np.sum(np.vstack((opponents_zones, 5 * opponents_field_of_view)), axis=0) f_opponents[walls_field_of_view == 1.] = 0. if not np.all((f_opponents == 0.)): f_opponents = np.where(f_opponents == 0., -np.inf, f_opponents) f_opponents = softmax(f_opponents) f_opponents[opponents_field_of_view == 1.] = -1. features = np.concatenate((f_coins, f_crates, f_bombs, f_opponents, f_obstacles, agent_bomb_action), axis=None) return features def _compute_zones_heatmap(agent_position, objects_position, initial, weighting_func=None, weights=None, aggregation_func=None, normalization_func=None): """ Computes the distance of given objects from the agent and determines their position relative to the agent. The game field is divided in 4 quadrants relative to the agent's position, each covering an angle of 90 degrees. The quadrants, i.e. zones, are thus above, left, below, right of the agent. An optional weighting can be applied to the objects. Parameters ---------- agent_position : np.array Position of the agent (x, y) objects_position : np.array Position of the objects on the field weighting_func : callable, optional Function to additionally weight the objects weights : np.array Weights to apply to the objects' distance normalization_func : callable, optional Function to normalize (or scale) the aggregated value in the zones Returns ------- list A list with 4 values (right, down, left, up) representing the (weighted) density of the specified objects in the quadrants around the agent """ zones = np.full(shape=(4,), fill_value=initial) if objects_position.size == 0: return zones agent_position = np.atleast_2d(agent_position) distances = cdist(agent_position, objects_position, 'cityblock').squeeze(axis=0) agent_position = agent_position[0] if weighting_func: distances = weighting_func(distances, weights) angles = np.degrees( np.arctan2(objects_position[:, 1] - agent_position[1], objects_position[:, 0] - agent_position[0])) angles = (angles + 360) % 360 # Computed: RIGHT; Actual: RIGHT zones[0] = aggregation_func( distances[np.where(((angles >= 0) & (angles < 45)) | ((angles >= 315) & (angles <= 360)))]) # Computed: UP; Actual: DOWN zones[1] = aggregation_func(distances[np.where((angles >= 45) & (angles < 135))]) # Computed: LEFT; Actual: LEFT zones[2] = aggregation_func(distances[np.where((angles >= 135) & (angles < 225))]) # Computed: DOWN; Actual: UP zones[3] = aggregation_func(distances[np.where((angles >= 225) & (angles < 315))]) if normalization_func: zones = normalization_func(zones) return zones def _object_in_field_of_view(agent_position, objects_position, initial, normalization_func=None, norm_constant=None): """ Specifies the field of view w.r.t the given objects. When computing the distance of the agent to the objects, the agent's own position is included, i.e. if the agent is ON the object the distance is 0.0 . Parameters ---------- agent_position : np.array Position of the agent (x, y) objects_position : np.array Position of the objects on the field normalization_func : callable, optional Function to normalize (or scale) the distances on the 4 directions norm_constant : Constant used for the normalization Returns ------- list A list with 4 values (right, down, left, up) representing the distance of the agent to the nearest object (if any) below, left, above, right of it. """ field_of_view = np.full(shape=(4,), fill_value=initial) if objects_position.size == 0: return field_of_view agent_position = np.atleast_2d(agent_position) # Coordinate x is as of the framework field objects_on_x = objects_position[np.where(objects_position[:, 0] == agent_position[0, 0])] # Directions are actual directions, i.e. after translation of framework fields objects_down = objects_on_x[np.where(objects_on_x[:, 1] >= agent_position[0, 1])] if not objects_down.size == 0: field_of_view[1] = cdist(agent_position, objects_down, 'cityblock').squeeze(axis=0).min() objects_up = objects_on_x[np.where(objects_on_x[:, 1] <= agent_position[0, 1])] if not objects_up.size == 0: field_of_view[3] = cdist(agent_position, objects_up, 'cityblock').squeeze(axis=0).min() # Coordinate y is as of the framework field objects_on_y = objects_position[np.where(objects_position[:, 1] == agent_position[0, 1])] # Directions are actual directions, i.e. after translation of framework fields objects_right = objects_on_y[np.where(objects_on_y[:, 0] >= agent_position[0, 0])] if not objects_right.size == 0: field_of_view[0] = cdist(agent_position, objects_right, 'cityblock').squeeze(axis=0).min() objects_left = objects_on_y[np.where(objects_on_y[:, 0] <= agent_position[0, 0])] if not objects_left.size == 0: field_of_view[2] = cdist(agent_position, objects_left, 'cityblock').squeeze(axis=0).min() if normalization_func: field_of_view = normalization_func(field_of_view, norm_constant) return field_of_view <file_sep>import random import numpy as np from agent_code.auto_bomber.feature_engineering import state_to_features from agent_code.auto_bomber.model import LinearAutoBomberModel def setup(self): """ Setup your code. This is called once when loading each agent. Make sure that you prepare everything such that act(...) can be called. When in training mode, the separate `setup_training` in train.py is called after this method. This separation allows you to share your trained agent with other students, without revealing your training code. In this example, our model is a set of probabilities over actions that are is independent of the game state. :param self: This object is passed to all callbacks and you can set arbitrary values. """ self.model = LinearAutoBomberModel(self.train, feature_extractor=lambda x: state_to_features(x)) def act(self, game_state: dict) -> str: """ Your agent should parse the input, think, and take a decision. When not in training mode, the maximum execution time for this method is 0.5s. :param self: The same object that is passed to all of your callbacks. :param game_state: The dictionary that describes everything on the board. :return: The action to take as a string. """ hyper_parameters = self.model.hyper_parameters if self.train and hyper_parameters["policy"] == 'SOFTMAX': return self.model.select_best_action(game_state, self, softmax=True) elif self.train and random.random() < hyper_parameters["epsilon"]: if hyper_parameters["policy"] == 'GREEDY': self.logger.debug("Choosing action purely at random.") # 80%: walk in any direction. 10% wait. 10% bomb. return np.random.choice(hyper_parameters["actions"], p=[.2, .2, .2, .2, .1, .1]) elif hyper_parameters["policy"] == 'IANN': return self.model.select_best_action(game_state, self, softmax=True) else: self.logger.debug("Querying model for action.") return self.model.select_best_action(game_state, self) <file_sep>SAME_REGION = 'SAME_REGION'<file_sep>numpy==1.20.1 pygame==2.0.1 tqdm==4.58.0 tensorboardX==2.1 tensorboard==2.4.1 scipy==1.6.1<file_sep>import json import os import pickle import shutil from pathlib import Path import numpy as np from tensorboardX import SummaryWriter import agent_code.auto_bomber.model_path as model_path from agent_code.auto_bomber.transitions import Transitions def get_model_dir(): try: return os.environ["MODEL_DIR"] except KeyError as e: return model_path.MODEL_DIR def get_config_path(): try: return os.environ["CONFIG_FILE"] except KeyError as e: return "default_hyper_parameters.json" class LinearAutoBomberModel: def __init__(self, train, feature_extractor): self.train = train self.weights = None self.feature_extractor = feature_extractor self.determine_or_create_model_dir() self.weights_path = self.model_dir / "weights.pt" if self.weights_path.is_file(): with self.weights_path.open(mode="rb") as file: self.weights = pickle.load(file) hyper_parameters_path = self.model_dir / "hyper_parameters.json" if hyper_parameters_path.is_file(): with hyper_parameters_path.open(mode="rb") as file: self.hyper_parameters = json.load(file) if self.train: current = Path(model_path.MODELS_DEFAULT_ROOT) self.writer = SummaryWriter(logdir=f"{model_path.TF_BOARD_DIR}/{self.model_dir.relative_to(current)}") def store(self): with self.weights_path.open(mode="wb") as file: pickle.dump(self.weights, file) def select_best_action(self, game_state: dict, agent_self, softmax=False): features_x = self.feature_extractor(game_state) self.init_if_needed(features_x, agent_self) q_action_values = np.dot(self.weights, features_x) if softmax: temp = self.hyper_parameters["temperature"] p = np.exp(q_action_values / temp) / np.sum(np.exp(q_action_values / temp)) choice = np.random.choice(len(q_action_values), p=p) else: top_3_actions = q_action_values.argsort()[-3:][::-1] choice = self.filter_bomb_if_not_top_action(np.random.choice(top_3_actions, p=[0.9, 0.05, 0.05]), top_3_actions) return self.hyper_parameters["actions"][choice] def filter_bomb_if_not_top_action(self, choice, top_3_actions): if choice == 5 and choice != top_3_actions[0]: return top_3_actions[0] return choice def fit_model_with_transition_batch(self, transitions: Transitions, round: int): loss = [] numpy_transitions = transitions.to_numpy_transitions(self.hyper_parameters) for action_id, action in enumerate(self.hyper_parameters["actions"]): x_all_t, y_all_t = numpy_transitions.get_features_and_value_estimates(action) if x_all_t.size != 0: q_estimations = np.dot(x_all_t, self.weights[action_id]) residuals = y_all_t - q_estimations loss.append(np.mean(residuals ** 2)) q_grad = np.dot(x_all_t.T, residuals) weight_updates = self.hyper_parameters["learning_rate"] / y_all_t.shape[0] * q_grad self.weights[action_id] += weight_updates mean_loss = np.mean(loss) self.writer.add_scalar('loss', mean_loss, round) mean_reward = np.mean(numpy_transitions.rewards) self.writer.add_scalar('rewards', mean_reward, round) def init_if_needed(self, features_x, agent_self): if self.weights is None: agent_self.logger.info("Model is empty init with random weights.") # Xavier weights initialization self.weights = np.random.rand(len(self.hyper_parameters["actions"]), len(features_x)) * np.sqrt(1 / len(features_x)) def determine_or_create_model_dir(self): configured_model_dir = get_model_dir() if configured_model_dir and Path(configured_model_dir).is_dir(): self.model_dir = Path(configured_model_dir) elif self.train: self.create_model_dir(configured_model_dir) else: raise FileNotFoundError("The specified model directory does not exist!\n" "Create a new model by training first.") def create_model_dir(self, configured_model_dir): if configured_model_dir: self.model_dir = Path(configured_model_dir) else: root_dir = Path(model_path.MODELS_DEFAULT_ROOT) root_dir.mkdir(parents=True, exist_ok=True) existing_subdirs = sorted([int(x.stem) for x in root_dir.iterdir() if x.is_dir()]) model_index = existing_subdirs[-1] if existing_subdirs else -1 model_index += 1 self.model_dir = Path(model_path.MODELS_DEFAULT_ROOT) / str(model_index) self.model_dir.mkdir(parents=True) # Copy configuration file for logging purposes shutil.copy(Path(get_config_path()), self.model_dir / "hyper_parameters.json") shutil.copy(Path("feature_engineering.py"), self.model_dir / "feature_engineering.py") <file_sep>from queue import Queue from typing import List from agent_code.auto_bomber import custom_events as ce from agent_code.auto_bomber.feature_engineering import state_to_features from agent_code.auto_bomber.transitions import Transitions def setup_training(self): """ Initialise self for training purpose. This is called after `setup` in callbacks.py. :param self: This object is passed to all callbacks and you can set arbitrary values. """ # Setup an array that will track transition tuples self.transitions = Transitions(state_to_features) self.q = Queue(maxsize=self.model.hyper_parameters["region_time_tolerance"]) def game_events_occurred(self, old_game_state: dict, last_action: str, new_game_state: dict, events: List[str]): """ Called once per step to allow intermediate rewards based on game events. When this method is called, self.events will contain a list of all game events relevant to your agent that occurred during the previous step. Consult settings.py to see what events are tracked. You can hand out rewards to your agent based on these events and your knowledge of the (new) game state. This is *one* of the places where you could update your agent. -- > we will collect the transition only here :param self: This object is passed to all callbacks and you can set arbitrary values. :param old_game_state: The state that was passed to the last call of `act`. :param last_action: The action that you took. :param new_game_state: The state the agent is in now. :param events: The events that occurred when going from `old_game_state` to `new_game_state` """ # Punishment, if agent is still in the same radius after certain time steps new_position = new_game_state["self"][3] region_size = self.model.hyper_parameters["region_size"] if self.q.full(): old_position = self.q.get() if (old_position[0] - region_size <= new_position[0] <= old_position[0] + region_size) \ or (old_position[1] - region_size <= new_position[1] <= old_position[1] + region_size): events.append(ce.SAME_REGION) self.q.put(new_position) self.logger.debug(f'Encountered game event(s) {", ".join(map(repr, events))} in step {new_game_state["step"]}') # state_to_features is defined in callbacks.py self.transitions.add_transition(old_game_state, last_action, new_game_state, reward_from_events(self, events)) def end_of_round(self, last_game_state: dict, last_action: str, events: List[str]): """ Called at the end of each game or when the agent died to hand out final rewards. This is similar to reward_update. self.events will contain all events that occurred during your agent's final step. This is *one* of the places where you could update your agent. This is also a good place to store an agent that you updated. :param self: The same object that is passed to all of your callbacks. :param last_game_state: last entered game state (terminal state?) :param last_action: action executed last by agent :param events: events occurred before end of round (q: all events or all since last game_events_occurred(..) call?) """ self.logger.debug(f'Encountered event(s) {", ".join(map(repr, events))} in final step') self.transitions.add_transition(last_game_state, last_action, None, reward_from_events(self, events)) self.model.fit_model_with_transition_batch(self.transitions, last_game_state['round']) self.model.store() # clear experience buffer for next round self.transitions.clear() def reward_from_events(self, events: List[str]) -> int: """ *This is not a required function, but an idea to structure your code.* Here you can modify the rewards your agent get so as to en/discourage certain behavior. """ rewards_dict = self.model.hyper_parameters["game_rewards"] reward_sum = 0 for event in events: if event in rewards_dict: reward_sum += rewards_dict[event] self.logger.info(f"Awarded {reward_sum} for events {', '.join(events)}") return reward_sum <file_sep>MODELS_DEFAULT_ROOT = "./models" TF_BOARD_DIR = "./runs/opponents" MODEL_DIR = "./production/rew4_IANN_eps0.25_temp0.9_disc0.9_lr0.0003"
02e7dc69d9a28b9b186ea162c4fdea3b2565492c
[ "Python", "Text", "Shell" ]
11
Python
PrimeF/bomberman_rl
df0cdf7d356584ba5e59e9ffdceddb958b2e643b
f211a873af5dff3c6dd749e6dcad8be55a312607
refs/heads/master
<file_sep>-- phpMyAdmin SQL Dump -- version 3.5.2.2 -- http://www.phpmyadmin.net -- -- Inang: 127.0.0.1 -- Waktu pembuatan: 22 Jan 2018 pada 15.17 -- Versi Server: 5.5.27 -- Versi PHP: 5.4.7 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Basis data: `db_projectwork` -- -- -------------------------------------------------------- -- -- Struktur dari tabel `admin` -- CREATE TABLE IF NOT EXISTS `admin` ( `USERNAME` varchar(500) NOT NULL, `PASSWORD` varchar(500) DEFAULT NULL, PRIMARY KEY (`USERNAME`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `admin` -- INSERT INTO `admin` (`USERNAME`, `PASSWORD`) VALUES ('admin', '<PASSWORD>'); -- -------------------------------------------------------- -- -- Struktur dari tabel `customer` -- CREATE TABLE IF NOT EXISTS `customer` ( `NAMA_CUST` varchar(500) DEFAULT NULL, `KD_BOOKING` varchar(30) NOT NULL, `TELP` varchar(15) DEFAULT NULL, `TANGGAL` date NOT NULL, `USERNAME` varchar(500) DEFAULT NULL, `JENIS_ACARA` varchar(500) DEFAULT NULL, `JAM` varchar(500) DEFAULT NULL, `email` varchar(50) NOT NULL, `KETERANGAN` text, `READ` enum('unread','read') NOT NULL DEFAULT 'unread', PRIMARY KEY (`TANGGAL`), KEY `FK_MEMESAN` (`USERNAME`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `customer` -- INSERT INTO `customer` (`NAMA_CUST`, `KD_BOOKING`, `TELP`, `TANGGAL`, `USERNAME`, `JENIS_ACARA`, `JAM`, `email`, `KETERANGAN`, `READ`) VALUES ('hfjdh', 'K8Czh8p', '9832759235', '1010-10-10', NULL, 'Acara Umum', '11:11', '<EMAIL>', 'tggertg', 'read'), ('yufyudyf', 's3vxnUH', '8374972', '1090-11-10', NULL, 'Acara Sosial', '10:10', '<EMAIL>', 'hdfhvihv', 'read'), ('lalaland', 'p627jqh', '081292938913', '1098-08-14', NULL, 'Acara Umum', '05:05', '<EMAIL>', 'uekjtkrjt', 'read'), ('fhjhff', 'hm9T7ml', '924890234802', '1997-09-18', NULL, 'Acara Umum', '08:09', '<EMAIL>', 'ksdgjdfh', 'read'), ('kdfjhidf', 'E0ZhByG', '03249734', '1998-09-10', NULL, 'Acara Umum', '09:09', '<EMAIL>', 'egetget', 'read'), ('salsaaaa', 'BoSpw5K', '081257711574', '2010-10-10', NULL, 'Acara Umum', '08:00', '<EMAIL>', 'bismillah', 'read'), ('Ridha', '', '989898', '2018-01-10', 'admin', 'Umum', '09.00', '', 'pesan gedung tanpa pintu tanpa dinding', 'read'), ('qweq', '', '12345', '2018-01-12', NULL, 'acara sosial', '12.00', '', '', 'read'), ('Diraf', '', '123456', '2018-01-13', 'admin', 'Sosial', '10.00', '', 'Kursi dan sound ', 'read'), ('Rehan', '', '8888888', '2018-01-14', NULL, 'acara sosial', '09.00', '', '', 'read'), ('qwerty', '', '90900', '2018-01-15', NULL, 'acara umum', '12.00', '', '', 'read'), ('lisa', 'PYfvFmg', '08555555555', '2018-01-21', NULL, 'Acara Umum', '10:00', '', 'siap nikah', 'read'), ('malaaku', 'eFajP1U', '888', '2018-01-24', NULL, 'Acara Umum', '10:00', '', 'SIAP NIKAH', 'read'), ('salsaaaaa', 'bygJv8Q', '99999999', '2018-01-25', NULL, 'Acara Sosial', '10:58', '', 'whskqllhwsdwd', 'read'), ('qwertyuiopsdfghjkl', '0UNdNNx', '99999999', '2018-01-26', NULL, 'acara umum', '10.00', '', '', 'read'), ('faris', 'bVTCRzK', '99999999', '2018-01-27', NULL, 'Acara Umum', '11:00', '', 'mau sunatan', 'read'), ('riri', '', '89089', '2018-01-28', NULL, 'acara sosial', '09.00', '', '', 'read'), ('<NAME>', 'UemO8oe', '99999999', '2018-01-29', NULL, 'acara sosial', '18.00', '', 'hdashdkj', 'read'), ('qwww', '', '123467', '2018-01-31', NULL, 'acara sosial', '12.00', '', '', 'read'), ('jajaja', 'IsqqW5c', '888', '2018-02-02', NULL, 'Acara Umum', '10:10', '', 'hjhkhkdhajhhas', 'read'), ('asihdishdei', 'g56nzNo', '889979', '2018-02-03', NULL, 'Acara Umum', '00:00', '', 'shsdsakhdka', 'read'), ('nyenyeney', 'pJFZ2Ai', '99999999', '2018-02-10', NULL, 'acara umum', '14.00', '', 'hihihih', 'read'), ('iqbal', '', '1111', '2018-12-30', NULL, 'acara umum', '12.01', '', 'asdsa', 'read'); -- -------------------------------------------------------- -- -- Struktur dari tabel `konfirmasi_pembayaran` -- CREATE TABLE IF NOT EXISTS `konfirmasi_pembayaran` ( `KD_BOOKING` varchar(500) NOT NULL, `TANGGAL` date DEFAULT NULL, `USERNAME` varchar(500) DEFAULT NULL, `NAMA_KONFIR` varchar(500) DEFAULT NULL, `NO_REKENING` decimal(8,0) DEFAULT NULL, `JML_UANG` decimal(8,0) DEFAULT NULL, `STATUS` text, PRIMARY KEY (`KD_BOOKING`), KEY `FK_MENGECEK` (`USERNAME`), KEY `FK_MENGONFIRMASI` (`TANGGAL`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `konfirmasi_pembayaran` -- INSERT INTO `konfirmasi_pembayaran` (`KD_BOOKING`, `TANGGAL`, `USERNAME`, `NAMA_KONFIR`, `NO_REKENING`, `JML_UANG`, `STATUS`) VALUES ('0UNdNNx', '2018-01-26', NULL, 'qwertyuiopsdfghjkl', 1234567, 99999999, 'lunas'), ('asd123', '2018-01-10', 'admin', 'Febyani', 989, 99999999, NULL), ('BoSpw5K', '2010-10-10', NULL, NULL, NULL, NULL, 'Selesai'), ('bVTCRzK', '2018-01-27', NULL, 'wulan', 99999999, 80000, 'Selesai'), ('bygJv8Q', '2018-01-25', NULL, NULL, NULL, NULL, NULL), ('E0ZhByG', '1998-09-10', NULL, NULL, NULL, NULL, NULL), ('eFajP1U', '2018-01-24', NULL, NULL, NULL, NULL, NULL), ('g56nzNo', '2018-02-03', NULL, NULL, NULL, NULL, NULL), ('gh', NULL, NULL, 'ridha', 99999999, 800000, NULL), ('hm9T7ml', '1997-09-18', NULL, NULL, NULL, NULL, 'Lunas'), ('IsqqW5c', '2018-02-02', NULL, NULL, NULL, NULL, NULL), ('K8Czh8p', '1010-10-10', NULL, NULL, NULL, NULL, 'Lunas'), ('p627jqh', '1098-08-14', NULL, NULL, NULL, NULL, 'Lunas'), ('pJFZ2Ai', '2018-02-10', NULL, 'nyenyeney', NULL, NULL, 'Selesai'), ('PYfvFmg', '2018-01-21', NULL, 'louisa', 99999999, 10000, NULL), ('s3vxnUH', '1090-11-10', NULL, NULL, NULL, NULL, 'Selesai'), ('UemO8oe', '2018-01-29', NULL, NULL, NULL, NULL, NULL); -- -- Ketidakleluasaan untuk tabel pelimpahan (Dumped Tables) -- -- -- Ketidakleluasaan untuk tabel `customer` -- ALTER TABLE `customer` ADD CONSTRAINT `FK_MEMESAN` FOREIGN KEY (`USERNAME`) REFERENCES `admin` (`USERNAME`); -- -- Ketidakleluasaan untuk tabel `konfirmasi_pembayaran` -- ALTER TABLE `konfirmasi_pembayaran` ADD CONSTRAINT `FK_MENGECEK` FOREIGN KEY (`USERNAME`) REFERENCES `admin` (`USERNAME`), ADD CONSTRAINT `FK_MENGONFIRMASI` FOREIGN KEY (`TANGGAL`) REFERENCES `customer` (`TANGGAL`); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Penyewaan Aula SMK Telkom Malang</title> <!-- Bootstrap core CSS --> <link href="<?php echo base_url(); ?>assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="<?php echo base_url(); ?>assets/vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'> <!-- Custom styles for this template --> <link href="<?php echo base_url(); ?>assets/css/agency.css" rel="stylesheet"> </head> <body id="page-top"> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark fixed-top" id="mainNav"> <div class="container"> <a class="navbar-brand js-scroll-trigger" href="<?php echo base_url(); ?>index.php/home/">SMK Telkom Malang</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> Menu <i class="fa fa-bars"></i> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav text-uppercase ml-auto"> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="<?php echo base_url(); ?>index.php/home/">Kembali ke Home</a> </li> </ul> </div> </div> </nav> <section id="pemesanan"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading text-uppercase">Konfirmasi Pembayaran</h2> <h3 class="section-subheading text-muted">Isi Untuk konfirmasi setelah pembayaran.</h3> </div> </div> <div class="row"> <div class="col-lg-12"> <?php if ($this->session->flashdata('notif')):?> <div class="alert alert-info"><?php echo $this->session->flashdata('notif');?></div> <?php endif;?> <form id="target" method="post" action="<?php echo base_url();?>konfirmasi/konfir"> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> <div class="form-group"> <span style="color: white;">Kode Booking :</span> <input class="form-control" id="kd_booking" name="kd_booking" type="text" placeholder="Kode Booking" required data-validation-required-message="Silahkan isi Kode Booking Anda."> <p class="help-block text-danger"></p> </div> <div class="form-group"> <span style="color: white;">Nama Pengirim :</span> <input class="form-control" id="nama_konfir" name="nama_konfir" type="text" placeholder="Nama Pengirim" required data-validation-required-message="Silahkan isi nomor pemesanan Anda."> <p class="help-block text-danger"></p> </div> <div class="form-group"> <span style="color: white;">Nomor Rekening :</span> <input class="form-control" id="no_rekening" name="no_rekening" type="text" placeholder="Nomor Rekening" required data-validation-required-message="Silahkan isi nomor rekening Anda."> <p class="help-block text-danger"></p> </div> <div class="form-group"> <span style="color: white;">Jumlah Uang :</span> <input class="form-control" id="jml_uang" name="jml_uang" type="text" placeholder="Jumlah Uang" required data-validation-required-message="Silahkan isi jumlah uang yang telah Anda bayar."> <p class="help-block text-danger"></p> </div> </div> <div class="col-md-3"> </div> <div class="clearfix"></div> <div class="col-lg-12 text-center"> <div id="success"></div> <input type="submit" name="send" id="other" class="btn btn-primary btn-xl text-uppercase" value="KIRIM" /> </div> </div> </form> </div> </div> </div> </section> <script src="<?php echo base_url(); ?>assets/vendor/jquery/jquery.min.js"></script> <script src="<?php echo base_url(); ?>assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Plugin JavaScript --> <script src="<?php echo base_url(); ?>assets/vendor/jquery-easing/jquery.easing.min.js"></script> <!-- Contact form JavaScript --> <script src="<?php echo base_url(); ?>assets/js/jqBootstrapValidation.js"></script> <script src="<?php echo base_url(); ?>assets/js/contact_me.js"></script> <!-- Custom scripts for this template --> <script src="<?php echo base_url(); ?>assets/js/agency.min.js"></script> </body> </html><file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Penyewaan Aula SMK Telkom Malang</title> <!-- Bootstrap core CSS --> <link href="<?php echo base_url(); ?>assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="<?php echo base_url(); ?>assets/vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'> <!-- Custom styles for this template --> <link href="<?php echo base_url(); ?>assets/css/agency.css" rel="stylesheet"> <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Import materialize.css--> <link href="<?php echo base_url(); ?>assets/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content="widatah=device-widatah, initial-scale=1.0"/> </head> <body> <div class="box-body mdl-cell--12-col"> <table widatah="85%" class="table table-condensed" > <section class="bg-light" id="tim"> <div class="container"> <div class="row"> <div class="mdl-cell--12-col panel panel-default text-center"> <div class="col-lg-12 text-center"> <h2 class="section-heading text-uppercase">Maaf, tanggal yang Anda pilih telah dipesan.</h2> <h3 class="mdl-cell panel panel-default text-center">Silahkan lakukan pemesanan ulang di tanggal lain.</h3> <a href="<?php echo base_url(); ?>home/keluar" class="btn btn-md btn-primary">Tutup</a> <br><br><br><br><br><br><br><br> </div> </div> </div> </div> </section> <script src="<?php echo base_url(); ?>assets/vendor/jquery/jquery.min.js"></script> <script src="<?php echo base_url(); ?>assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Plugin JavaScript --> <script src="<?php echo base_url(); ?>assets/vendor/jquery-easing/jquery.easing.min.js"></script> <!-- Contact form JavaScript --> <script src="<?php echo base_url(); ?>assets/js/jqBootstrapValidation.js"></script> <script src="<?php echo base_url(); ?>assets/js/contact_me.js"></script> <!-- Custom scripts for this template --> <script src="<?php echo base_url(); ?>assets/js/agency.min.js"></script> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="<?php echo base_url(); ?>assets/bootstrap/js/bootstrap.min.js" type="text/javascript"></script> </body> </body> </html> <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class home extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('pesan_model'); //Do your magic here } public function index() { $this->load->view('template_view'); } public function pesan() { if($this->input->post('send')){ $this->form_validation->set_rules('nama_cust','Nama','trim|required'); $this->form_validation->set_rules('telp','Telp','trim|required'); $this->form_validation->set_rules('tanggal','Tanggal','trim|required'); $this->form_validation->set_rules('jam','Jam','trim|required'); $this->form_validation->set_rules('email','Email','trim|required'); $this->form_validation->set_rules('jenis','Jenis Acara','trim|required'); $this->form_validation->set_rules('keterangan','Keterangan','trim'); if($this->form_validation->run() == TRUE){ if (count($this->pesan_model->getcounttgl($this->input->post('tanggal'))) == 0) { if($this->pesan_model->pesan()==TRUE) { $this->load->library('email'); $config = array( 'protocol' => 'smtp', 'smtp_host' => 'ssl://smtp.googlemail.com', 'smtp_port' => 465, //'auth' => TRUE, 'smtp_user' => '<EMAIL>', 'smtp_pass' => '<PASSWORD>', 'mailtype' => 'html', 'wordwrap' => TRUE, ); $this->email->initialize($config); $this->email->set_newline("\r\n"); $this->email->from('<EMAIL>','Administrator Penyewaan Aula SMK Telkom Malang'); $this->email->to($this->input->post('email')); $this->email->subject('Pemesanan Sewa Aula SMK Telkom Malang'); $this->email->message(' <h2>Pemesanan Aula SMK Telkom Anda sudah berhasil! <br>Untuk pertanyaan dan info lebih lanjut silahkan hubungi <b>085102077834</b> - Suko. </h2> <br>Kode Booking anda adalah <h1><b>'.$this->input->post('generatecode').'</b></h1> <br><h3>Terimakasih<br> <br><br>Admin Penyewaan Aula SMK Telkom</h3>'); if ($this->email->send()) { $data['notif'] = 'Validasi sukses'; $data['tanggal'] = $this->input->post('tanggal'); $this->load->view('template_view',$data); $array = array( 'tanggal' => $this->input->post('tanggal') ); $this->session->set_userdata( $array ); redirect('home/pesanpesan'); } else { $data['notif'] = 'Validasi gagal'; $this->load->view('template_view',$data); } }else{ $data['notif'] = 'Validasi gagal'; $this->load->view('template_view',$data); } } else { //disini tempat notif keTika tanggal duplikat $this->load->view('tanggalsama_view'); } }else{ //jika gagal $data['notif'] = validation_errors(); $this->load->view('template_view',$data); } } } public function pesanpesan() { $data['mesen'] = $this->pesan_model->get_data_pesanan_by_tgl($this->session->userdata('tanggal')); $this->load->view('kode_pesanan_view',$data); } function keluar() { $this->session->unset_userdata('tanggal'); redirect('home'); } } /* End of file controllername.php */ /* Location: ./application/controllers/controllername.php */<file_sep><!DOCTYPE html> <html lang="en"> <script type="text/javascript"> $(function(){ $("#tanggal").datepicker({ minDate: 0 }); $('#tanggal').datepicker({dateFormat: 'yy-mm-dd'}); }); </script> <script src="<?php echo base_url(); ?>assets/js/jquery-ui-1.7.2.custom.min.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/js/jquery.validate.min.js" type="text/javascript"></script> <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/sunny/jquery-ui.css" type="text/css" rel="stylesheet"/> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Penyewaan Aula SMK Telkom Malang</title> <!-- Bootstrap core CSS --> <link href="<?php echo base_url(); ?>assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="<?php echo base_url(); ?>assets/vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'> <!-- Custom styles for this template --> <link href="<?php echo base_url(); ?>assets/css/agency.css" rel="stylesheet"> </head> <body id="page-top"> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark fixed-top" id="mainNav"> <div class="container"> <a class="navbar-brand js-scroll-trigger" href="#page-top">SMK Telkom Malang</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> Menu <i class="fa fa-bars"></i> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav text-uppercase ml-auto"> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="#services">Fasilitas</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="#galeri">Galeri</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="#informasi">Informasi</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="#pemesanan">Pemesanan</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="<?php echo base_url(); ?>konfirmasi/">Konfirmasi</a> </li> </ul> </div> </div> </nav> <!-- Header --> <header class="masthead"> <div class="container"> <div class="intro-text"> <div class="intro-lead-in">Selamat Datang!</div> <div class="intro-heading text-uppercase">Persewaan Aula SMK Telkom Malang</div> <a class="btn btn-primary btn-xl text-uppercase js-scroll-trigger" href="#pemesanan">Pesan Sekarang!</a> </div> </div> </header> <!-- Services --> <section id="services"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading text-uppercase">Fasilitas</h2> <h3 class="section-subheading text-muted">Beberapa fasilitas yang disediakan.</h3> </div> </div> <div class="row text-center"> <div class="col-md-4"> <span class="fa-stack fa-4x"> <i class="fa fa-circle fa-stack-2x text-primary"></i> <i class="fa fa-volume-up fa-stack-1x fa-inverse"></i> </span> <h4 class="service-heading">Sound</h4> <p>Sound system beserta 2 microphone</p> </div> <div class="col-md-4"> <span class="fa-stack fa-4x"> <i class="fa fa-circle fa-stack-2x text-primary"></i> <i class="fa fa-users fa-stack-1x fa-inverse"></i> </span> <h4 class="service-heading">Kursi</h4> <p>Kursi lipat sebanyak 150 dan meja 4 set</p> </div> <div class="col-md-4"> <span class="fa-stack fa-4x"> <i class="fa fa-circle fa-stack-2x text-primary"></i> <i class="fa fa-user-secret fa-stack-1x fa-inverse"></i> </span> <h4 class="service-heading">Keamanan</h4> <p>Keamanan dari Binmas, Babinsa dan Security</p> </div> </div> </div> </section> <!-- galeri Grid --> <section class="bg-light" id="galeri"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading text-uppercase">Galeri</h2> <!--<h3 class="section-subheading text-muted">Foto keseluruhan.</h3>--> </div> </div> <div class="row"> <div class="col-md-4 col-sm-6 galeri-item"> <img class="img-fluid" src="<?php echo base_url(); ?>assets/img/galeri/aula3.jpg" alt=""> <div class="galeri-caption"> <h4>Aula SMK Telkom</h4> <p class="text-muted">Tampak depan aula</p> </div> </div> <div class="col-md-4 col-sm-6 galeri-item"> <img class="img-fluid" src="<?php echo base_url(); ?>assets/img/galeri/aula2.jpg" alt=""> <div class="galeri-caption"> <h4>Acara Internal</h4> <p class="text-muted">Kegitan Sekolah di Aula</p> </div> </div> <div class="col-md-4 col-sm-6 galeri-item"> <img class="img-fluid" src="<?php echo base_url(); ?>assets/img/galeri/aula1.jpg" alt=""> <div class="galeri-caption"> <h4>Acara Umum</h4> <p class="text-muted">Kegiatan umum di aula</p> </div> </div> <div class="col-md-4 col-sm-6 galeri-item"> <img class="img-fluid" src="<?php echo base_url(); ?>assets/img/galeri/aula4.jpg" alt=""> <div class="galeri-caption"> <h4>Acara Resepsi</h4> <p class="text-muted">Acara resepsi pernikahan di aula</p> </div> </div> <div class="col-md-4 col-sm-6 galeri-item"> <img class="img-fluid" src="<?php echo base_url(); ?>assets/img/galeri/aula6.jpg" alt=""> <div class="galeri-caption"> <h4>Acara Resepsi</h4> <p class="text-muted">Acara resepsi pernikahan di aula</p> </div> </div> <div class="col-md-4 col-sm-6 galeri-item"> <img class="img-fluid" src="<?php echo base_url(); ?>assets/img/galeri/aula5.jpg" alt=""> <div class="galeri-caption"> <h4>Acara Resepsi</h4> <p class="text-muted">Acara resepsi pernikahan di aula</p> </div> </div> </div> </div> </section> <!-- informasi --> <section id="informasi"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading text-uppercase">Informasi</h2> <h3 class="section-subheading text-muted">Tata cara menyewa gedung ini</h3> </div> </div> <div class="row"> <div class="col-lg-12"> <ul class="timeline"> <li class="timeline-inverted"> <div class="timeline-image"> <!-- <i class="rounded-circle fa fa-file-text-o fa-stack fa-4x fa-inverse"></i> --> <img class="rounded-circle img-fluid" src="<?php echo base_url(); ?>assets/img/about/ideas-icon.png" alt=""> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4>Hal yang wajib diketahui,</h4> <h4 class="subheading">Daftar Harga</h4> </div> <div class="timeline-body"> <p>Even pernikahan : Rp 4.000.000</p> <p>Even sosial : Rp 2.000.000</p> <p>NB: Harga sudah termasuk fasilitas</p> </div> </div> </li> <li> <div class="timeline-image"> <!-- <i class="rounded-circle fa fa-file-text-o fa-stack fa-4x fa-inverse"></i> --> <img class="rounded-circle img-fluid" src="<?php echo base_url(); ?>assets/img/about/icon-forms.png" alt=""> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4>Pertama,</h4> <h4 class="subheading">Isi Form Pemesanan</h4> </div> <div class="timeline-body"> <p>Isilah formulir pemesanan dengan lengkap dan benar kemudian "kirim" form tersebut</p> </div> </div> </li> <li class="timeline-inverted"> <div class="timeline-image"> <!-- <i class="fa fa-check-square-o fa-volume-up fa-stack fa-4x fa-inverse"></i> --> <img class="rounded-circle img-fluid" src="<?php echo base_url(); ?>assets/img/about/form-code.png" alt=""> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4>Kedua,</h4> <h4 class="subheading">Dapatkan Kode Pemesanan</h4> </div> <div class="timeline-body"> <p>Anda selanjutnya akan mendapatkan kode pemesanan setelah mengisi lengkap form yang tersedia, jangan lupa screenshot</p> </div> </div> </li> <li> <div class="timeline-image"> <!-- <i class="fa fa-credit-card fa-volume-up fa-stack fa-4x fa-inverse"></i> --> <img class="rounded-circle img-fluid" src="<?php echo base_url(); ?>assets/img/about/credit-card.png" alt=""> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4>Ketiga,</h4> <h4 class="subheading">Lakukan Pembayaran</h4> </div> <div class="timeline-body"> <p>Lakukan pembayaran ke rekening yang tersedia sesuai harga yang telah ditetapkan</p> <p>Batas maksimal pembayaran 6 hari setelah pemesanan</p> </div> </div> </li> <li class="timeline-inverted"> <div class="timeline-image"> <!-- <i class="fa fa-thumbs-o-up fa-volume-up fa-stack fa-4x fa-inverse"></i> --> <img class="rounded-circle img-fluid" src="<?php echo base_url(); ?>assets/img/about/thumb-up.jpg" alt=""> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4>Keempat,</h4> <h4 class="subheading">Konfirmasi Pembayaran</h4> </div> <div class="timeline-body"> <p>Setelah melakukan transfer, isi form konfirmasi pembayaran di tab "Konfirmasi"</p> <p>Jika ada pertanyaan silahkan hubungi <NAME> (0851-0207-7834)</p> </div> </div> </li> </ul> </div> </div> </div> </section> <!-- Contact --> <section id="pemesanan"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading text-uppercase">Pemesanan</h2> <h3 class="section-subheading text-muted">Untuk memesan silahkan isi formulir di bawah ini.</h3> </div> </div> <div class="row"> <div class="col-lg-12"> <?php if (!empty($notif)) { echo '<div class="alert alert-danger">'; echo $notif; echo '</div>'; } ?> <form method="post" id="target" action="<?php echo base_url();?>home/pesan"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <span class="form-group" style="color: white; font-weight: bold;">Nama Lengkap :</span> <input class="form-control" id="nama" name="nama_cust" type="text" placeholder="Nama Lengkap" required data-validation-required-message="Masukan Nama Lengkap."> <p class="help-block text-danger"></p> </div> <div class="form-group"> <span class="form-group" style="color: white; font-weight: bold;">Nomor Telephone :</span> <input class="form-control" id="tlp" name="telp" type="number" placeholder="Nomor Telepon" required data-validation-required-message="Masukan Nomor Telepon yang bisa dihubungi."> <p class="help-block text-danger"></p> </div> <div class="form-group"> <span class="form-group" style="color: white; font-weight: bold;">Tanggal Pelaksanaan :</span> <input class="form-control" id="datepicker" name="tanggal" type="date" placeholder="Tanggal Acara" required data-validation-required-message="Masukan Tanggal yang akan dipesan."> <p class="help-block text-danger"></p> </div> <div class="form-group"> <span class="form-group" style="color: white; font-weight: bold;">Jam Pelaksanaan :</span> <input class="form-control" id="jam" name="jam" type="time" placeholder="Jam Pelaksanaan" required data-validation-required-message="Masukan Jam yang akan dipesan."> <p class="help-block text-danger"></p> </div> <?php function generateCode(){ $done = 0; do{ $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; $code = ''; for ($i = 0; $i < 7; $i++){ $code .= $characters[mt_rand(0, 61)]; } $done = 1; }while($done != 1); return $code; } $code = generateCode(); ?> <input type="hidden" name="generatecode" value="<?php echo $code;?>"> </div><!-- samllekom --> <div class="col-md-6"> <div class="form-group"> <span style="color: white; font-weight: bold;">Email :</span> <input class="form-control" id="email" name="email" type="email" placeholder="Email" required data-validation-required-message="Masukan Email Anda yang aktif."> <p class="help-block text-danger"></p> </div> <div class="form-group" style="color: white; font-weight: bold;margin-top: -6%"> <br> <label>Jenis Acara :</label><br>&nbsp &nbsp &nbsp <input class="radio" type="radio" name="jenis" value="Acara Umum">Acara Umum &nbsp &nbsp &nbsp &nbsp <input class="radio" type="radio" name="jenis" value="Acara Sosial">Acara Sosial <!-- <select class="form-control" id="jenis_acara" name="jenis"> <option value="" disabled>PILIH JENIS ACARA</option> <option value="acara umum">ACARA UMUM</option> <option value="acara sosial">ACARA SOSIAL</option> </select> --> <p class="help-block text-danger"></p> </div> <div class="form-group" style="margin-top: -4%"> <span style="color: white; font-weight: bold;">Keterangan :</span> <textarea class="form-control" id="ket" name="keterangan" placeholder="Keterangan" rows="1"></textarea> <span class="form-group" style="color: red;"></span> <p class="help-block text-danger"></p> </div> </div> <div class="clearfix"></div> <div class="col-lg-12 text-center"> <div id="success"></div> <input type="submit" name="send" id="other" class="btn btn-primary btn-xl" value="KIRIM" data-toggle="modal" /> </div> </div> </form> </div> </div> </div> </section> <!-- Modal --> <?php if(isset($tanggal)):?> <div class="modal fade" id="myModal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Kode Pemesanan</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Kode Pemesanan Anda : <?php echo generateCode(); ?> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Ok</button> </div> </div> </div> </div> <script> $('#myModal').modal({ show : true}); </script> <?php endif;?> </body> <!-- tim --> <section class="bg-light" id="tim"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading text-uppercase">Tim Pengembang</h2> <h3 class="section-subheading text-muted">Siswa SMK Telkom Malang Kelas 12</h3> </div> </div> <div class="row"> <div class="col-sm-4"> <div class="tim-member"> <img class="mx-auto rounded-circle" src="<?php echo base_url(); ?>assets/img/team/mala.jpg" alt=""> <h5>Nurkumala Budi Fajrin</h5> <br> <!-- <p class="text-muted">Lorem Ipsum</p> --> <ul class="list-inline social-buttons"> <li class="list-inline-item"> <a href="https://www.instagram.com/malbuf/"> <i class="fa fa-instagram"></i> </a> </li> </ul> </div> </div> <div class="col-sm-4"> <div class="tim-member"> <img class="mx-auto rounded-circle" src="<?php echo base_url(); ?>assets/img/team/ridha.jpg" alt=""> <h5><NAME></h5> <br> <!-- <p class="text-muted">Lorem Ipsum</p> --> <ul class="list-inline social-buttons"> <li class="list-inline-item"> <a href="https://www.instagram.com/riridhh/"> <i class="fa fa-instagram"></i> </a> </li> </ul> </div> </div> <div class="col-sm-4"> <div class="tim-member"> <img class="mx-auto rounded-circle" src="<?php echo base_url(); ?>assets/img/team/salsa.jpg" alt=""> <h5><NAME>ingtyas</h5> <br> <!-- <p class="text-muted">Lorem Ipsum</p> --> <ul class="list-inline social-buttons"> <li class="list-inline-item"> <a href="https://www.instagram.com/salspr_/"> <i class="fa fa-instagram"></i> </a> </li> </ul> </div> </div> </div> </div> </section> <!-- Bootstrap core JavaScript --> <script src="<?php echo base_url(); ?>assets/vendor/jquery/jquery.min.js"></script> <script src="<?php echo base_url(); ?>assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Plugin JavaScript --> <script src="<?php echo base_url(); ?>assets/vendor/jquery-easing/jquery.easing.min.js"></script> <!-- Contact form JavaScript --> <script src="<?php echo base_url(); ?>assets/js/jqBootstrapValidation.js"></script> <script src="<?php echo base_url(); ?>assets/js/contact_me.js"></script> <!-- Custom scripts for this template --> <script src="<?php echo base_url(); ?>assets/js/agency.min.js"></script> <script type="text/javascript"> // $("#other").click(function() { // console.log("ayo"); // $("#target").submit(); // }); </script> </body> </html> <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Konfirmasi_model extends CI_Model { public function __construct() { parent::__construct(); //Do your magic here } public function konfirmasi() { $data = array ( 'NAMA_KONFIR' => $this->input->post('nama_konfir'), 'NO_REKENING' => $this->input->post('no_rekening'), 'JML_UANG' => $this->input->post('jml_uang') ); $this->db->where('KD_BOOKING',$this->input->post('kd_booking')) ->update('konfirmasi_pembayaran', $data); if($this->db->affected_rows() > 0) { return TRUE; } else{ return FALSE; } } } /* End of file konfirmasi_model.php */ /* Location: ./application/models/konfirmasi_model.php */<file_sep><!DOCTYPE html> <html> <head> <title>Detil Data Pesanan </title> <link href="<?php echo base_url(); ?>assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="<?php echo base_url(); ?>assets/vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'> <!-- Custom styles for this template --> <link href="<?php echo base_url(); ?>assets/css/agency.css" rel="stylesheet"> <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Import materialize.css--> <link href="<?php echo base_url(); ?>assets/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content="widatah=device-widatah, initial-scale=1.0"/> </head> <body> <div class="container" style="max-width: 800px"><br> <div class="row"> <div class="col-md-12 col-sm-12 col-xs-12 col-lg-12"> <div class=" panel-info"> <div class="panel-heading"><h3 style="text-align: center;">Lihat Detil Data Pesanan</h3></div> <div class="panel-body"> <form action="<?php echo base_url(); ?>admin/update/<?php echo $detil->TANGGAL; ?>" method="post"> <div class="col-md-12 col-sm-12 col-xs-12 col-lg-12"><div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span> <input type="text" id="kd_booking" name="kd_booking" autofocus placeholder="Kode Pemesanan" class="form-control" disabled value="<?php echo $detil->KD_BOOKING ?>"/> </div> <br> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span> <input type="text" id="nama" name="nama" autofocus placeholder="Nama Lengkap" class="form-control" disabled value="<?php echo $detil->NAMA_CUST ?>"/> </div> <br> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-phone"></i></span> <input type="number" id="telp" name="telp" autofocus placeholder="Nomor Telepon" class="form-control" disabled value="<?php echo $detil->TELP ?>"/> </div><br> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-list"></i></span> <input type="text" id="tanggal" name="tanggal" autofocus placeholder="Tanggal" class="form-control" disabled value="<?php echo $detil->TANGGAL?>" /> </div><br> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-list"></i></span> <input type="text" id="jam" name="jam" autofocus placeholder="Jam" class="form-control" disabled value="<?php echo $detil->JAM?>" /> </div><br> <input type="hidden" id="email" name="email" autofocus placeholder="Email" class="form-control" value="<?php echo $detil->email?>" /> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-list"></i></span> <input type="text" id="jenis_acara" name="jenis_acara" autofocus placeholder="Jenis Acara" class="form-control" disabled value="<?php echo $detil->JENIS_ACARA?>" /> </div><br> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-home"></i></span> <textarea id="alamat" name="keterangan" placeholder="Keterangan" class="form-control" disabled><?php echo $detil->KETERANGAN ?></textarea> </div><br> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-list"></i></span> <!-- <input type="select" id="status" name="status" autofocus placeholder="Status" class="form-control" value="<?php echo $detil->STATUS ?>" /> --> <select name="status" id="status" class="form-control" <?php echo $detil->STATUS ?>> <option value="">--Pilih Status--</option> <option value="DP">Belum Lunas</option> <option value="Lunas">Lunas</option> </select> </div> </div> <div class="col-md-12 col-sm-12 col-xs-12 col-lg-12" style="margin-top: 10px; text-align: center;"> <a href="<?php echo base_url(); ?>admin/data_transaksi_pesanan" class="btn btn-md btn-default"> Kembali</a> <input type="submit" name="submit" value="Simpan" class="btn btn-primary"> </div> </form> </div> </div> </div> </div> <br> </div> </body> </html><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class konfirmasi extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('konfirmasi_model'); //Do your magic here } public function index() { $this->load->view('template_konfirmasi'); } public function konfir() { if($this->input->post('send')){ $this->form_validation->set_rules('kd_booking','Kode Booking','trim|required'); $this->form_validation->set_rules('nama_konfir','Nama','trim|required'); $this->form_validation->set_rules('no_rekening','Nomor Rekening','trim|required'); $this->form_validation->set_rules('jml_uang','Jumlah Uang','trim|required'); if($this->form_validation->run() == TRUE){ if($this->konfirmasi_model->konfirmasi()==TRUE) { $this->session->set_flashdata('notif', 'Konfirmasi Pembayaran Anda Berhasil'); redirect('konfirmasi'); }else{ $this->session->set_flashdata('notif', 'Konfirmasi Pembayaran Gagal'); redirect('konfirmasi'); } }else{ //jika gagal $this->session->set_flashdata('notif', validation_errors()); redirect('konfirmasi'); } } } } /* End of file konfirmasi.php */ /* Location: ./application/controllers/konfirmasi.php */<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Admin_model extends CI_Model { public function __construct() { parent::__construct(); //Do your magic here } public function get_notifikasi() { return $this->db->select('count(*) as unread') ->where('read', 'unread') ->get('customer') ->row()->unread; } public function change_read(){ $data = array('read' => 'read'); $this->db->update('customer', $data); if($this->db->affected_rows() >0) { return TRUE; } else { return FALSE; } } public function lihat_batal(){ } function cek_user() { $username = $this->input->post('username'); $password = $this->input->post('<PASSWORD>'); $query = $this->db->where('username', $username) ->where('password', md5($password)) ->get('admin'); if($query->num_rows() > 0) { $data = array( 'username' => $username, 'logged_in' => TRUE ); $this->session->set_userdata($data); return TRUE; } else{ return FALSE; } } function get_data_pesanan() { return $this->db->order_by('customer.TANGGAL','ASC') ->join('konfirmasi_pembayaran', 'konfirmasi_pembayaran.TANGGAL = customer.TANGGAL') ->get('customer') ->result(); } function get_data_pesanan_by_tgl($tanggal) { return $this->db->where('customer.TANGGAL',$tanggal) ->join('konfirmasi_pembayaran', 'konfirmasi_pembayaran.TANGGAL = customer.TANGGAL') ->get('customer') ->row(); } function update_status($tanggal) { $data = array( 'status' => $this->input->post('status') ); $this->db->where('tanggal', $tanggal) ->update('konfirmasi_pembayaran', $data); if($this->db->affected_rows() > 0){ return TRUE; } else { return FALSE; } /*$query = $this->db->get('customer'); $query_result = $query->result(); return $query_result; }*/ // Function To Fetch Selected Student Record /*function update($data){ $this->db->select('*'); $this->db->from('customer'); $this->db->where('tanggal', $data); $query = $this->db->get(); $result = $query->result(); return $result; }*/ // Update Query For Selected Student /*function update_student_id1($id,$data){ $this->db->where('student_id', $id); $this->db->update('students', $data); }*/ // $data = array( // 'status' => $this->input->post('status') // ); // // 'status' => $this->input->post('status'); // //prose insert // $this->db->where('tanggal', $tanggal) // ->update('customer', $data); // //cek apakah berhasil insert data? // if($this->db->affected_rows() > 0){ // return TRUE; // } else { // return FALSE; // } } } /* End of file admin_model.php */ /* Location: ./application/models/admin_model.php */<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Admin extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('admin_model'); } public function index() { if($this->session->userdata('logged_in') == TRUE) { redirect('admin/data_transaksi_pesanan'); } else { $this->load->view('login_view'); } } public function masuk() { if ($this->input->post('submit')) { $this->form_validation->set_rules('username', 'Username', 'trim|required'); $this->form_validation->set_rules('password', '<PASSWORD>', '<PASSWORD>'); if ($this->form_validation->run() == TRUE) { if ($this->admin_model->cek_user() == TRUE) { redirect(base_url('admin/data_transaksi_pesanan')); }else{ $data['notif'] = 'Login Gagal'; $this->load->view('login_view', $data); } } else { $data['notif'] = validation_errors(); $this->load->view('login_view', $data); } } } public function data_transaksi_pesanan() { if($this->session->userdata('logged_in') == TRUE) { //get notifikasi $data['unread'] = $this->admin_model->get_notifikasi(); // $data['main_view'] = 'admin_view'; $data['pesanan'] = $this->admin_model->get_data_pesanan(); $this->load->view('admin_view', $data); } else{ redirect('admin'); } } public function data_pesanan() { if($this->session->userdata('logged_in') == TRUE) { //ubah semua data menjadi read $this->admin_model->change_read(); // $data['main_view'] = 'admin_view'; $data['pesanan'] = $this->admin_model->get_data_pesanan(); $this->load->view('data_pesanan_view', $data); } else{ redirect('admin'); } } function detil_data_pesanan() { if($this->session->userdata('logged_in') == TRUE){ $tanggal = $this->uri->segment(3); $data['detil'] = $this->admin_model->get_data_pesanan_by_tgl($tanggal); $this->load->view('detil_data_pesanan_view',$data); }else{ redirect('admin'); } } public function data_pembayaran() { if($this->session->userdata('logged_in') == TRUE) { // $data['main_view'] = 'admin_view'; $data['pembayaran'] = $this->admin_model->get_data_pesanan(); $this->load->view('data_pembayaran_view', $data); } else{ redirect('admin'); } } public function update() { $tanggal = $this->uri->segment(3); if($this->input->post('submit')){ $this->form_validation->set_rules('status', 'status', 'trim|required'); if ($this->form_validation->run() == TRUE) { /* $data['main_view'] = 'admin_view'; */ $this->load->library('email'); $config = array( 'protocol' => 'smtp', 'smtp_host' => 'ssl://smtp.googlemail.com', 'smtp_port' => 465, //'auth' => TRUE, 'smtp_user' => '<EMAIL>', 'smtp_pass' => '<PASSWORD>', 'mailtype' => 'html', 'wordwrap' => TRUE, ); $this->email->initialize($config); $this->email->set_newline("\r\n"); $this->email->from('<EMAIL>','Administrator Penyewaan Aula SMK Telkom Malang'); $this->email->to($this->input->post('email')); $this->email->subject('Pemesanan Sewa Aula SMK Telkom Malang'); $this->email->message('Pembayaran Anda telah dikonfirmasi oleh Admin dengan status <br><h4><b>LUNAS.</b></h4> Untuk persiapan acara, dapat dilakukan H-1 pelaksanaan. <br>Terimakasih atas kepercayaan anda. <br><br><b>Hormat Kami,</b> <br>Sarana Prasarana SMK Telkom Malang'); if ($this->email->send()) { if($this->admin_model->update_status($tanggal) == TRUE){ $data['unread'] = $this->admin_model->get_notifikasi(); $data['pesanan'] = $this->admin_model->get_data_pesanan(); $data['notif'] = 'Edit Status Berhasil!'; $this->load->view('admin_view', $data); }else{ /* $data['main_view'] = 'admin_view'; */ $data['notif'] = 'Edit Status Gagal!'; $data['unread'] = $this->admin_model->get_notifikasi(); $data['pesanan'] = $this->admin_model->get_data_pesanan(); $this->load->view('data_pesanan_view', $data); } } else { $data['unread'] = $this->admin_model->get_notifikasi(); $data['pesanan'] = $this->admin_model->get_data_pesanan(); $data['notif'] = 'Edit Status Gagal!'; $this->load->view('admin_view', $data); } }else{ /* $data['main_view'] = 'admin_view'; */ $data['notif'] = validation_errors(); $data['unread'] = $this->admin_model->get_notifikasi(); $data['pesanan'] = $this->admin_model->get_data_pesanan(); $this->load->view('admin_view', $data); } } } /* public function data_pembatalan() { if($this->session->userdata('logged_in') == TRUE) { // $data['main_view'] = 'admin_view'; $data['pembatalan'] = $this->admin_model->lihat_batal(); $this->load->view('data_pembatalan_view', $data); } else{ redirect('admin'); } } public function data_history() { if($this->session->userdata('logged_in') == TRUE) { // $data['main_view'] = 'admin_view'; $data['history'] = $this->admin_model->get_data_pesanan(); $this->load->view('data_history_view', $data); } else{ redirect('admin'); } }*/ public function logout() { $data = array( 'username' => '', 'logged_in' => FALSE ); $this->session->sess_destroy(); redirect(base_url('admin')); } } /* End of file admin.php */ /* Location: ./application/controllers/admin.php */<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Pesan_model extends CI_Model { public function __construct() { parent::__construct(); //Do your magic here } public function pesan() { $data = array ( 'NAMA_CUST' => $this->input->post('nama_cust'), 'KD_BOOKING' => $this->input->post('generatecode'), 'TELP' => $this->input->post('telp'), 'TANGGAL' => $this->input->post('tanggal'), 'JAM' => $this->input->post('jam'), 'email' => $this->input->post('email'), 'JENIS_ACARA' => $this->input->post('jenis'), 'KETERANGAN' => $this->input->post('keterangan') ); $this->db->insert('customer', $data); $object = array( 'KD_BOOKING' => $this->input->post('generatecode'), 'TANGGAL' => $this->input->post('tanggal') ); $this->db->insert('konfirmasi_pembayaran',$object); if($this->db->affected_rows() > 0) { return TRUE; } else{ return FALSE; } } function get_data_pesanan() { //untuk kode_pesanan_view return $this->db->order_by('customer.TANGGAL','ASC') ->join('konfirmasi_pembayaran', 'konfirmasi_pembayaran.TANGGAL = customer.TANGGAL') ->get('customer') ->result(); } function get_data_pesanan_by_tgl($tanggal) { return $this->db->where('customer.TANGGAL',$tanggal) ->get('customer') ->row(); } function getcounttgl($tgl) { return $this->db->where('TANGGAL', $tgl) ->get('customer') ->result(); } } /* End of file pesan_model.php */ /* Location: ./application/models/pesan_model.php */<file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Penyewaan Aula SMK Telkom Malang</title> <!-- Bootstrap core CSS --> <link href="<?php echo base_url(); ?>assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="<?php echo base_url(); ?>assets/vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'> <!-- Custom styles for this template --> <link href="<?php echo base_url(); ?>assets/css/agency.css" rel="stylesheet"> <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Import materialize.css--> <link href="<?php echo base_url(); ?>assets/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content="widatah=device-widatah, initial-scale=1.0"/> </head> <body> <section class="bg-light" id="tim"> <div class="container"> <div class="row"> <!-- <div class="mdl-cell--12-col panel panel-default text-center"> </div> --> <div class="col-lg-12 text-center"> <h2 style="color: grey" class="section-heading text-uppercase">Screenshoot! Catat Kode Booking!</h2> <a>Transfer ke no rekening <a style="color: red;">BTN 93509930000011100</a> A/n TS-SMK TELKOM MALANG</a> <br><p> </p> </div> </div> <div class="row"> <table widatah="85%" class="table table-condensed text-center" > <thead> <tr> <th>Nama</th> <th>Kode Booking</th> <th>Nomor Telepon</th> <th>Tanggal</th> <th>Jam</th> <th>Jenis Acara</th> <th>Keterangan</th> </tr> </thead> <tbody> <tr><td><?php echo $mesen->NAMA_CUST; ?></td> <td style="color: red"><?php echo $mesen->KD_BOOKING; ?></td> <td><?php echo $mesen->TELP; ?></td> <td><?php echo $mesen->TANGGAL; ?></td> <td><?php echo $mesen->JAM; ?></td> <td><?php echo $mesen->JENIS_ACARA; ?></td> <td><?php echo $mesen->KETERANGAN; ?></td> </tr> </tbody> </table> </div> <center> <h4>Batas waktu transfer maksimal 6 hari setelah mendapat kode booking</h4> <h4 style="color:red;">Silahkan cek email anda untuk melihat kode <i>booking</i></h4><br> <a href="<?php echo base_url(); ?>home/keluar" class="btn btn-md btn-primary">Tutup</a> </center> </div> </section> <script src="<?php echo base_url(); ?>assets/vendor/jquery/jquery.min.js"></script> <script src="<?php echo base_url(); ?>assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Plugin JavaScript --> <script src="<?php echo base_url(); ?>assets/vendor/jquery-easing/jquery.easing.min.js"></script> <!-- Contact form JavaScript --> <script src="<?php echo base_url(); ?>assets/js/jqBootstrapValidation.js"></script> <script src="<?php echo base_url(); ?>assets/js/contact_me.js"></script> <!-- Custom scripts for this template --> <script src="<?php echo base_url(); ?>assets/js/agency.min.js"></script> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="<?php echo base_url(); ?>assets/bootstrap/js/bootstrap.min.js" type="text/javascript"></script> </body> </body> </html> <file_sep>8<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Penyewaan Aula SMK Telkom Malang</title> <link href="<?php echo base_url(); ?>assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="<?php echo base_url(); ?>assets/vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'> <!-- Custom styles for this template --> <link href="<?php echo base_url(); ?>assets/css/agency.css" rel="stylesheet"> <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Import materialize.css--> <link href="<?php echo base_url(); ?>assets/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content="widatah=device-widatah, initial-scale=1.0"/> </head> <body id="page-top"> <!-- Navigation --> <body id="page-top" class="bg-light"> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark fixed-top" id="mainNav"> <div class="container"> <a href="<?php echo base_url(); ?>admin/data_transaksi_pesanan/" class="btn btn-md btn-primary">Kembali</a> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav text-uppercase ml-auto"> <li class="nav-item"> <a class="js-scroll-trigger" href="<?php echo base_url(); ?>admin/logout">Keluar</a> </li> </ul> </div> </div> </nav> <?php $notif = $this->session->flashdata('notif'); if(!empty($notif)){ echo ' <div class="alert alert-danger"> '.$notif.' </div> '; } ?> <section id="admin_view"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading text-uppercase">Data Pembatalan</h2> </div> </div> <div class="row"> <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-body"> <div class="table-responsive"> <table class="table table-striped"> <thead> <tr> <th>Nama Pemesan</th> <th>Kode Booking</th> <th>Nomor Telepon</th> <th>Tanggal</th> <th>Jam</th> <th>Jenis Acara</th> <th>Keterangan</th> </tr> </thead> <tbody> <?php foreach ($pemba as $data) { echo' <tr> <td>'.$data->NAMA_CUST.'</td> <td>'.$data->KD_BOOKING.'</td> <td>'.$data->TELP.'</td> <td>'.$data->TANGGAL.'</td> <td>'.$data->JAM.'</td> <td>'.$data->JENIS_ACARA.'</td> <td>'.$data->KETERANGAN.'</td> </tr> '; } ?> </tbody> </table> </div> </div> </div> </div> </div> </div> </section> <script src="<?php echo base_url(); ?>assets/vendor/jquery/jquery.min.js"></script> <script src="<?php echo base_url(); ?>assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Plugin JavaScript --> <script src="<?php echo base_url(); ?>assets/vendor/jquery-easing/jquery.easing.min.js"></script> <!-- Contact form JavaScript --> <script src="<?php echo base_url(); ?>assets/js/jqBootstrapValidation.js"></script> <script src="<?php echo base_url(); ?>assets/js/contact_me.js"></script> <!-- Custom scripts for this template --> <script src="<?php echo base_url(); ?>assets/js/agency.min.js"></script> </body> </html>
f750039cf74cbc8ab4d562f9aac4877434a453ea
[ "SQL", "PHP" ]
13
SQL
salsapr/ProjectWork
488be55658b9a484d42d84777192bdd58ab2cdc3
80212ffcc3b759434f0d8633b9ac4f602192d987
refs/heads/main
<file_sep>const { body } = require('express-validator'); const authValidation = [ body('email').isEmail().withMessage('This is not valid email format'), body('password') .isLength({ min: 6 }) .withMessage('Your password should be more than 5 characters'), ]; module.exports = authValidation;
274c4ffccc984d0d3f6df8d4e94f9a4f41e00b7a
[ "JavaScript" ]
1
JavaScript
zulfikarrosadi/node-auth-jwt-prisma
82d44b44839572bd19c2b7b795d2913b64d6e601
c5a2d5eb35496407657eb53b6cbdce514a07eb87
refs/heads/master
<file_sep>Banking cat is a project built for McMaster University's Hackathon DeltaHack V. It is a bank statement analysis website featured by a Chatbot. Utilized technologies include backend server on Google Cloud, Natural Language Processing, Javascript, HTML, CSS and Bootstrap. ![gallery](https://user-images.githubusercontent.com/35947890/55677991-25e41c80-58a7-11e9-919a-31873464d54b.jpg) <file_sep>var request = require('request'); var querystring = require('querystring'); var form = { number1: 'TD', number2: 'CIBC', number3: 'RBC', number4: 'CICS' }; var formData = querystring.stringify(form); var contentLength = formData.length; request({ headers: { 'Content-Length': contentLength, 'Content-Type': 'form-data' }, uri: 'http://localhost:8081', body: formData, method: 'POST' }, function (err, res, body) { console.log(res.body); });<file_sep># function for responses def results(): # build a request object req = request.get_json(force=True) # fetch action from json action = req.get('queryResult').get('action') # return a fulfillment response return {'fulfillmentText': 'This is a response from webhook.'} # create a route for webhook @app.route('/webhook', methods=['GET', 'POST']) def webhook(): # return response return make_response(jsonify(results()))
76a72d0cf8fbcf6a09ab3b5b77d7fceaefa575dd
[ "Markdown", "Python", "JavaScript" ]
3
Markdown
Helinia/deltahack-project-helena
d1120ad3a9de3835e25ed9348df808fbaafc0448
8ee2fbb77e47b68aa06d2f6cd8cda8202b5d8491
refs/heads/master
<repo_name>allknowingfrog/smashy<file_sep>/README.md # Encode/Decode (Code Camp) Project for 2017 [Try it!](https://allknowingfrog.github.io/smashy) <file_sep>/main.js var canvas; var context; var player; var zombieSprites = new Image(); var wallSprite = new Image(); var enemies = []; var bullets = []; var walls = []; var inputs = { left: false, up: false, right: false, down: false, click: false }; var mx; var my; var timestamp; var SPEED = 30; var SIZE = 20; var XSIZE = 30; var YSIZE = 20; var ACC = 1000; //acceleration per second var DCC = 2; var COOL = .5; var SPAWN = 2; var ENEMY_RAND = .33; var DELTA_MAX = .1; var coolTimer = 0; var spawnTimer = 0; var score = 0; var playing; var map = " X " + " X X " + " X " + " XXX X X " + " " + " xxxxxx X X X " + " x X X " + " x X X " + " x x X X X " + " x X X X " + " xxxxx X X " + " X X " + " X X X " + " " + " " + " " + " XXXXXXXXXXXXXXXXXXXXXXXXX " + " " + " " + " " ; function init() { canvas = document.getElementById('canvas'); canvas.width = SIZE * XSIZE; canvas.height = SIZE * YSIZE; context = canvas.getContext('2d'); zombieSprites.src = 'zombies.png'; wallSprite.src = 'wall.png'; document.addEventListener('keydown', keyDown, false); document.addEventListener('keyup', keyUp, false); document.addEventListener('mousedown', mouseDown, false); document.addEventListener('mouseup', mouseUp, false); document.addEventListener('mousemove', mouseMove, false); player = new Entity(0, 0, 'red'); reset(); } function reset() { playing = true; enemies = []; bullets = []; player.x = 0; player.y = 0; score = 0; for(var x=0; x<XSIZE; x++) { walls[x] = []; for(var y=0; y<YSIZE; y++) { if(map.substr(y * XSIZE + x, 1) !== ' ') { walls[x][y] = new Entity(x * SIZE, y * SIZE, 'brown'); } else { walls[x][y] = null; } } } timestamp = Date.now(); gameLoop(); } function gameLoop() { var now = Date.now(); var delta = (now - timestamp) / 1000; timestamp = now; if(delta > DELTA_MAX) delta = DELTA_MAX; if(inputs.left) { player.vx -= ACC * delta; } else if(inputs.right) { player.vx += ACC * delta; } else { player.vx -= player.vx * DCC * delta; } if(inputs.up) { player.vy -= ACC * delta; } else if(inputs.down) { player.vy += ACC * delta; } else { player.vy -= player.vy * DCC * delta; } if(inputs.click && coolTimer <= 0) { var dx = mx - player.getMidX(); var dy = my - player.getMidY(); var total = Math.abs(dx) + Math.abs(dy); var bullet = new Entity(0, 0, 'blue'); bullet.size /= 4; bullet.setMidX(player.getMidX()); bullet.setMidY(player.getMidY()); bullet.max *= 6; bullet.vx = dx / total * bullet.max; bullet.vy = dy / total * bullet.max; bullets.push(bullet); coolTimer = COOL; } else if(coolTimer > 0) { coolTimer -= delta; } player.update(delta); if(enemies.length < 1 && spawnTimer <= 0) { var enemy = new Entity(0, 0, 'green'); /* do { enemy.x = Math.floor(Math.random() * canvas.width - SIZE); enemy.y = Math.floor(Math.random() * canvas.height - SIZE); } while( Math.abs(player.x - enemy.x) < SIZE * 4 || Math.abs(player.y - enemy.y) < SIZE * 4 ); */ enemy.setMidX(canvas.width / 2); enemy.setMidY(canvas.height / 2); enemies.push(enemy); spawnTimer = SPAWN; } else if(spawnTimer > 0) { spawnTimer -= delta; } var enemy, dx, dy, total; for(var i=0; i<enemies.length; i++) { enemy = enemies[i]; dx = player.x - enemy.x; dy = player.y - enemy.y; if(ENEMY_RAND > Math.random()) dx *= -1; else if(ENEMY_RAND > Math.random()) dy *= -1; total = Math.abs(dx) + Math.abs(dy); enemy.vx += (dx / total) * ACC * delta; enemy.vy += (dy / total) * ACC * delta; enemy.update(delta); } for(var i=0; i<enemies.length; i++) { for(var n=0; n<enemies.length; n++) { if(i == n) continue; if(collides(enemies[i], enemies[n])) { resolve(enemies[i], enemies[n]); } } } for(var i=bullets.length-1; i>=0; i--) { if(bullets[i].update(delta)) { bullets.splice(i, 1); } else { for(var n=enemies.length-1; n>=0; n--) { if(collides(bullets[i], enemies[n])) { enemies.splice(n, 1); bullets.splice(i, 1); score += 10; break; } } } } for(var i=0; i<enemies.length; i++) { enemy = enemies[i]; if(collides(player, enemy)) { resolve(player, enemy); //playing = false; } } hitWalls(player); for(var i=0; i<enemies.length; i++) { hitWalls(enemies[i]); } for(var i=bullets.length-1; i>=0; i--) { if(hitWalls(bullets[i], true)) { bullets.splice(i, 1); } } context.clearRect(0, 0, canvas.width, canvas.height); context.drawImage( zombieSprites, 2, 44, 24, 26, player.x, player.y, player.size, player.size ); for(var i=0; i<enemies.length; i++) { context.drawImage( zombieSprites, 87, 45, 16, 23, enemies[i].x, enemies[i].y, enemies[i].size, enemies[i].size ); } for(var i=0; i<bullets.length; i++) { bullets[i].draw(); } for(var x=0; x<XSIZE; x++) { for(var y=0; y<YSIZE; y++) { if(walls[x][y]) { context.drawImage( wallSprite, walls[x][y].x, walls[x][y].y, walls[x][y].size, walls[x][y].size ); } } } context.font = 'bold 18px monospace'; context.fillStyle = 'white'; context.fillText(score, canvas.width - 50, 40); if(playing) { window.requestAnimationFrame(gameLoop); } else { context.textAlign = 'center'; context.textBaseline = 'middle'; context.fillText('SPACE to start', canvas.width / 2, canvas.height / 2); } } function keyDown(e) { e.preventDefault(); switch(e.keyCode) { case 37: case 65: inputs.left = true; break; case 38: case 87: inputs.up = true; break; case 39: case 68: inputs.right = true; break; case 40: case 83: inputs.down = true; break; case 32: if(!playing) reset(); break; } } function keyUp(e) { e.preventDefault(); switch(e.keyCode) { case 37: case 65: inputs.left = false; break; case 38: case 87: inputs.up = false; break; case 39: case 68: inputs.right = false; break; case 40: case 83: inputs.down = false; break; } } function mouseMove(e) { var rect = canvas.getBoundingClientRect(); mx = e.pageX - rect.left; my = e.pageY - rect.top; } function mouseDown(e) { inputs.click = true; } function mouseUp(e) { inputs.click = false; } function collides(a, b) { if(a.getRight() < b.getLeft()) return false; if(a.getBottom() < b.getTop()) return false; if(a.getLeft() > b.getRight()) return false; if(a.getTop() > b.getBottom()) return false; return true; } function hitWalls(obj, bullet) { var xx = Math.floor(obj.x / SIZE); var yy = Math.floor(obj.y / SIZE); if(xx < 0) xx = 0; if(yy < 0) yy = 0; var hit = false; for(var x=xx; x<=xx+1; x++) { if(x >= XSIZE) continue; for(var y=yy; y<=yy+1; y++) { if(y >= YSIZE) continue; if(walls[x][y] && collides(obj, walls[x][y])) { hit = true; if(bullet) { walls[x][y] = null; } else { shove(walls[x][y], obj, true); } } } } return hit; } function shove(a, b, wall) { var dx = b.x - a.x; var dy = b.y - a.y; var dxAbs = Math.abs(dx); var dyAbs = Math.abs(dy); var move; if(dxAbs > dyAbs) { move = wall ? 0 : b.size - dxAbs; if(b.x > a.x) { a.x -= move / 2; b.setLeft(a.getRight()); } else { a.x += move / 2; b.setRight(a.getLeft()); } } else { move = wall ? 0 : b.size - dyAbs; if(b.y > a.y) { a.y -= move / 2; b.setTop(a.getBottom()); } else { a.y += move / 2; b.setBottom(a.getTop()); } } } function resolve(a, b) { var vx = b.vx - a.vx; var vy = b.vy - a.vy; if(!vx && !vy) return; var dx = b.x - a.x; var dy = b.y - a.y; console.log('>>>'); console.log('vx: ' + vx + ', vy: ' + vy + ', dx: ' + dx + ', dy: ' + dy); var dist = a.size / 2 + b.size / 2; if(vx > 0 && dx > 0) { dx = -dx - dist; console.log('here'); } else if(vx < 0 && dx < 0) { dx = -dx + dist; console.log('here'); } if(vy > 0 && dy > 0) { dy = -dy - dist; console.log('here'); } else if(vy < 0 && dy < 0) { dy = -dy + dist; console.log('here'); } //console.log('vx: ' + vx + ', vy: ' + vy + ', dx: ' + dx + ', dy: ' + dy); var dx_delta; var dy_delta; var delta; if(vx) dx_delta = dx / vx; if(vy) dy_delta = dy / vy; if(!vy || dx_delta > dy_delta) { delta = dx_delta / 2; if(delta < -DELTA_MAX) delta = -DELTA_MAX; a.update(delta); b.update(delta); //a.vx *= -1; //b.vx *= -1; } else { delta = dy_delta / 2; if(delta < -DELTA_MAX) delta = -DELTA_MAX; a.update(delta); b.update(delta); //a.vy *= -1; //b.vy *= -1; } console.log(delta); if(isNaN(delta)) playing = false; //a.update(-delta); //b.update(-delta); }
eeb180c4dea485602a5354750a1d105540755e22
[ "Markdown", "JavaScript" ]
2
Markdown
allknowingfrog/smashy
b2fbd20a14daefd99dcd10f0303aea4a465a8ef9
892b86421a1ad73c4563d3b3c8289c2c3430b4f5